diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a629fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# virtual environment folder +venv*/ +# compiled bytecode +**/__pycache__/ +**/*.pyc +# Simulation result folders +**/batch_202* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md index c725606..3d45ce0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,58 @@ -# OS_ORIGAME -ORIGAME is a Python-based discrete event modelling and simulation environment. It has a full-featured graphical user interface (GUI) in which users build models and run Monte Carlo simulations. +# ORIGAME +Private repository for ORIGAME simulation software. + +This repository was created for a Government of Canada contract to update the ORIGAME code base. + +(c) Her Majesty the Queen in Right of Canada + +## LICENSE +See LICENSE file. + +## RECOMMENDED INSTALLATION + +These instructions are for running ORIGAME on python 3.8 and 3.11 + +1. Install Python 3.8.10 (python-3.8.10-amd64.exe) + - https://www.python.org/downloads/release/python-3810/ + +2. Install Python 3.11.2 (python-3.11.2-amd64.exe) + - https://www.python.org/downloads/release/python-3112/ + +3. Install Visual C++ Redistributable for Visual Studio 2015 (vc_redist.x64.exe) + - https://www.microsoft.com/en-ca/download/details.aspx?id=48145 + +4. Clone or download ORIGAME to a project folder on your system + +5. From the project folder, create a virtual environment for ORIGAME for each Python version + - e.g. `C:\Python38\python -m venv venv8` + - e.g. `C:\Python311\python -m venv venv11` + +6. Activate a virtual environment and install dependencies in "requirements.txt". Deactivate the virtual environment +if not in use. + - `venv11\Scripts\activate` + - `pip install -r requirements.txt` + - `deactivate` + +7. Activate the desired virtual environment, and launch ORIGAME GUI. + - `venv11\Scripts\activate` + - `py .\origame_gui.py` + +Visit this [this page](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment) for more information about virtual environments. + +## DOCUMENTATION + +The ORIGAME User Manual and ORIGAME Tutorial documents are located in the /origame/docs folder. + +## TESTING + +A number of test scenarios and run procedures are provided in the /testing folder. + +These test scenarios constitute Government Supplied Material 2 (GSM 2), referred to in the task Statement of Work. + +## CONTACT + +Stephen Okazawa
+Defence Scientist
+Defence Research and Development Canada
+stephen.okazawa@forces.gc.ca
+ diff --git a/origame/LICENSE.txt b/origame/LICENSE.txt new file mode 100644 index 0000000..d31a61a --- /dev/null +++ b/origame/LICENSE.txt @@ -0,0 +1,60 @@ +************************ +ORIGAME SOFTWARE LICENSE +************************ + + +Ownership and Administration +============================ + +The ORIGAME software and all accompanying documentation and material (hereinafter +called "the Software") are subject to copyright, with all rights reserved to Her +Majesty the Queen in Right of Canada. + +The Software is administered by Defence Research & Development Canada (DRDC), located at +60 Moodie Drive, Ottawa, Ontario, K1A 0K2. + + +Approved Users +============== + +The Software may only be used by the following individuals (hereinafter called "Approved Users"): + +1. Employees of the Government of Canada. + +2. Contractors that are currently engaged in a contract with the Government of + Canada and that have a requirement to use the Software in the execution of their work + for the Government of Canada. + +Individuals other than Approved Users may not use the Software and must destroy any copies of the +Software in their possession unless they have obtained prior written permission from DRDC to use +the Software. + + +Approved Use +============ + +Users of the Software must adhere to the following restrictions regarding their use +of the Software (herinafter called "Approved Use"): + +1. The Software must only be used to support the execution of work + for the Government of Canada. + +2. The Software must not be modified without prior written permission from DRDC. + +3. The Software must not be provided to others unless the recipients are + Approved Users and their use of the Software adheres with the Approved Use. + +4. Contractors must further adhere to the terms of their contract with the + Government of Canada with respect to their use of the Software. + + +Contact +======= + + Stephen Okazawa + Defence Scientist, DRDC + 101 Colonel By Drive, Ottawa, Ontario, K1A 0K2 + Tel.: (613) 901-9772 + E-mail: stephen.okazawa@forces.gc.ca + + diff --git a/origame/__init__.py b/origame/__init__.py new file mode 100644 index 0000000..5c431a9 --- /dev/null +++ b/origame/__init__.py @@ -0,0 +1,25 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: This package provides functionality related to running either variant of +the Origame application. + +Version History: See SVN log. +""" + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5788$" + +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- PUBLIC API --------------------------------------------------------------------------------- +# import *public* symbols (classes/functions/constants) from contained modules: diff --git a/origame/batch_sim/__init__.py b/origame/batch_sim/__init__.py new file mode 100644 index 0000000..12531e5 --- /dev/null +++ b/origame/batch_sim/__init__.py @@ -0,0 +1,28 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: This package provides functionality related to batch simulations in either variant of Origame. + +Version History: See SVN log. +""" + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5788$" + +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- PUBLIC API --------------------------------------------------------------------------------- +# import *public* symbols (classes/functions/constants) from contained modules: + +from .batch_sim_manager import BatchSimManager, BatchSimSettings, BsmStatesEnum, BatchDoneStatusEnum +from .batch_sim_manager import MIN_REPLIC_ID, MIN_VARIANT_ID +from .seed_table import SeedTable diff --git a/origame/batch_sim/batch_sim_manager.py b/origame/batch_sim/batch_sim_manager.py new file mode 100644 index 0000000..84c2397 --- /dev/null +++ b/origame/batch_sim/batch_sim_manager.py @@ -0,0 +1,1339 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Batch simulation management + +The BatchSimManager has a state machine which uses a simple pattern: the BSM has a *state* data member which +gets initialized to a new instance of one of the state classes every time there is a state transition. +Each state class knows when to transition out, and what state to transition to, but does not know if the +target state is allowed. So the target state is first created, and if succesful, the "from" state +sets the BSM to point to the new state, and gets discarded. Otherwise, the from state remains the current +state. The state classes only implement the behavior that is supported in the given state; since the BSM +simply forwards state-dependent calls to the current state object, an exception will get raised if the +current state does not support the required operation. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import functools +import logging +import multiprocessing as mp +import shutil +import time +import json +from datetime import datetime, timedelta +from enum import IntEnum +from pathlib import Path +from copy import deepcopy +from textwrap import dedent +from threading import current_thread + +# [2. third-party] + +# [3. local] +from ..core import BridgeEmitter, BridgeSignal, safe_slot, BaseFsmState, IFsmOwner, LogCsvFormatter +from ..core import internal, override, get_enum_val_name, AppSettings +from ..core.typing import Any, Either, Optional, List, Tuple, Sequence, Set, Dict, Iterable, Callable, PathType +from ..core.typing import AnnotationDeclarations +from ..scenario import ScenarioManager, Scenario, SimSteps +from ..scenario import create_batch_data_file, get_db_path, BatchDataMgr, DataPathTypesEnum, BATCH_TIMESTAMP_FMT +from ..scenario.defn_parts import RunRolesEnum + +from .bg_replication import ReplicSimState, BatchSetup, ReplicSimConfig, ReplicStatusEnum, ReplicationError +from .bg_replication import run_bg_replic, get_replic_path, ReplicExitReasonEnum +from .seed_table import SeedTable, MIN_VARIANT_ID, MIN_REPLIC_ID + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # public API of module + 'BatchSimManager', + 'BatchSimSettings', + 'BsmStatesEnum' + 'BatchDoneStatusEnum', + 'get_num_cores_actual', +] + +log = logging.getLogger('system') + + +class Decl(AnnotationDeclarations): + BatchSimSettings = 'BatchSimSettings' + + +# -- Function definitions ----------------------------------------------------------------------- + +def get_num_cores_actual(cores_wanted: int, total_num_replics: int) -> int: + """ + Get the actual number of cores that will be used at the beginning of the batch sim run. + :param cores_wanted: number of cores the user wants + :param total_num_replics: total number of replications that will be run + """ + num_cores_avail = mp.cpu_count() + if cores_wanted == 0: + # if cores=0, will use all available: + return min(num_cores_avail, total_num_replics) + else: + # if specified, can only use as many as are available, or the total replications, whichever is smaller: + return min(num_cores_avail, total_num_replics, cores_wanted) + + +# -- Class Definitions -------------------------------------------------------------------------- + +class BatchDoneStatusEnum(IntEnum): + not_started, in_progress, paused, aborted, completed = range(5) + + +class BsmStatesEnum(IntEnum): + """ + Enumerate the various states available to the Batch Sim Manager + """ + ready, running, paused, done = range(4) + + +# noinspection PyProtectedMember +class _BsmStateReady(BaseFsmState): + """ + The only thing that can be done while in READY state is to set the scenario path, load seeds from another + file, and start the batch sim. + + plantuml + """ + + state_id = BsmStatesEnum.ready + + def __init__(self, prev_state: BaseFsmState = None, fsm_owner: IFsmOwner = None): + super().__init__(prev_state, fsm_owner=fsm_owner) + + bsm = self._fsm_owner + bsm._reset_run_time() + + if prev_state is not None: + new_path = prev_state.scen_path_when_ready + if new_path is not None: + self.set_scen_path(new_path) + bsm.signals.sig_replication_done.emit(0, 0) + + def get_completion_status(self) -> BatchDoneStatusEnum: + return BatchDoneStatusEnum.not_started + + def start(self): + """Start the sim: transitions to RUNNING""" + self._set_state(BsmStateClasses.RUNNING) + + def set_scen_path(self, new_path: str): + """ + Set the scenario file path that will be used by each replication of a batch. + :param value: scenario file path + """ + log.info("BSM (ready) switching to scenario path '{}'", new_path) + self._fsm_owner._scen_path = None if new_path is None else Path(new_path) + + def set_cores_wanted(self, num_cores: int): + """ + It only makes sense to change the cores wanted in READY state. The actual number of cores that will be used + depends on how many available, and whether the user wants "all" or a specific #. + """ + # Oliver TODO build 3: add test for this + self._fsm_owner._settings.num_cores_wanted = num_cores + + +class CapturesNextReadyScenPath: + """ + The path of a loaded scenario can change at any time, but the path used by a running batch sim cannot + change. I.e., the scenario path as seen by the batch sim manager can only change while in the Ready state. + So all non-ready BSM states derive from this class to capture any scenario path change, so that it can be + "applied" later when BSM returns to its Ready state. + """ + + def __init__(self): + self.__scen_path_when_ready = None + + def set_scen_path(self, new_path: str): + """Scenario Path cannot change outside of ready state, but capture so next ready state can use it.""" + log.info("BSM ({}) save new scenario path '{}' for next Ready state", self._fsm_owner.state_name, new_path) + self.__scen_path_when_ready = new_path + + @property + def scen_path_when_ready(self) -> Either[str, None]: + """If the scenario path changed outside of the READY state, this will contain its value""" + return self.__scen_path_when_ready + + +# noinspection PyProtectedMember +class _BsmStateRunning(BaseFsmState, CapturesNextReadyScenPath): + """ + When entering the RUNNING state from READY, the batch folder is created, and + replications are queued and executed in parallel on a specified number of cores. + The final exit condition of each replicatoin is recorded by the BatchMonitor. Once + all replications have ended, the BSM automatically transitions to DONE. + + NOTE: the init will raise an exception if some preconditions for entering the state + are not satisfied, such as the scenario never having been saved (where would the batch sim + results go?). + + When entering the RUNNING state from PAUSED, there is no much to do except get a reference + to BatchMonitor from the previous state. + """ + + state_id = BsmStatesEnum.running + + def __init__(self, prev_state: BaseFsmState, + fsm_owner: IFsmOwner = None, + batch_log_file_handler: logging.Handler = None): + """Creates the shared memory manager and pool and initializes replications array and results. + :param fsm_owner: owning object of this state machine state + :param prev_state: the state object from which BSM transitioning""" + BaseFsmState.__init__(self, prev_state, fsm_owner=fsm_owner) + CapturesNextReadyScenPath.__init__(self) + self.__log_file_handler = batch_log_file_handler + self._results_scen_path = None + + # check any pre-conditions else + if self._fsm_owner.scen_path is None: + raise RuntimeError('Must save scenario before RUNNING') + + settings = self._fsm_owner._settings + if settings.auto_seed: + assert settings.seed_table is None + self.__seed_table = SeedTable(settings.num_variants, settings.num_replics_per_variant) + else: + self.__seed_table = settings.seed_table + + # ok, init: + if prev_state.state_id == BsmStatesEnum.ready: + # if previously ready, setup for running + self._batch_mon = None + + self._mp_manager = mp.Manager() + self._sim_state = ReplicSimState(self._mp_manager) + self._worker_pool = None + + self._batch_scen_path = None + self._batch_data = None + + elif prev_state.state_id == BsmStatesEnum.paused: + # if previously paused, copy state's data + self._batch_mon = prev_state._batch_mon + + self._mp_manager = prev_state._mp_manager + self._sim_state = prev_state._sim_state + self._worker_pool = prev_state._worker_pool + + self._batch_scen_path = prev_state._batch_scen_path + self._batch_data = prev_state._batch_data + + else: + raise NotImplementedError('Invalid previous state specified for _BsmStateRunning initialization.') + + self._sim_state.paused.value = False + + @override(BaseFsmState) + def enter_state(self, prev_state: BaseFsmState): + """ + Entering the RUNNING state must be done separately from object init, because when the state is entered, + it queues (if entered from READY) concurrent processes to be run for this batch. + Without this separation, replications could complete before the BSM has the new state object as state. + """ + if prev_state.state_id != BsmStatesEnum.ready: + # nothing else to do: + return + + # so the previous state was ready, setup the batch environment + assert self._sim_state.paused.value is False + + bsm = self._fsm_owner + settings = bsm._settings + total_num_replics = settings.num_variants * settings.num_replics_per_variant + num_cores_actual = get_num_cores_actual(settings.num_cores_wanted, total_num_replics) + + assert self.__log_file_handler is None + batch_folder = self.__create_batch_folder(settings.num_variants, settings.num_replics_per_variant) + self.__save_seed_file(batch_folder) + self.__copy_scenario_snapshot(batch_folder) + + # create the monitor of replication processes + self._batch_mon = BatchMonitor(bsm, batch_folder, num_cores_actual) + create_batch_data_file(batch_folder) + + # create the settings dict that is common to all replications: + sim_steps = settings.replic_steps + if sim_steps is None: + sim_steps = bsm.get_scen_sim_steps() + batch_setup = BatchSetup(bsm.scen_path, batch_folder, sim_steps, settings.save_scen_on_exit, + **bsm._app_settings) + + # queue a work item for each replication (NxM replications) + self._worker_pool = mp.Pool(num_cores_actual, maxtasksperchild=1) + for variant_id in range(settings.num_variants): + variant_id += MIN_VARIANT_ID + for replic_id in range(settings.num_replics_per_variant): + replic_id += MIN_REPLIC_ID + self._batch_mon.on_replic_queued(variant_id, replic_id) + seed = self.__seed_table.get_seed(variant_id, replic_id) + replic_sim_config = ReplicSimConfig(variant_id, replic_id, seed) + args = (batch_setup, replic_sim_config, self._sim_state,) + + self._worker_pool.apply_async(run_bg_replic, args, + callback=self._batch_mon._on_background_replic_done, + error_callback=self._batch_mon._on_background_replic_error) + + assert self._batch_mon.get_num_replics_pending() != 0 # no way should get this far with no replics queued! + self._worker_pool.close() + + log.info('Queued {} variants, {} replications/variant, to be run among {} cores', + settings.num_variants, settings.num_replics_per_variant, num_cores_actual) + sim_config = ['{}: {}'.format(key, val) for key, val in bsm._app_settings.items()] + log.info('Application config (None value implies default/not-applicable):') + for line in sorted(sim_config): + log.info(' {}', line) + + @override(BaseFsmState) + def exit_state(self, new_state: BaseFsmState): + if new_state.state_id == BsmStatesEnum.done: + self.__gen_and_save_batch_data() + + def get_completion_status(self) -> BatchDoneStatusEnum: + return BatchDoneStatusEnum.in_progress + + def pause(self): + """ + Pause the batch. This affects running replications only: they will each pause. The BSM + transitions to PAUSED. + """ + self._set_state(BsmStateClasses.PAUSED, batch_log_file_handler=self.__log_file_handler) + + def stop(self): + """Stop the batch. This just sets a flag that each replication not yet run reads. """ + log.warning('Aborting the batch') + self._sim_state.exit.value = True + self._worker_pool.terminate() + self._set_state(BsmStateClasses.DONE, + completion_status=BatchDoneStatusEnum.aborted, + batch_log_file_handler=self.__log_file_handler) + + def on_background_replic_done(self): + """When a replication is done, check if there are more; if not, transition to DONE state.""" + if self._batch_mon.get_num_replics_pending() == 0: + log.info("Batch sim completed, no more replications left to run") + self._set_state(BsmStateClasses.DONE, batch_log_file_handler=self.__log_file_handler) + + def __create_batch_folder(self, num_variants: int, num_replics_per_variant: int) -> Path: + """Create a folder to hold all the replication folders, batch log, etc.""" + fsm_owner = self._fsm_owner + assert fsm_owner.scen_path is not None # if None, should have trapped this earlier + + datetime_now = datetime.today().strftime(BATCH_TIMESTAMP_FMT) + batch_name = "batch_{}_{}x{}".format(datetime_now, num_variants, num_replics_per_variant) + batch_folder = fsm_owner.batch_runs_path / batch_name + + batch_folder.mkdir(parents=True) + self.__create_batch_log(batch_folder) + + fsm_owner.signals.sig_batch_folder_changed.emit(str(batch_folder)) + log.info("Batch sim folder is {}", batch_folder) + + return batch_folder + + def __create_batch_log(self, batch_folder: Path): + batch_log = (batch_folder / 'log.csv').absolute() + self.__log_file_handler = logging.FileHandler(str(batch_log)) + self.__log_file_handler.setFormatter(LogCsvFormatter('{asctime},{name},{levelname},"{message}"', style='{')) + logging.getLogger('system').addHandler(self.__log_file_handler) + + def __save_seed_file(self, batch_folder: Path): + """Save the random-seeds file to the batch folder""" + save_path = batch_folder / 'seeds.csv' + self.__seed_table.save_as(save_path) + + def __copy_scenario_snapshot(self, batch_folder: Path): + """Copy the scenario (last saved version on filesystem) to batch folder""" + save_path = batch_folder / Path(self._fsm_owner.scen_path).name + log.info("Copying scenario (as last saved) to '{}'", save_path.parent, save_path.name) + shutil.copy(str(self._fsm_owner.scen_path), str(save_path)) + self._batch_scen_path = save_path + + def __gen_and_save_batch_data(self): + """Generate batch data per the original batch scenario and save it""" + if not BatchDataMgr(self._batch_scen_path.parent).has_data(): + log.info("No batch data generated by this batch run") + return + + scen_mgr = ScenarioManager() + try: + scen = scen_mgr.load(self._batch_scen_path) + except Exception as exc: + log.error("Could not load scenario to process batch data: {}", exc) + return + + if not scen.sim_controller.has_role_parts(RunRolesEnum.batch): + # nothing else to do + return + + try: + scen.sim_controller.run_parts(RunRolesEnum.batch) + except Exception as exc: + log.warning('One or more exceptions while trying to run batch-role function parts, see above for details') + # TBD FIXME ASAP: remove the dead code below + # Reason: need to some time ensure it is not necessary (parts show their errors) + # for failed_part, exc_msg in exc.map_part_to_exc_str.items(): + # log.error(' - {}: {}', failed_part, exc_msg) + + # try to save final state, even if there was an error processing the batch parts: + results_scen_path = Path(scen.filepath).with_name('batch_results.orib') + try: + log.info("Saving batch post-processed state of scenario to {}:", results_scen_path) + scen_mgr.save(results_scen_path) + except Exception: + log.error('Batch post-processed version of scenario could not be saved') + else: + log.info('Batch post-processed version of scenario saved to {}:', results_scen_path) + self._results_scen_path = results_scen_path + + +# noinspection PyProtectedMember +class _BsmStatePaused(BaseFsmState, CapturesNextReadyScenPath): + """ + Implement the Paused state of the BSM. From this state, the BSM can stop or resume. In order to minimize + duplication of behavior, a stop actually causes a transition to RUNNING rather than READY; the RUNNING state + knows how to stop (it waits for all replications queued and in-progress to exit). Note that PAUSED must allow + for some replications to notify completion since some might have completed their sim loop just before the + transition to PAUSED occurred, but before they had completed (hence the on_background_replic_done() needed + in PAUSED). + """ + + state_id = BsmStatesEnum.paused + + def __init__(self, prev_state: BaseFsmState, batch_log_file_handler: logging.Handler, fsm_owner: IFsmOwner = None): + BaseFsmState.__init__(self, prev_state, fsm_owner=fsm_owner) + CapturesNextReadyScenPath.__init__(self) + assert (prev_state.state_id == BsmStatesEnum.running) + + self._batch_mon = prev_state._batch_mon + + self._mp_manager = prev_state._mp_manager + self._sim_state = prev_state._sim_state + self._worker_pool = prev_state._worker_pool + + self._batch_scen_path = prev_state._batch_scen_path + self._batch_data = prev_state._batch_data + + log.info('Pausing running replications') + self._sim_state.paused.value = True + self.__batch_log_file_handler = batch_log_file_handler + + def get_completion_status(self) -> BatchDoneStatusEnum: + return BatchDoneStatusEnum.paused + + def resume(self): + """Resume the batch sim; transitions to RUNNING.""" + log.info('Resuming running replications') + self._set_state(BsmStateClasses.RUNNING, + batch_log_file_handler=self.__batch_log_file_handler) + + def stop(self): + """Flag the replications to exit ASAP, and transition to RUNNING (see class docs for details).""" + log.info('Aborting batch sim') + self._sim_state.exit.value = True + self._worker_pool.terminate() + self._set_state(BsmStateClasses.DONE, + completion_status=BatchDoneStatusEnum.aborted, + batch_log_file_handler=self.__batch_log_file_handler) + + def on_background_replic_done(self): + """ + There is a small chance that a replication could complete after the batch has been paused, if it was + already about to exit its sim loop. If there are no more replications left, transition to DONE state. + """ + # Oliver TODO build 3: add test for this: directly call a few times and check via signals + if self._batch_mon.get_num_replics_pending() == 0: + log.info("Batch sim completed, no more replications left to run") + self._set_state(BsmStateClasses.DONE, + batch_log_file_handler=self.__batch_log_file_handler) + + +# noinspection PyProtectedMember +class _BsmStateDone(BaseFsmState, CapturesNextReadyScenPath): + """ + The batch simulation is done, there are no more replications to monitor. + The results are kept available, until a transition to READY is requested. + """ + + state_id = BsmStatesEnum.done + + def __init__(self, prev_state: BaseFsmState, + batch_log_file_handler: logging.Handler, + completion_status: BatchDoneStatusEnum = BatchDoneStatusEnum.completed, + fsm_owner: IFsmOwner = None): + BaseFsmState.__init__(self, prev_state, fsm_owner=fsm_owner) + CapturesNextReadyScenPath.__init__(self) + assert prev_state.state_id in (BsmStatesEnum.running, BsmStatesEnum.paused) + + self._batch_mon = prev_state._batch_mon + self._completion_status = completion_status + self.__results_scen_path = None + + log.info('Batch {}', completion_status.name) + log.info('Summary:') + for line in self._batch_mon.get_summary().splitlines(): + log.info(' {}', line) + + if batch_log_file_handler is not None: + logging.getLogger('system').removeHandler(batch_log_file_handler) + batch_log_file_handler.close() + self.__batch_log_file_path = Path(batch_log_file_handler.baseFilename) + + def enter_state(self, prev_state: BaseFsmState): + if prev_state.state_id == BsmStatesEnum.running: + self.__results_scen_path = prev_state._results_scen_path + + def get_completion_status(self) -> BatchDoneStatusEnum: + return self._completion_status + + def get_batch_log_file_path(self) -> Path: + return self.__batch_log_file_path + + def get_batch_results_scen_path(self) -> Path: + return self.__results_scen_path + + def new_batch(self): + self._set_state(BsmStateClasses.READY) + + def on_background_replic_done(self): + """ + If the batch was stopped before all in-progress replications could end, there is a small chance that + multiprocessing could flag them as exited after the DONE state has been entered. However, there is + nothing special to do, just need the method to be available. + """ + pass + + +class BatchSimSettings: + """ + Enables saving and loading the configured batch simulation settings with the scenario. + """ + + # --------------------------- class-wide methods -------------------------------------------- + + @staticmethod + def load(pathname: PathType) -> Decl.BatchSimSettings: + """ + Load and set the batch simulation settings from the given file. Overrides previous settings if any. + :param pathname: path to settings file + :returns: The dictionary of batch simulation settings. + :raises: ValueError. This error is raised by the JSON interpreter if a parsing error occurs while the file + is being loaded. + """ + + with Path(pathname).open("r") as f: + settings = json.load(f) + + # backwards compat: + if 'results_root_path' in settings: + settings['batch_runs_path'] = settings['results_root_path'] + del settings['results_root_path'] + + seed_list = settings['seed_table'] + if seed_list is not None: + settings['seed_table'] = SeedTable.from_list(seed_list) + + replic_step_settings = settings['replic_steps'] + if replic_step_settings is not None: + settings['replic_steps'] = SimSteps(**replic_step_settings) + + return BatchSimSettings(**settings) + + # --------------------------- instance (self) PUBLIC methods ---------------- + + def __init__(self, + batch_runs_path: str = None, + num_variants: int = 1, + num_replics_per_variant: int = 1, + num_cores_wanted: int = 0, + auto_seed: bool = True, + seed_table: SeedTable = None, + save_scen_on_exit: bool = True, + replic_steps: SimSteps = None, + ): + """ + Initialize the batch simulation settings. + :param batch_runs_path: The parent folder of all batch run folders. + :param num_variants: The number of variants. + :param num_replics_per_variant: The number of replications per variant. + :param num_cores_wanted: Number of computer cores to use. + :param auto_seed: Set True to use automatic seeding. + :param seed_table: Instance of the seed table (None is used if auto_seed is True). + :param save_scen_on_exit: Set True to save the scenarios. + :param replic_steps: Instance of the sim step settings from the scenario's simulation controller. + """ + + self.batch_runs_path = batch_runs_path + self.num_variants = num_variants + self.num_replics_per_variant = num_replics_per_variant + self.num_cores_wanted = num_cores_wanted + self.auto_seed = auto_seed + self.seed_table = seed_table + self.__check_auto_seeding() + + self.save_scen_on_exit = save_scen_on_exit + self.replic_steps = replic_steps + + def save(self, pathname: Path): + """ + Save the batch settings to the given file. + :param pathname: The save file path. + """ + settings = self.get_settings_dict() + with pathname.open("w") as f: + json.dump(settings, f, indent=4, sort_keys=True) + log.info('Batch settings saved to {}', pathname) + + def get_use_scen_sim_settings(self) -> bool: + """Returns __use_scen_sim_settings boolean based on whether replic_steps is set to None""" + return self.replic_steps is None + + def get_settings_dict(self) -> Dict[str, Any]: + """Returns a dictionary containing the current batch sim settings""" + settings = { + 'batch_runs_path': self.batch_runs_path, + 'num_variants': self.num_variants, + 'num_replics_per_variant': self.num_replics_per_variant, + 'num_cores_wanted': self.num_cores_wanted, + 'auto_seed': self.auto_seed, + 'seed_table': None if self.auto_seed else self.seed_table.get_seeds_list(), + 'save_scen_on_exit': self.save_scen_on_exit, + 'replic_steps': None if self.replic_steps is None else self.replic_steps.to_json(), + } + + return settings + + # --------------------------- instance PUBLIC properties and safe_slots --------------------- + + use_scen_sim_settings = property(get_use_scen_sim_settings) + + # --------------------------- instance _PROTECTED methods ---------------------------- + + def __check_auto_seeding(self): + """Check that auto-seeding and seed table settings are consistent, fix as necessary.""" + if self.auto_seed: + if self.seed_table is not None: + log.warning("Auto-seeding is enabled. Seed Table {} will not be used.", self.seed_table) + + elif self.seed_table is None: + self.seed_table = SeedTable(self.num_variants, self.num_replics_per_variant) + + assert self.auto_seed or self.seed_table is not None + + +class BsmStateClasses: + READY = _BsmStateReady + RUNNING = _BsmStateRunning + PAUSED = _BsmStatePaused + DONE = _BsmStateDone + + +def ret_val_on_attrib_except(ret_val): + """Decorator that will automatically return a specified value if the decorated method raises AttributeError.""" + + def decorator(unbound_meth): + @functools.wraps(unbound_meth) + def wrapper(self, *args, **kwargs): + try: + return unbound_meth(self, *args, **kwargs) + except AttributeError: + return ret_val + + return wrapper + + return decorator + + +class BatchSimManager(IFsmOwner): + """ + Manages a batch simulation of scenario replications of scenario variants. Its Signals instance derives from + BridgeEmitter so it can emit backend signals when imported in console variant, but emit PyQt signals when + imported in the GUI. It forwards several operations to its current + state object; if the state does not support the operation, an exception gets raised. + + The manager supports two modes of operation, descirbed in the init. + """ + + SETTINGS_FILE_EXT = '.bssj' + SETTINGS_FILE_NAME = 'batch_sim_settings' + + class Signals(BridgeEmitter): + sig_state_changed = BridgeSignal(int) # BsmStatesEnum, but used by BaseFsm which emits as int + sig_replication_done = BridgeSignal(int, int) # number of replics done, total number of replics + sig_replication_error = BridgeSignal(int, int, str) # num replics done, total num replics, error string + sig_num_cores_actual_changed = BridgeSignal(int) # actual number of cores + sig_scen_path_changed = BridgeSignal(str) # new path + sig_batch_folder_changed = BridgeSignal(str) # new folder for batch + # time since last start (stops increasing when Done), number of replics done, number of replics pending, + # average ms per replic, estimate to completion (in seconds) from now: + sig_time_stats_changed = BridgeSignal(timedelta, int, int, timedelta, timedelta) + + # --------------------------- class-wide methods -------------------------------------------- + + @staticmethod + def remove_all_batch_folders(path: PathType, max_try_time_sec: int = 10): + """ + Remove all folders in given path. + Note: if some folders are currently not removable, will try every 10 ms until max_try_time_sec elapsed. + :return: list of folders not deleted within max time + """ + GLOB_PATTERN = "batch_*_*x*" + batch_folders = list(Path(path).parent.glob(GLOB_PATTERN)) + failure_wait_sec = 0.01 + for batch_folder in batch_folders: + fail_removal = True + start_time = time.clock() + while fail_removal and time.clock() - start_time < max_try_time_sec: + try: + shutil.rmtree(str(batch_folder)) + log.debug('Removed {} after {} sec', batch_folder, time.clock() - start_time) + fail_removal = False + except OSError: + time.sleep(failure_wait_sec) + + if fail_removal: + log.warning('Could not remove {} in less than {} sec', batch_folder, max_try_time_sec) + + # return list of remaining folders that could not be deleted within max time + return list(Path(path).parent.glob(GLOB_PATTERN)) + + @classmethod + def get_settings_path(cls, scen_path: PathType) -> Path: + """Get path to batch sim settings file based on given scenario .ORI(B) file""" + return Path(scen_path).with_name(cls.SETTINGS_FILE_NAME).with_suffix(cls.SETTINGS_FILE_EXT) + + # --------------------------- instance (self) PUBLIC methods -------------------------------- + + def __init__(self, scenario_manager: ScenarioManager, app_settings: AppSettings = None, bridged_ui: bool = False): + """ + BSM is initialized to a READY state. The presence or absence of a Scenario instance in scenario_manager + determines the mode of operation: + + - single scenario mode: this mode is used when the scenario is already avialable from the scenario + manager at init time; the manager will not be monitored for scenario replacements, etc, and BSM + assumes that app settings will define simulation parameters; the settings from batch sim + settings file are loaded; if the sim steps are None but overridden from app settings, they + are copied from the scenario's sim controller sim steps and the relevant overrides are applied. + + - multi scenario mode: this mode is used when the scenario is None at init time; then the BSM will + monitor the scenario manager for replacement scenario, and will automatically load their settings. + """ + IFsmOwner.__init__(self) + self.signals = BatchSimManager.Signals(thread_is_main=True) + + self._app_settings = dict() + if app_settings: # use it: + self._app_settings.update( + save_log=app_settings.save_log, + log_deprecated=app_settings.log_deprecated, + log_raw_events=app_settings.log_raw_events, + fix_linking_on_load=app_settings.fix_linking_on_load, + + bridged_ui=bridged_ui, + ) + + if hasattr(app_settings, 'loop_log_level') and app_settings.loop_log_level is not None: + self._app_settings['loop_log_level'] = app_settings.loop_log_level + + self.__scen_sim_step_settings = None + self.__auto_load_settings = True + self.__scen_manager = scenario_manager + self._scen_path = None + self._settings = None + + if scenario_manager.scenario is None: + self.__monitor_scen_mgr(scenario_manager) + else: + # assume this is command line driven and only one scenario will ever be used + self.__setup_for_unique_scen(app_settings) + + self._state = _BsmStateReady(fsm_owner=self) + assert self._settings.auto_seed is True or self._settings.seed_table is not None + + def get_settings(self, copy: bool = False) -> BatchSimSettings: + """ + By default get a reference to the manager's settings. + :param copy: set to True to get a copy of the settings + """ + return deepcopy(self._settings) if copy else self._settings + + def set_settings(self, settings: BatchSimSettings, copy: bool = False): + """ + By default store a reference to the provided settings, which will be used at the next batch run. This + method should only be called in the Ready state, otherwise an exception will be raised. + :param copy: set to True to make a copy of the settings + """ + self._settings = deepcopy(settings) if copy else settings + if self._scen_path is not None: + try: + self.save_settings() + except IOError: + log.warning('Failed to save the new settings of BatchSimManager, will try again at next save or set') + + def save_settings(self): + """ + Save the current batch sim manager settings for the loaded scenario. Will fail if no scenario loaded + or new scenario never saved. + """ + self._settings.save(self.get_settings_path(self._scen_path)) + + def load_settings(self): + """ + Load the batch sim settings for the loaded scenario. Will fail if no scenario loaded + or new scenario never saved. + """ + if self._scen_path is None: + raise FileNotFoundError('Cannot load batch sim settings (no scenario path yet)') + + self._settings = BatchSimSettings.load(self.get_settings_path(self._scen_path)) + + def set_auto_load_settings(self, value: bool = True): + """By default, settings are automatically loaded upon scenario change. Set to False to change this.""" + self.__auto_load_settings = value + if self.__auto_load_settings: + try: + self.load_settings() + except FileNotFoundError: + log.warning('Auto-loading of settings now True, but no settings file exists (no scenario folder)') + + def get_scen_sim_steps(self, copy: bool = True) -> SimSteps: + """ + Get the scenario simulation step settings, i.e. the simulation steps that are specific to the + scenario's simulation controller. + :param copy: True if get a copy of settings. Only change + :return: the scenario's sim step settings, or a new instance of SimSteps if no scenario loaded/new-not-saved + """ + if self.__scen_sim_step_settings is not None: + return SimSteps(**json.loads(self.__scen_sim_step_settings)) + + return SimSteps() + + def set_replic_sim_steps(self, **step_settings): + """ + Set the replication sim steps. This causes self.settings.use_scen_sim_settings to become False. + :param step_settings: same args as sim_controller.SimSteps.__init__ + """ + self._settings.replic_steps = SimSteps(**step_settings) + assert self._settings.use_scen_sim_settings is False + + def get_num_cores_wanted(self) -> int: + """Get number of cores set for this or next batch""" + return self._settings.num_cores_wanted + + def get_num_cores_available(self) -> int: + """Get how many cores are available on this machine""" + return mp.cpu_count() + + def get_num_variants(self) -> int: + """Get number of scenario variants set for this or next batch""" + return self._settings.num_variants + + def get_num_replics_per_variant(self) -> int: + """Get number of replications per variant set for this or next batch""" + return self._settings.num_replics_per_variant + + def get_scen_path(self) -> Path: + """Get scenario file path for next batch sim run.""" + return self._scen_path + + def get_seed_table(self) -> SeedTable: + """Get the seed table. If settings.auto_seed is True, returns None""" + return self._settings.seed_table + + # In the non-ready states, the following methods will work: + + def is_running(self) -> bool: + """Return true if currently in RUNNING state, false otherwise. """ + return self.is_state(BsmStatesEnum.running) + + def start_sim(self): + """Attempt to start a batch sim.""" + self._state.start() + + def pause_sim(self): + """Attempt to pause a batch sim.""" + # Oliver FIXME ASAP: enable pausing when simualtion does not have events/startup parts + self._state.pause() + + def resume_sim(self): + """Attempt to resume a batch sim.""" + self._state.resume() + + def stop_sim(self): + """Attempt to stop a batch sim.""" + self._state.stop() + + def update_sim(self): + """ + Process any state changes that may have resulted from worker threads. + Note: this currently doesn't do anything because state is updated by the process thread + """ + pass + + @ret_val_on_attrib_except(0) + def get_num_cores_actual(self) -> int: + """Get number of cores set for this or next batch""" + return self._state._batch_mon.get_num_cores_actual() + + @ret_val_on_attrib_except(0) + def get_num_replics_done(self) -> int: + """Get number of replications that have started and ended (regardless of success).""" + return self._state._batch_mon.get_num_replics_done() + + @ret_val_on_attrib_except(0) + def get_num_replics_failed(self) -> int: + """Get number of replications that have completed with a failure.""" + return self._state._batch_mon.get_num_replics_failed() + + @ret_val_on_attrib_except(0) + def get_num_variants_done(self) -> int: + """Get number of variants that have all their replications completed (regardless of success/fail).""" + return self._state._batch_mon.get_num_variants_done() + + @ret_val_on_attrib_except(0) + def get_num_variants_failed(self) -> int: + """Get number of variants that have all their replications completed but at least one replication failed.""" + return self._state._batch_mon.get_num_variants_failed() + + @ret_val_on_attrib_except(0) + def get_num_replics_in_progress(self) -> int: + return self._state._batch_mon.get_num_replics_in_progress() + + @ret_val_on_attrib_except(None) + def get_batch_folder(self) -> Optional[Path]: + """Get the batch folder of currently running batch sim (or, currently completed batch sim).""" + return self._state._batch_mon.get_batch_folder() + + @ret_val_on_attrib_except(None) + def get_batch_results_scen_path(self) -> Optional[Path]: + """ + Get the path to the batch results scenario available upon completion of a batch run. Returns None if the + file does not exist (because the batch did not complete, or no batch data was generated by any replication). + """ + return self._state.get_batch_results_scen_path() + + @ret_val_on_attrib_except(None) + def get_replic_path(self, variant_id: int, replic_id: int) -> Path: + """Get the path for the replication from last/current batch""" + return self._state._batch_mon.get_replic_path(variant_id, replic_id) + + def wait_till_done(self, max_time_sec=None): + """ + Wait till the BSM is back in ready state, or at most max_time_sec if given. Returns whether the BSM is + still in running state. Note: The BSM state may change between the time the return value is created and + it is tested by the caller. + """ + # Oliver TODO build 3: add test for this + if max_time_sec: + start_time = time.clock() + while self.is_running() and time.clock() - start_time < max_time_sec: + self.update_sim() + time.sleep(0.01) + + else: + while self.is_running(): + self.update_sim() + time.sleep(0.01) + + return self.is_running() + + def is_state(self, state_id: BsmStatesEnum) -> bool: + """Return true if our state object has class state_class""" + return state_id == self._state.state_id + + def get_completion_status(self) -> BatchDoneStatusEnum: + """Returns the completion status. In ready state, returns not_started""" + return self._state.get_completion_status() + + def get_batch_log_file_path(self) -> Path: + """When state=DONE, the log file can be obtained""" + return self._state.get_batch_log_file_path() + + def get_batch_runs_path(self) -> Path: + """ + Get the path to folder in which a batch folder will be created when a batch is run. If + self.settings.batch_runs_path is None then this returns folder containing the scenario file. + """ + if self._settings.batch_runs_path is None: + return self.scen_path.parent + else: + return Path(self._settings.batch_runs_path) + + def new_batch(self): + """ + Abandon any "done" batch and return to Ready state from where a new batch can be configured + and started. Can only be called in DONE state. + """ + self._state.new_batch() + + # --------------------------- instance PUBLIC properties ---------------------------- + + num_cores_wanted = property(get_num_cores_wanted) + num_cores_available = property(get_num_cores_available) + num_variants = property(get_num_variants) + num_replics_per_variant = property(get_num_replics_per_variant) + + seed_table = property(get_seed_table) + scen_path = property(get_scen_path) + batch_runs_path = property(get_batch_runs_path) + batch_folder = property(get_batch_folder) + batch_results_scen_path = property(get_batch_results_scen_path) + + num_cores_actual = property(get_num_cores_actual) + num_replics_in_progress = property(get_num_replics_in_progress) + num_replics_done = property(get_num_replics_done) + num_replics_failed = property(get_num_replics_failed) + num_variants_done = property(get_num_variants_done) + num_variants_failed = property(get_num_variants_failed) + + settings = property(get_settings) + + # --------------------------- instance __SPECIAL__ method overrides ---------------------------- + # --------------------------- instance _PROTECTED and _INTERNAL methods --------------------- + + @override(IFsmOwner) + def _on_state_changed(self, prev_state: BaseFsmState): + """Signal connected slots that our state has changed""" + self.signals.sig_state_changed.emit(int(self._state.state_id)) + + @internal(BsmStateClasses) + def _reset_run_time(self): + self.signals.sig_time_stats_changed.emit(timedelta(0), 0, 0, timedelta(0), timedelta(0)) + + @internal(BsmStateClasses) + def _update_run_time(self, time: timedelta, num_replics_done: int, num_replics_pending: int): + avg_ms_per_replic = time / num_replics_done if num_replics_done else 0 + etc_sec = avg_ms_per_replic * num_replics_pending + self.signals.sig_time_stats_changed.emit(time, num_replics_done, num_replics_pending, + avg_ms_per_replic, etc_sec) + + # --------------------------- instance _PROTECTED and _INTERNAL properties -------- + # --------------------------- instance __PRIVATE members------------------------------------- + + def __setup_for_unique_scen(self, app_settings): + log.debug("WARNING: using single-scenario mode (scenario available at init time), scen mgr NOT monitored") + + # load the scenario batch settings + self.__on_scen_replaced() + + if app_settings: + self._settings.num_variants = app_settings.num_variants + self._settings.num_replics_per_variant = app_settings.num_replics_per_variant + self._settings.num_cores_wanted = app_settings.num_cores + self._settings.save_scen_on_exit = app_settings.batch_replic_save + + if app_settings.realtime_scale != 1.0: + log.warning('Realtime scale not used during batch, settings ({}) ignored', + app_settings.realtime_scale) + + if app_settings.seed_file_path is not None: + self._settings.seed_table = SeedTable( + self._settings.num_variants, + self._settings.num_replics_per_variant, + app_settings.seed_file_path) + self._settings.seed_table.load() + self._settings.auto_seed = False + + if app_settings.max_sim_time_days is not None or app_settings.max_wall_clock_sec is not None: + # if using the scen sim steps, get them, because we have to override a portion: when user does + # this it is as though they had copied all the other settings over + if self._settings.replic_steps is None: + assert self.__scen_sim_step_settings is not None + self._settings.replic_steps = self.get_scen_sim_steps() + + end_settings = self._settings.replic_steps.end + if app_settings.max_sim_time_days is not None: + end_settings.max_sim_time_days = app_settings.max_sim_time_days + if app_settings.max_wall_clock_sec is not None: + end_settings.max_wall_clock_sec = app_settings.max_wall_clock_sec + + def __monitor_scen_mgr(self, scen_mgr: ScenarioManager): + """ + Setup the BSM assuming that the scenario will be delivered later. For now create a default settings + obj and connect to scenario manager. + """ + log.debug("WARNING: BSM does not have a scenario yet, assumes will be delivered later") + self._settings = BatchSimSettings() + assert self._settings.auto_seed is True + assert self._settings.seed_table is None + assert self._settings.use_scen_sim_settings is True + + scen_mgr_signals = scen_mgr.signals + scen_mgr_signals.sig_scenario_replaced.connect(self.__slot_on_scen_replaced) + scen_mgr_signals.sig_scenario_saved.connect(self.__slot_on_scen_saved) + scen_mgr_signals.sig_scenario_filepath_changed.connect(self.__slot_on_scen_path_changed) + # forward signal for scen file path changed: + scen_mgr_signals.sig_scenario_filepath_changed.connect(self.signals.sig_scen_path_changed) + + def __on_scen_path_changed(self, filepath: str): + log.debug('BSM received signal that scenario file path has changed to {}', filepath) + self._state.set_scen_path(filepath or None) + if self._scen_path is not None: + try: + self.load_settings() + except FileNotFoundError as exc: + log.warning('Could not load scenario {} batch sim settings: {} (like legacy scenario)', + self._scen_path, exc) + + def __on_scen_saved(self): + if self._scen_path is not None: + settings_path = self.get_settings_path(self._scen_path) + self._settings.save(settings_path) + + def __on_scen_sim_step_settings_changed(self, json_str: str): + self.__scen_sim_step_settings = json_str + # scen_sim_step_settings = json.loads(json_str) + # self._settings.replic_steps = SimSteps(**scen_sim_step_settings) + + def __on_scen_replaced(self): + # Oliver TODO build 3.3: change sig_scen_replaced to carry scenario to slots + # Reason: no time before interim release, will need to modify IScenarioMonitor + scenario = self.__scen_manager.scenario + self._scen_path = scenario.filepath + self._settings = BatchSimSettings() + if self.__auto_load_settings and self._scen_path is not None: + try: + self.load_settings() + except IOError as exc: + log.warning('New scenario loaded, but no batch sim settings file found (likely legacy scenario): {}', + exc) + + json_settings = scenario.sim_controller.settings.get_sim_steps(copy=True).to_json() + self.__scen_sim_step_settings = json.dumps(json_settings) + assert self.__scen_sim_step_settings is not None + + sig_step_settings_changed = scenario.sim_controller.signals.sig_step_settings_changed + sig_step_settings_changed.connect(self.__slot_on_scen_sim_step_settings_changed) + + # Oliver FIXME ASAP: define safe_slot slots + # Reason: tried this and could not get connections to work, presumably derivations from BridgeEmitter missing + __slot_on_scen_path_changed = __on_scen_path_changed + __slot_on_scen_saved = __on_scen_saved + __slot_on_scen_sim_step_settings_changed = __on_scen_sim_step_settings_changed + __slot_on_scen_replaced = __on_scen_replaced + + +class BatchMonitor: + """ + Monitor a batch of replications that will be queued (outside of this class) for multi-processing. + The BatchMonitor is useful to keep track of state between the Running, Paused and Done states of + the BatchSimManager. + """ + + def __init__(self, bsm: BatchSimManager, batch_folder: Path, num_cores_start: int): + self.__bsm = bsm + self.__batch_folder = batch_folder + assert batch_folder is not None + self.__num_variants = bsm.num_variants + self.__num_replics_per_variant = bsm.num_replics_per_variant + self.__pool_mutex = mp.RLock() # synchro access to data members accessed by Pool threads AND main thread + + self.__num_cores_actual = num_cores_start + self.__replics_in_queue = [] + self.__replic_results = {} # each replication has a status as result (indicating its completion status) + + self.__start_time = datetime.now() + self.__done_time = None + + def on_replic_queued(self, variant_id: int, replic_id: int): + """Whenever the BatchSimManager queues a replication for execution, it must notify the monitor.""" + with self.__pool_mutex: + self.__replics_in_queue.append((variant_id, replic_id)) + + def get_batch_folder(self) -> Path: + """Get the batch folder of currently running batch sim (or, currently completed batch sim).""" + return self.__batch_folder + + def get_replic_path(self, variant_id: int, replic_id: int) -> Path: + """Get the path for the replication from last/current batch. Raises RuntimeError if batch""" + return get_replic_path(self.__batch_folder, variant_id, replic_id) + + def get_num_cores_actual(self) -> int: + """ + Get the number of actual cores in use. This will be less than the original number (num_cores_start) + when there are fewer replications left than that number. + """ + with self.__pool_mutex: + return self.__num_cores_actual + + def get_num_replics_pending(self) -> int: + """Get the number of replications that are not done yet. Note: Some of them might be in progress.""" + with self.__pool_mutex: + return len(self.__replics_in_queue) + + def get_num_replics_in_progress(self) -> int: + """ + Get the number of replication currently executing. This method assumes that it is the number of + actual cores in use. + """ + with self.__pool_mutex: + return self.__num_cores_actual + + def get_num_replics_done(self) -> int: + """ + Get number of replications that have started and ended, *regardless* of success. So + num done - num failed = num completed successfully. + """ + with self.__pool_mutex: + num_pending = len(self.__replics_in_queue) + num_done = self.__num_variants * self.__num_replics_per_variant - num_pending + assert num_done == sum(len(variant_results) for variant_results in self.__replic_results.values()) + return num_done + + def get_num_replics_failed(self) -> int: + """Get number of replications that have failed.""" + failed = 0 + with self.__pool_mutex: + for variant_replics in self.__replic_results.values(): + for status in variant_replics.values(): + if status == ReplicExitReasonEnum.failure: + failed += 1 + return failed + + def get_replics_failed(self) -> List[int]: + """Get number of replications that have failed.""" + failed = [] + with self.__pool_mutex: + for variant_replics in self.__replic_results.values(): + for replic_id, status in variant_replics.items(): + if status == ReplicExitReasonEnum.failure: + failed.append(replic_id) + return sorted(failed) + + def get_num_variants_done(self) -> int: + """Get number of variants that have all their replications completed (regardless of success/fail).""" + done = 0 + with self.__pool_mutex: + for variant_replics in self.__replic_results.values(): + if len(variant_replics) == self.__num_replics_per_variant: + done += 1 + return done + + def get_variants_failed(self) -> List[int]: + """Get list of variants that have at least one replication failed.""" + failed_variants = [] + with self.__pool_mutex: + for variant_id, variant_replics in self.__replic_results.items(): + for status in variant_replics.values(): + if status == ReplicExitReasonEnum.failure: + failed_variants.append(variant_id) + break # stop in this variant at first replic failed + + return sorted(failed_variants) + + def get_num_variants_failed(self) -> int: + """Get number of variants that have all their replications completed but at least one replication failed.""" + return len(self.get_variants_failed()) + + def get_exec_time(self) -> timedelta: + """Return the amount of time used to run a batch simulation""" + if self.__done_time is None: + return datetime.now() - self.__start_time + return self.__done_time - self.__start_time + + def get_summary(self) -> str: + num_replics_queued = self.__num_variants * self.__num_replics_per_variant + num_variants_failed = self.get_num_variants_failed() + num_replics_failed = self.get_num_replics_failed() + if num_variants_failed == 0: + variants_failed = '' + else: + variants_failed = '(variant IDs: {})'.format(', '.join(str(id) for id in self.get_variants_failed())) + if num_replics_failed == 0: + replics_failed = '' + else: + replics_failed = '(replic IDs: {})'.format(', '.join(str(id) for id in self.get_replics_failed())) + + return dedent("""\ + Queued at start: {} replications ({} variants) + Variants with failures: {} of {} {} + Replications failed: {} of {} {} + Execution time (days HH:MM:SS.ss): {} + """).format(num_replics_queued, self.__num_variants, + num_variants_failed, self.get_num_variants_done(), variants_failed, + num_replics_failed, self.get_num_replics_done(), replics_failed, + self.get_exec_time(), + ) + + # --------------------------- instance _PROTECTED and _INTERNAL methods --------------------- + # --------------------------- instance _PROTECTED and _INTERNAL properties -------- + + @internal(_BsmStateRunning) + def _on_background_replic_done(self, result: Tuple[int, int, ReplicStatusEnum]): + """ + Called when a replication has completed (returned) successfully + :param result: the tuple returned by self._child_replication + """ + variant_id, replic_id, status = result + log.info('Got status "{}" for replication ({},{})', get_enum_val_name(status), variant_id, replic_id) + with self.__pool_mutex: + self.__update_state(variant_id, replic_id, status) + # Notify the GUI that replications have been completed. + total_replics = self.__num_variants * self.__num_replics_per_variant + self.__bsm.signals.sig_replication_done.emit(self.get_num_replics_done(), total_replics) + + @internal(_BsmStateRunning) + def _on_background_replic_error(self, exc: ReplicationError): + """ + Called when a replication has raised an exception + :param exc: the ReplicationError that was raised + """ + if len(exc.args) < 4: + log.error("Unexpected format for ReplicationError! Type {}, args={}: {}", type(exc), exc.args, exc) + return + + variant_id, replic_id, err_msg, exc_traceback = exc.args + log.error('Replication ({}, {}) raised exception, see its log file for details', variant_id, replic_id) + with self.__pool_mutex: + status = ReplicExitReasonEnum.failure + status.set_exc_traceback(err_msg) + + self.__update_state(variant_id, replic_id, status) + total_replics = self.__num_variants * self.__num_replics_per_variant + self.__bsm.signals.sig_replication_error.emit(self.get_num_replics_done(), total_replics, err_msg) + + # --------------------------- instance __PRIVATE members------------------------------------- + + def __update_state(self, variant_id: int, replic_id: int, status: ReplicExitReasonEnum): + """Update the state of the monitor. Needs to be called whenever the a replication finishes""" + self.__done_time = datetime.now() + + variant_results = self.__replic_results.setdefault(variant_id, {}) + variant_results[replic_id] = status + + self.__replics_in_queue.remove((variant_id, replic_id)) + self.__update_cores_actual() + + num_pending = len(self.__replics_in_queue) + num_done = self.__num_variants * self.__num_replics_per_variant - num_pending + self.__bsm._update_run_time(self.get_exec_time(), num_done, num_pending) + + self.__bsm._state.on_background_replic_done() + + def __update_cores_actual(self): + """The number of replications left will eventually < num actual cores""" + replics_left = len(self.__replics_in_queue) + if replics_left < self.__num_cores_actual: + self.__num_cores_actual = replics_left + if replics_left: + log.debug('Batch now using {} cores (1 replication process/core)', self.__num_cores_actual) diff --git a/origame/batch_sim/bg_replication.py b/origame/batch_sim/bg_replication.py new file mode 100644 index 0000000..4587e9c --- /dev/null +++ b/origame/batch_sim/bg_replication.py @@ -0,0 +1,630 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Background Replication module + +The bg_replication module provides classes that implement the functionality required to run one +scenario replication. This includes starting, monitoring pause & stop commands from parent +process (GUI or Console), logging configuration, creation of replication's folder, error handling, +etc. The module is used primarily by the BatchSimManager class, which uses multiprocessing.Pool to +start multiple replications in separate child background processes. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import traceback +import logging +from enum import IntEnum, unique +from pathlib import Path +import multiprocessing as mp +import sys + +# [2. third-party] + +# [3. local] +from ..core import LogManager, log_level_int, log_level_name +from ..core.utils import ori_profile, ClockTimer +from ..core.signaling import setup_bridge_for_console +from ..core.typing import Any, Either, Optional, List, Tuple, Sequence, Set, Dict, Iterable, Callable, PathType +from ..core.typing import AnnotationDeclarations + +from ..scenario import SimController, SimStatesEnum, SimSteps, SimControllerSettings, RunRolePartsError +from ..scenario import proto_compat_warn, DataPathTypesEnum + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + + +__all__ = [ + 'run_bg_replic', + 'get_replic_path', + + 'ReplicationError', + 'ReplicStatusEnum', + 'ReplicSimState', + 'ReplicSimConfig', + 'Replication', + 'BatchSetup', +] + +log = logging.getLogger('system') + +# set this to True if profile data should be generated for each replication (each one gets its own .pstats file) +PROFILE_BATCH_REPLICATIONS = False + + +class Decl(AnnotationDeclarations): + BatchSetup = 'BatchSetup' + ReplicSimConfig = 'ReplicSimConfig' + ReplicSimState = 'ReplicSimState' + ReplicStatusEnum = 'ReplicStatusEnum' + + +# -- Function definitions ----------------------------------------------------------------------- + +def setup_variant(bridged_ui: bool): + """ + When run from the GUI, the multiprocessing module will load the same modules, same configuration, so the + replication ends up with Qt QObject as BridgeEmitter base class to the Scenario signals. Here, we check if + this is the case and if so, reload the scenario modules. WARNING: this can cause unexpected behavior because + for example enum classes get reloaded; so the same enum member before and after this function is called + will have different id() and hence they will not compare equal! + """ + if bridged_ui: + log.info('Running batch replication from GUI, patching the signaling module') + + for mod in list(sys.modules.keys()): + if mod.startswith('origame.scenario'): + del sys.modules[mod] + + setup_bridge_for_console() + + else: + # save some time: for console run, no need to re-configure + log.info('Running batch replication from Console') + + +def run_bg_replic(batch_setup: Decl.BatchSetup, + sim_config: Decl.ReplicSimConfig, + shared_sim_state: Decl.ReplicSimState) -> Tuple[int, int, Decl.ReplicStatusEnum]: + """ + Start a replication. This is called by multiprocessing.Pool *in separate process* to start a replication. + + First checks if have an EXIT signal already; only if NOT will a Replication be created and evolved until + either STOPPED, no more events, or max sim time reached. + + :param batch_setup: setup parameters common to all replications of a batch + :param sim_config: ReplicSimConfig instance containing run parameters specific to sim (random seed etc) + :param shared_sim_state: the shared sim state, instance of ReplicSimState + + :returns: (variant_id, replic_id, status), where status is one of ReplicStatusEnum constants + :raises ReplicationError: when something went wrong in replication process; this exception got + pickled in process and carried over to parent process. + """ + + # if there has been a batch stop then we want to know before we even create the Replication + variant_id, replic_id = sim_config.variant_id, sim_config.replic_id + + log_mgr = LogManager() + + try: + shared_sim_state.start(variant_id, replic_id) + shared_sim_state.update_exit() + if shared_sim_state.need_exit(): + log.warning("Replication ({},{}) will NOT be created", variant_id, replic_id) + return variant_id, replic_id, ReplicExitReasonEnum.stopped + + # ok, replication needed, create its folder; user-facing IDs start at 1 instead of 0 + replic_path = get_replic_path(batch_setup.batch_folder, variant_id, replic_id) + replic_path.mkdir(parents=True) + sim_config.replic_path = str(replic_path) + if batch_setup.save_log: + # and log to log.csv in that folder + log_mgr.log_to_file(path=replic_path) + + # start and run it: + replication = Replication(batch_setup, sim_config) + if PROFILE_BATCH_REPLICATIONS: + replication.run = ori_profile(replication.run, batch_setup.scen_path, v=variant_id, r=replic_id) + result = replication.run(shared_sim_state) + + return result + + except Exception as exc: + log.error('Exception in Replication ({},{}):', variant_id, replic_id) + log.exception('Traceback:') + # This is tricky because this function gets called in a separate process, so the exception actually + # gets pickled by multiprocessing and copied to the host process. It seems that this puts some limitations + # on what can be done because after many tries the following was the only reliable way of passing variant + # and replication id and relevant info about trackeback + exc_tb = traceback.format_exc() + raise ReplicationError(variant_id, replic_id, str(exc), exc_tb) + + finally: + log_mgr.close() + + +def get_replic_path(batch_folder: str, variant_id: int, replic_id: int) -> Path: + """Get the path name to a replication in batch folder with given id's""" + return Path(batch_folder) / 'v_{}_r_{}'.format(variant_id, replic_id) + + +# -- Class Definitions -------------------------------------------------------------------------- + +class ReplicationError(Exception): + """ + Raised when a replication cannot continue. This may happen during initialization of the replication, + during the simulation loop, or (unlikely but possible) during shutdown (when the final scenario state + gets saved). + """ + + def __init__(self, variant_id: int, replic_id: int, message: str, traceback: str): + """ + :param variant_id: id of variant for this replication + :param replic_id: id of this replication + :param traceback: stack traceback + """ + Exception.__init__(self, variant_id, replic_id, message, traceback) + + +class SimEventExecError(Exception): + """ + Raised when sim controller of a replication has failed processing an event (ie executing the + associated IExecutablePart) + """ + pass + + +class ReplicStatusEnum(IntEnum): + """ + Enumeration of the possible status of a scenario replication simulation. Before a Replication instance is + created, the replication status is NOT_STARTED. Once it is created, it becomes CREATED, and one the + replication starts simulating the scenario, it becomes NOT_DONE. The status will transition to either + STOPPED if sim stopped externally, ELAPSED if sim time reached set limit, or NO_MORE_EVENTS if ran out of events. + """ + not_started, initialized, processing_events, exited = range(4) + + +@unique +class ReplicExitReasonEnum(IntEnum): + # normal exits: + max_sim_time_elapsed, max_wall_clock_elapsed, no_more_events, paused_by_script = range(4) + # abnormal exits (did not end properly): + stopped, event_failed, startup_failure, finish_failure = range(20, 24) + # general failure: + failure = 100 + + def set_exc_traceback(self, exc_traceback: str): + self.__exc_traceback = exc_traceback + + def get_exc_traceback(self) -> str: + return self.__exc_traceback + + +class ReplicSimState: + """ + Represent the simulation state that is shared between background replications and the master process + (Origame GUI or Console variant). The master process instantiates only one instance for a batch run, + and gives this one instance to each replication. The master does not call any of the methods, but the + master writes to self.exit and self.paused when replications should exit or un/pause. + + Each replication runs in a separate process via multiprocessing.Pool and gets its own process-local + instance of the ReplicSimState, with initialization state copied across processes by the + multiprocessing.Manager, except for self.exit and self.pause which actually reflect the state set + by the master process (they are not copies, they dynamically update when master changes). + + Hence each replication calls start() when it starts, and then calls other methods until the replication + is eventually done, but it does not change self.exit or self.paused. The + multiprocessing module (specifically, its Manager and Pool classes) take care of all the behind-the-scenes + communication necessary to transfer self.exit and self.pause across all processes. + """ + + # calls to update_*() methods are expensive as they communicate with master process; only update every so often: + UPDATE_INTERVAL_SEC = 0.1 + + def __init__(self, mp_manager: mp.Manager): + """ + :param mp_manager: The multiprocess.Manager instance to use to share exit and pause states between + master and replication processes + """ + # shared by all children and parent + self.exit = mp_manager.Value('b', False) + self.paused = mp_manager.Value('b', False) + + # local to the child receiving self: the instance in master will never see those change; each replication + # has its own copy of those data members, but init can only be called in master so can't set here. Use + # reasonable defaults: + self._need_exit = False + self._current_paused = None + self._variant_id = None + self._replic_id = None + self._update_pause_timer = None + self._update_exit_timer = None + + def start(self, variant_id: int, replic_id: int): + """ + Signify the start of a replication for the given ID. This is called by the Replication itself, + when it starts doing its work, so it is in a separate process! + :param variant_id: ID of scenario variant, starts at 0 + :param replic_id: ID of scenario variant replication, starts at 1 + """ + assert variant_id >= 1 + assert replic_id >= 1 + self._need_exit = self.exit.value + self._current_paused = self.paused.value + self._variant_id = variant_id + self._replic_id = replic_id + self._update_pause_timer = ClockTimer() + self._update_exit_timer = ClockTimer() + + def update_paused(self) -> bool: + """ + Update the pause flag based on master setting. This flag state is copied locally (to replication) + to ensure it does not change when queried multiple times in one replication step. + :return: True if transitioned (previous state different from new), False otherwise + """ + if self._update_pause_timer.total_time_sec < self.UPDATE_INTERVAL_SEC: + return False + + self._update_pause_timer.reset() + new_paused = self.paused.value + if self._current_paused != new_paused: + if new_paused: + log.info('Replication ({},{}) entering PAUSED state', self._variant_id, self._replic_id) + else: + log.info('Replication ({},{}) entering RUN state', self._variant_id, self._replic_id) + self._current_paused = new_paused + return True + + return False + + def need_pause(self) -> bool: + """Return True if the Replication should pause. Only call this after update_paused().""" + return self._current_paused + + def update_exit(self): + """ + Update the exit flag based on master setting. This flag state is copied locally (to replication) + to ensure it does not change when queried multiple times in one replication step. + """ + if self._update_exit_timer.total_time_sec >= self.UPDATE_INTERVAL_SEC: + self._update_exit_timer.reset() + new_exit = self.exit.value + self._need_exit = new_exit + + def need_exit(self) -> bool: + """Return True if replication should exit ASAP. Only call this after update_exit().""" + return self._need_exit + + +class ReplicSimConfig: + """ + POD structure that aggregates configuration parameters specific to each individual replication + of a batch (each replication will have a different instance of this class): + its variant and replication ID, its seed, etc. + """ + + def __init__(self, variant_id: int, replic_id: int, reset_seed: int, replic_path: PathType = None): + """ + :param variant_id: variant id of this replication, starts at 1 + :param replic_id: replication id of this variant replication, starts at 1 + :param reset_seed: the seed for the random number generator + :param replic_path: path to the replication's folder where log etc stored; if not set now, must be set + before the Replication is instantiated + """ + self.variant_id = variant_id + self.replic_id = replic_id + self.reset_seed = reset_seed + self.replic_path = str(replic_path) + + +class BatchSetup: + """ + POD structure that aggregates configuration parameters that are GLOBAL TO THE BATCH, i.e. pertain + identically to ALL REPLICATIONS: batch folder, scenario path, whether to log, whether to save on exit, + etc. + """ + + def __init__(self, + scen_path: str, + batch_folder: str, + sim_steps: SimSteps, + save_scen_on_exit: bool = True, + + save_log: bool = True, + loop_log_level: Either[int, str] = logging.WARNING, + log_deprecated: bool = False, + log_raw_events: bool = False, + fix_linking_on_load: bool = True, + + bridged_ui: bool = False): + """ + :param scen_path: path to scenario file for scenario to run + :param batch_folder: the folder in which to save replication folders + + :param save_log: if False, replications will not save their log to a file + :param loop_log_level: log level (int or str) for each replication's sim loop + :param log_deprecated: if True, use of deprecated functions will be logged + :param log_raw_events: if True, simulation events will be logged to a separate file; WARNING: + each replication uses the same file, so this option really only makes sense for 1x1 batch! + :param fix_linking_on_load: if True, linking will be verified on load and fixed (should only be + required for prototype scenarios) + + :param max_sim_time_days: sim time (days) at which replication should exit + :param max_wall_clock_sec: real-time (seconds) at which replication should exit + :param realtime_scale: scale factor for real-time; if as-fast-as-possible, then None, else must be > 0 + + :param save_scen_on_exit: If False, the replication final state (scenario) will not be saved on exit + :param bridged_ui: if True, indicates this batch is being run from an application that uses UI bridging; in + such case, the replication will re-configure itself without bridging + """ + + self.scen_path = scen_path + self.batch_folder = batch_folder + self.sim_steps = sim_steps + + self.save_log = save_log + self.loop_log_level = log_level_int(loop_log_level) # always a number + self.log_deprecated = log_deprecated + self.log_raw_events = log_raw_events + self.fix_linking_on_load = fix_linking_on_load + + self.save_scen_on_exit = save_scen_on_exit + self.bridged_ui = bridged_ui + + +class SimStartupError(Exception): + pass + + +class Replication: + """ + Represent an Origame scenario replication executing the scenario logic. Each replication has its + own folder and log file. + """ + + def __init__(self, batch_config: BatchSetup, sim_config: ReplicSimConfig): + """ + :param batch_config: batch-level configuration parameters (scenario path, batch folder, etc) + :param sim_config: replication-specific settings (variant and replication ID, replication folder etc) + """ + + variant_id = sim_config.variant_id + replic_id = sim_config.replic_id + + setup_variant(batch_config.bridged_ui) + + # Signaling-related functionality must be imported here due to how multiprocessing imports modules in processes; + # for example, if the batch is started from GUI, we still want Replication's ScenarioManager to use + # BackendEmitter not BridgeEmitter + from ..core.signaling import BackendEmitter + from ..scenario import ScenarioManager, MIN_REPLIC_ID, MIN_VARIANT_ID + assert issubclass(ScenarioManager.Signals, BackendEmitter) + + # Each replication has its own folder + # create folder for this replication, inside batch folder: + log.info('Creating Replication ({},{})', variant_id, replic_id) + + if variant_id < MIN_VARIANT_ID: + raise ValueError("invalid variant id", variant_id) + if replic_id < MIN_REPLIC_ID: + raise ValueError("invalid replication id", replic_id) + + self.__v_id = variant_id + self.__r_id = replic_id + self.__replic_folder = sim_config.replic_path + self.__save_scen_on_exit = batch_config.save_scen_on_exit + self.__sim_loop_log_level = batch_config.loop_log_level + + self.__replic_status = ReplicStatusEnum.initialized + + # load scenario + self.__scenario_mgr = ScenarioManager() + # assert Path(replic_folder).parent.parent == Path(scen_path).parent + self.__scenario_mgr.config_logging(batch_config) + self.__scenario_mgr.set_future_anim_mode_constness(False) + scen = self.__scenario_mgr.load(batch_config.scen_path) + assert scen.scenario_def.root_actor.anim_mode is False + # WARNING: due to setup_variant() re-importing modules, we cannot provide the file_type here, it will not + # compare equal. Instead we let batch_data module infer it. + scen.shared_state.batch_data_mgr.set_data_path(batch_config.batch_folder) + # scen.shared_state.batch_data_mgr.set_data_path(batch_config.batch_folder, + # file_type=DataPathTypesEnum.batch_folder) # FAILS, see above + + # config sim controller of that scenario + sim_settings = SimControllerSettings(variant_id=variant_id, + replic_id=replic_id, + auto_seed=False, # batch manager always picks seed for replication + reset_seed=sim_config.reset_seed, + sim_steps=batch_config.sim_steps) + self.__sim_controller = self.__scenario_mgr.scenario.sim_controller + self.__sim_controller.replic_folder = sim_config.replic_path + self.__sim_controller.set_settings(sim_settings) + assert self.__sim_controller.get_anim_while_run_dyn_setting() is True + assert self.__sim_controller.is_animated is False + + @property + def status(self) -> ReplicStatusEnum: + """Obtain run status of the replication.""" + return self.__replic_status + + @property + def replic_folder(self): + """Get the folder for this replication""" + return self.__replic_folder + + @property + def sim_controller(self) -> SimController: + """Get the sim controller for this replication""" + return self.__sim_controller + + @property + def variant_id(self) -> int: + """Get the sim controller for this replication""" + return self.__v_id + + @property + def replic_id(self) -> int: + """Get the sim controller for this replication""" + return self.__r_id + + def run(self, shared_sim_state: ReplicSimState) -> Tuple[int, int, ReplicStatusEnum]: + """ + Start a replication, with given shared sim state. Will be evolved in a loop until either STOPPED + (via shared sim state), no more events, or max sim time reached. + + :param shared_sim_state: the shared sim state, instance of ReplicSimState + :returns: (variant_id, replic_id, status), where status is one of ReplicStatusEnum constants + :raises ReplicationError: when something went wrong in replication process; this exception got + pickled in process and carried over to parent process. + """ + shared_sim_state.update_exit() + if shared_sim_state.need_exit(): + replic_exit_reason = ReplicExitReasonEnum.stopped + self.__replic_status = ReplicStatusEnum.exited + log.warning('Replication ({},{}) run stopped before start (STOPPED)', self.__v_id, self.__r_id) + return self.__v_id, self.__r_id, replic_exit_reason + + try: + self.__startup(shared_sim_state) + replic_exit_reason = self.__loop_till_stopped(shared_sim_state) + + # process exit condition: + if replic_exit_reason == ReplicExitReasonEnum.stopped: + assert shared_sim_state.need_exit() + log.warning('Unsuccessful completion for Replication ({},{}) (STOPPED)', self.__v_id, self.__r_id) + + elif replic_exit_reason == ReplicExitReasonEnum.event_failed: + last_step_error_info = self.__sim_controller.last_step_error_info + assert self.__sim_controller.last_step_was_error + error_msg = last_step_error_info.msg + log.error(error_msg) + log.error('Unsuccessful completion for Replication ({},{}) (FAILED event)', self.__v_id, self.__r_id) + raise SimEventExecError(error_msg) + + else: + assert not self.__sim_controller.last_step_was_error + log.info('Successful completion for Replication ({},{})', self.__v_id, self.__r_id) + + # done: + return self.__v_id, self.__r_id, replic_exit_reason + + finally: + self.__replic_status = ReplicStatusEnum.exited + # After scenario saved-as, scenario path will be in the replication folder, and on scenario shutdown, + # batch replication data automatically gets saved if there is any. *So* we have to save the batch + # replication data *first* AND clear it, so it doesn't get saved in the wrong place on scenario shutdown. + self.__scenario_mgr.scenario.save_batch_replic_data(clear_after=True) + # regardless of success, attempt to save scenario in case final state useful for debugging + if self.__save_scen_on_exit: + self.__scenario_mgr.save(Path(self.__replic_folder, 'final_scenario.ori')) + + # --------------------------- instance _PROTECTED and _INTERNAL methods --------------------- + # --------------------------- instance _PROTECTED properties and safe slots ----------------- + # --------------------------- instance __PRIVATE members------------------------------------- + + def __startup(self, shared_sim_state: ReplicSimState): + try: + log.info('Starting Replication ({},{})', self.__v_id, self.__r_id) + self.__replic_status = ReplicStatusEnum.processing_events + # even if this replic has been paused already, we need to start the sim then check for pause, else too + # much logic repeated: + self.__sim_controller.sim_run() + # now check if should be in pause state before entering the loop : + shared_sim_state.update_paused() + if shared_sim_state.need_pause(): + self.__sim_controller.sim_pause() + + except Exception as exc: + # log.error('Failed startup: {}', exc) + raise SimStartupError('Failed startup: {}'.format(exc)) + + def __loop_till_stopped(self, shared_sim_state: ReplicSimState) -> ReplicExitReasonEnum: + prev_level = log.getEffectiveLevel() + if prev_level != self.__sim_loop_log_level: + log.warning("Changing log level to {} for sim loop", log_level_name(self.__sim_loop_log_level)) + log.setLevel(self.__sim_loop_log_level) + + try: + shared_sim_state.update_exit() + replic_exit_reason = None + while replic_exit_reason is None: + if shared_sim_state.update_paused(): + if shared_sim_state.need_pause(): + self.__sim_controller.sim_pause() + else: + self.__sim_controller.sim_resume() + + replic_exit_reason = self.__step(shared_sim_state) + + return replic_exit_reason + + except RunRolePartsError as exc: + log.error(str(exc)) + raise + + finally: + if prev_level != self.__sim_loop_log_level: + log.warning("Sim loop done, restoring log level to {}", logging.getLevelName(prev_level)) + log.setLevel(prev_level) + + def __scen_transitioned_to_paused(self, before_state: SimStatesEnum): + return before_state != SimStatesEnum.paused and self.__sim_controller.state_id == SimStatesEnum.paused + + def __step(self, shared_sim_state: ReplicSimState) -> ReplicExitReasonEnum: + """ + Execute one step of evolution of the scenario replication. This steps the simulation engine. + """ + assert self.__replic_status == ReplicStatusEnum.processing_events + replic_exit_reason = None + + sim_con_state_before = self.__sim_controller.state_id + self.__sim_controller.sim_update() + + if self.__sim_controller.last_step_was_error: + log.error('Replication {},{} failed to process an event', self.__v_id, self.__r_id) + replic_exit_reason = ReplicExitReasonEnum.event_failed + + elif self.__sim_controller.max_sim_time_elapsed: + # assert self.__sim_controller.is_state(SimStatesEnum.paused) + log.warning('Replication {},{} reached max sim date-time {}', + self.__v_id, self.__r_id, self.__sim_controller.sim_time_days) + replic_exit_reason = ReplicExitReasonEnum.max_sim_time_elapsed + + elif self.__sim_controller.max_wall_clock_elapsed: + log.warning('Replication {},{} reached max real time {} (excluding pause times)', + self.__v_id, self.__r_id, self.__sim_controller.realtime_sec) + replic_exit_reason = ReplicExitReasonEnum.max_wall_clock_elapsed + + elif self.__sim_controller.num_events == 0: + # WARN level otherwise risk not seeing since part of event loop + log.warning('Replication {},{} consumed all events', self.__v_id, self.__r_id) + replic_exit_reason = ReplicExitReasonEnum.no_more_events + + elif self.__scen_transitioned_to_paused(sim_con_state_before): + log.warning('Replication {},{} paused by scenario, cannot continue', self.__v_id, self.__r_id) + replic_exit_reason = ReplicExitReasonEnum.paused_by_script + + else: + # might have been stopped externally: + shared_sim_state.update_exit() + if shared_sim_state.need_exit(): + self.__sim_controller.sim_pause() + replic_exit_reason = ReplicExitReasonEnum.stopped + + return replic_exit_reason diff --git a/origame/batch_sim/seed_table.py b/origame/batch_sim/seed_table.py new file mode 100644 index 0000000..d9c1172 --- /dev/null +++ b/origame/batch_sim/seed_table.py @@ -0,0 +1,342 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: This module exposes functions that can be used to read/write to a seed file. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import csv +import logging +from random import Random +from pathlib import Path + +# [2. third-party] + +# [3. local] +from ..core.typing import AnnotationDeclarations +from ..core.typing import Any, Either, Optional, Callable, PathType, TextIO, BinaryIO +from ..core.typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream +from ..scenario.sim_controller import MIN_RAND_SEED, MAX_RAND_SEED, MIN_VARIANT_ID, MIN_REPLIC_ID + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + + +__all__ = [ + 'SeedFileFormatError', + 'SeedFileIncompleteError', + 'SeedFileInvalidInformationError', + 'SeedTable', + 'MIN_VARIANT_ID', + 'MIN_REPLIC_ID', +] + +log = logging.getLogger('system') + +LINE_OFFSET = 1 # Offset to account for CSV file header line + + +class Decl(AnnotationDeclarations): + SeedTable = 'SeedTable' + + +# -- Class Definitions -------------------------------------------------------------------------- + +class SeedFileFormatError(Exception): + """Raised when a seed file is being read has wrong format""" + + def __init__(self, msg): + super().__init__(msg) + + +class SeedFileIncompleteError(Exception): + def __init__(self, variant_id, num_missing): + super().__init__("Missing seeds for desired seed table", variant_id, num_missing) + + +class SeedFileInvalidInformationError(Exception): + """Raised when the format is correct but the info is invalid, such as a value not being within allowed range. """ + + def __init__(self, msg): + super().__init__(msg) + + +class SeedTable: + """ + Represent the random seeds to be used for a batch simulation of N variants by M replications per variant. + The table can be saved to file in CSV format, and loaded from CSV. + + The CSV file must be in the format 'variant, replication, seed' with a header 'var,rep,seed'. + An example of a valid csv file that can be loaded by this class is: + + var,rep,seed + 1,1,454 + 1,2,399 + 2,1,09923 + 2,2,876 + 3,1,56373 + 3,2,09955 + """ + + # --------------------------- class-wide data and signals ----------------------------------- + + SeedList = List[Tuple[int, int, float]] + + VARIANT_COL = 0 + REPLIC_COL = 1 + SEED_COL = 2 + + _csv_header = ('var', 'rep', 'seed') + + # --------------------------- class-wide methods -------------------------------------------- + + @staticmethod + def from_list(seed_list: SeedList) -> Decl.SeedTable: + """Converts a list of seeds to a SeedTable object""" + + num_variants = seed_list[-1][0] + num_replics_per_variant = seed_list[-1][1] + seed_table = SeedTable(num_variants, num_replics_per_variant) + + for variant_id, replic_id, seed in seed_list: + seed_table.set_seed(variant_id, replic_id, seed) + + return seed_table + + @staticmethod + def get_csv_file_name(filename: PathType): + path = Path(filename) + if not path.suffix: + path = path.with_suffix(".csv") + + if path.suffix != ".csv": + raise ValueError("Filename '{}' has invalid suffix, must be .csv".format(filename)) + + return path + + # --------------------------- instance (self) PUBLIC methods -------------------------------- + + def __init__(self, num_variants: int, num_replics_per_variant: int, csv_path: PathType = None): + """ + If no path given, then random numbers will be generated for given number of variants and replics per variant. + Otherwise, the file must contain random seeds for the specified number of variants and replics per variant. + + :param num_variants: The number of variants expected in the seed file + :param num_replics_per_variant: The number of replications per num_variants expected in the seed file + :param csv_path: If given, file to load seeds from. + """ + + self._num_variants = num_variants + self._replics_per_variant = num_replics_per_variant + self._seeds = self._generate_seeds() + self._csv_path = None + if csv_path: + self._csv_path = self.get_csv_file_name(csv_path) + + def get_seeds_list_iter(self) -> Iterable[Tuple[int, int, int]]: + """ + Get a copy of the 2d array (list of list) representation of a seed file. + """ + for variant_id, variant_seeds in enumerate(self._seeds): + if variant_id >= MIN_VARIANT_ID: + for replic_id, seed in enumerate(variant_seeds): + if replic_id >= MIN_REPLIC_ID: + yield variant_id, replic_id, seed + + def get_seeds_list(self): + return list(self.get_seeds_list_iter()) + + def set_seed(self, variant_id: int, replic_id: int, seed: int): + """ + Set the seed for given variant and replication ID to given seed. + s from a 2d array (list of list) object. The seeds array is copied entirely, even if it is + larger than necessary. Array must have at least num_variants x num_replics_per_variant seeds (given at + construction time). + :param array2d: the array from which to get the random number generator seeds + :raises: ValueError, if insufficient seeds in array for number of variants and replications configured + """ + self._check_data_valid(variant_id, replic_id, seed) + try: + self._seeds[variant_id][replic_id] = seed + except IndexError: + raise ValueError("IDs must be >= 1, max variant_id is {}, max replic_id is {}" + .format(self._num_variants, self._replics_per_variant)) + + def get_num_variants(self) -> int: + """Number of variants supported by this seed table""" + return self._num_variants + + def get_num_replics_per_variant(self) -> int: + """Number of replications per variant supported by this seed table""" + return self._replics_per_variant + + def get_seed(self, variant_id: int, replic_id: int) -> int: + """ + Get the random seed for given variant and replication IDs. IDs must be in range of num variants and num + replications per variant. + """ + return self._seeds[variant_id][replic_id] + + def copy(self, rhs: Decl.SeedTable): + """ + Copies the seeds from given table into self. Only uses the portion of rhs that fits in self (if rhs larger + than self), or (if rhs smaller than self) only overwrites portion of self covered by rhs. + """ + num_variants = min(rhs.num_variants, self._num_variants) + num_replics_per_variant = min(rhs.num_replics_per_variant, self._replics_per_variant) + for v_id in range(1, num_variants + 1): + for r_id in range(1, num_replics_per_variant + 1): + self._seeds[v_id][r_id] = rhs.get_seed(v_id, r_id) + + def load(self): + """ + Method used to load a comma delimited CSV file. Each row of the CSV + file is a list. Each list contains a variant, replication and seed information. + + :raises: SeedFileFormatError: Raised when number of rows does not match expected number (where expected + number is var*rep. Can also be raised if seed file contains missing information (ie within a row). + :raises: SeedFileInvalidInformationError: Raised when invalid data is found within the seed file + (ie string values instead of numbers). Can also be raised if there are duplicates of any + variation-replication pair. + :raises: RuntimeError: if csv path to file not specified + """ + if self._csv_path is None: + raise ValueError("Must set seed file path before load()") + + # create temporary empty seeds array with sentinel_value values + sentinel_value = 0 + new_seeds = [[sentinel_value] * (self._replics_per_variant + MIN_REPLIC_ID) + for _ in range(self._num_variants + MIN_VARIANT_ID)] + + log.debug('Loading seeds from {}', self._csv_path) + with self._csv_path.open('r') as file: + csv_reader = csv.reader(file, delimiter=",") + for row_index, row in enumerate(csv_reader): + line_num = row_index + LINE_OFFSET + try: + variant = int(row[self.VARIANT_COL]) + replic = int(row[self.REPLIC_COL]) + seed = int(row[self.SEED_COL]) + except ValueError: + if row_index != 0 or tuple(row) != self._csv_header: + msg = "Line {}: some values are not numbers".format(line_num) + raise SeedFileInvalidInformationError(msg) + else: + continue # skip this line + + try: + self._check_data_valid(variant, replic, seed) + except ValueError as exc: + raise SeedFileInvalidInformationError("Line #{}: {}".format(line_num, exc)) + + # if the var and rep ID are in range, accept; else, ignore it, so bigger tables can be used + if (variant <= self._num_variants) and (replic <= self._replics_per_variant): + value = new_seeds[variant][replic] + if value != 0: + msg = "Line #{}: seed already defined earlier in file".format(line_num) + raise SeedFileInvalidInformationError(msg) + new_seeds[variant][replic] = seed + + # check that there are no sentinels left except in first row and col, as this would indicate that + # there were missing seeds + for variant_id, var_seeds in enumerate(new_seeds): + if variant_id >= MIN_VARIANT_ID: + num_zeros = var_seeds.count(sentinel_value) + if num_zeros > MIN_REPLIC_ID: + raise SeedFileIncompleteError(variant_id, num_zeros) + + self._seeds = new_seeds + + def save_as(self, filepath: Optional[PathType]): + """ + Saves the seed to file. If the filepath is given, it will be used, and this will become the filepath + this SeedTable is associated to. Otherwise, the file to save to must have been specified as a setting + given at initialization of SeedTable(). If not, an exception will be raised. The seed file format is + same as in load(). + + :param filepath: the file to save to (will get overwritten if exists); this replaces the csv_path + set when the seed table was instantiated; if None, the file path will be based on the + csv_path that was set when the seed table was instantiated + """ + if filepath is not None: + self._csv_path = self.get_csv_file_name(filepath) + + log.info('Saving seeds to {}', self._csv_path) + with self._csv_path.open('w', newline='') as csv_file: + csv_writer = csv.writer(csv_file, dialect='excel') + csv_writer.writerow(self._csv_header) + for v_id, variant_seeds in enumerate(self._seeds): + if v_id >= MIN_VARIANT_ID: + for r_id, replic_seed in enumerate(variant_seeds): + if r_id >= MIN_REPLIC_ID: + csv_writer.writerow([v_id, r_id, replic_seed]) + + # --------------------------- instance PUBLIC properties and safe_slots --------------------- + + num_variants = property(get_num_variants) + num_replics_per_variant = property(get_num_replics_per_variant) + + # --------------------------- instance __SPECIAL__ method overrides ------------------------- + + def __len__(self): + """Number of seeds in this table""" + num_seeds = self._num_variants * self._replics_per_variant + assert len(self.get_seeds_list()) == num_seeds + return num_seeds + + # --------------------------- instance _PROTECTED and _INTERNAL methods --------------------- + + def _generate_seeds(self): + """Returns a 2D array of seeds (size (self._num_variants + 1) x (self._replics_per_variant + 1))""" + log.debug('Generating {}x{} unique seeds', self._num_variants, self._replics_per_variant) + # get one random seed per replication + rng = Random() + seeds = rng.sample(range(MIN_RAND_SEED, MAX_RAND_SEED), self._num_variants * self._replics_per_variant) + # put in 2D array and return it: + seeds_array = [[0] * (self._replics_per_variant + MIN_REPLIC_ID)] + for variant_id in range(1, self._num_variants + 1): + start_index = (variant_id - 1) * self._replics_per_variant + stop_index = variant_id * self._replics_per_variant + variant_seeds = seeds[start_index: stop_index] + variant_seeds.insert(0, 0) + seeds_array.append(variant_seeds) + assert seeds_array[variant_id] is variant_seeds + assert len(seeds_array[variant_id]) == self._replics_per_variant + 1 + assert len(seeds_array) == self._num_variants + 1 + + return seeds_array + + def _check_data_valid(self, variant: int, replic: int, seed: int): + """ + Determine whether given arguments are valid (in range). + :param variant: The variant number to check + :param replic: The replication number to check + :param seed: The seed to check. + """ + # TODO build 3: add test for this + + if variant < MIN_VARIANT_ID: + raise ValueError("variant #{} must be >= 1".format(variant)) + + if replic < MIN_REPLIC_ID: + raise ValueError("replication #{} must be >= 1".format(replic)) + + if seed < MIN_RAND_SEED or seed > MAX_RAND_SEED: + msg = "random seed {} must be in range [{}, {}]".format(seed, MIN_RAND_SEED, MAX_RAND_SEED) + raise ValueError(msg) diff --git a/origame/core/__init__.py b/origame/core/__init__.py new file mode 100644 index 0000000..48e1faa --- /dev/null +++ b/origame/core/__init__.py @@ -0,0 +1,40 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: This package provides core functionality used by various Origame components. + +In particular it defines BridgeEmitter and BridgeSignal: these default to being aliases for BackendEmitter +and BackendSignal, respectively. Any component that uses those will automatically get a signal base class that +is determined by the host application. + +Version History: See SVN log. +""" + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5788$" + +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- PUBLIC API --------------------------------------------------------------------------------- +# import *public* symbols (classes/functions/constants) from contained modules: + +from .constants import * +from .cmd_line_args_parser import RunScenCmdLineArgs, LoggingCmdLineArgs, ConsoleCmdLineArgs, BaseCmdLineArgsParser +from .cmd_line_args_parser import AppSettings +from .singleton import Singleton +from .decorators import * +from .base_fsm import BaseFsmState, IFsmOwner +from .signaling import BackendEmitter, BackendSignal, BridgeEmitter, BridgeSignal, safe_slot +from .utils import validate_python_name, get_valid_python_name, InvalidPythonNameError +from .utils import UniqueIdGenerator, get_enum_val_name, select_object, ClockTimer, plural_if +from ._logging import LogManager, LogRecord, LogCsvFormatter, log_level_int, log_level_name +from .meta import AttributeAggregator diff --git a/origame/core/_logging.py b/origame/core/_logging.py new file mode 100644 index 0000000..b0cbbdd --- /dev/null +++ b/origame/core/_logging.py @@ -0,0 +1,267 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Common logging functionality for Origami application variants. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging +from pathlib import Path + +# [2. third-party] + +# [3. local] +from .typing import Any, Either, Optional, Callable, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # defines module members that are public; one line per string + 'LogManager', + 'LogRecord', + 'LogCsvFormatter', + 'log_level_name', + 'log_level_int', +] + +# -- Module-level objects ----------------------------------------------------------------------- + +log = logging.getLogger('system') + + +# -- Function definitions ----------------------------------------------------------------------- + +def log_level_name(level: Either[int, str]) -> str: + """ + Returns the log level name for a given level. There is no equivalent in logging module: + logging.getLevelName(obj) returns the level value if obj is name, but the level name if obj is value. + + :param level: int like logging.DEBUG, or string like 'DEBUG' + :returns: the corresponding string like 'DEBUG' + + WARNING: uses instance, so do not call in compute intensive sections of code (e.g., loops). + """ + return level if isinstance(level, str) else logging.getLevelName(level) + + +def log_level_int(level: Either[int, str]) -> int: + """ + Returns the log level integer value for a given level. There is no equivalent in logging module: + logging.getLevelName(obj) returns the level value if obj is name, but the level name if obj is integer value. + + :param level: int like logging.DEBUG, or string like 'DEBUG' + :returns: the corresponding integer value like 10 for logging.DEBUG + + WARNING: uses instance, so do not call in compute intensive sections of code (e.g., loops). + """ + return level if isinstance(level, int) else logging.getLevelName(level) + + +# -- Class Definitions -------------------------------------------------------------------------- + +class LogRecord(logging.LogRecord): + """Override logging.LogRecord's getMessage so that both .format and % are supported in log messages""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.csv_format = False + + def getMessage(self): + """ + Return the message for this LogRecord. + + Return the message for this LogRecord after merging any user-supplied + arguments with the message. + """ + msg = str(self.msg) # required per LogRecord docs + if self.args: + try: + msg = super().getMessage() + except: + msg = msg.format(*self.args) + + if self.csv_format: + msg = msg.replace('"', '""') + return msg + + +class LogManager: + """ + Manages all log setup for a process. This should be instantiated once in the main process of both + Origame variants, and once by each background replication process. + """ + + def __init__(self, stream=None, log_level: Either[int, str] = None): + self._logfile = None + + self._syslog = logging.getLogger('system') + self._usrlog = logging.getLogger('user') + + # create new level + if not hasattr(logging, 'PRINT'): + self.setup_print_logger() + + # set log levels for each logger: + if log_level is None: + log_level = logging.INFO + self._syslog.setLevel(log_level) + self._usrlog.setLevel(logging.PRINT) + + # setup the logging to a stream if requested: + self._stream = None + if stream is not None: + # create a stream handler to stream to stream + self._stream = logging.StreamHandler(stream) + self._stream.setLevel(logging.DEBUG) + # Logs to the GUI log panel + formatter = logging.Formatter('%(asctime)s.%(msecs)03d:\t%(name)s:\t%(levelname)s:\t%(message)s', + datefmt='%m/%d/%Y %H:%M:%S') + self._stream.setFormatter(formatter) + self._syslog.addHandler(self._stream) + self._usrlog.addHandler(self._stream) + + assert self.is_ready # post-condition + + @staticmethod + def setup_print_logger(): + logging.PRINT = 15 + logging.addLevelName(logging.PRINT, 'PRINT') + userlog = logging.getLogger('user') + + def userlog_print(msg, *args, **kwargs): + return userlog.log(logging.PRINT, msg, *args, **kwargs) + + userlog.print = userlog_print + + def log_to_file(self, path='.', filename='log.csv', create_path=False, write_mode='w'): + """ + Call this when logging to file is desired. Can only be called once. Output format is CSV. + :param path: override default location of log file + :param filename: override default file name of log file + :param write_mode: specify the mode to open the file (for writing, reading, appending, etc.) + :raises: RuntimeError if called previously + :raises: OSError for problems encountered opening log file + """ + + assert self.is_ready # verify that we have not been closed already + + if self._logfile is not None: + raise RuntimeError('Can only call this once per LogManager instance') + + path = Path(path) + if create_path and not path.exists(): + Path(path).mkdir(parents=True) + filepath = path / filename + + # Clear previous contents and set up header in log file + header_line = 'Time [MM/DD/YYYY HH:MM:SS.mmm],Log Name,Log-Level,Message\n' + with filepath.open(write_mode) as f: + f.write(header_line) + f.close() + + # Open the logfile using 'filepath' for 'appending' logs + self._logfile = logging.FileHandler(str(filepath)) # <- Note: this defaults to append mode + self._logfile.setLevel(logging.DEBUG) + + formatter = LogCsvFormatter('{asctime},{name},{levelname},"{message}"', style='{') + + formatter.default_time_format = '%m/%d/%Y %H:%M:%S' + formatter.default_msec_format = '%s.%03d' + + self._logfile.setFormatter(formatter) + + self._syslog.addHandler(self._logfile) + self._usrlog.addHandler(self._logfile) + + def cleanup_files(self, glob_pattern: str, path: str = '.', keep: int = 5): + """ + Cleanup existing log files that match glob_pattern. Folder containing log files is current working + director if not specified. + :param glob_pattern: pattern that will be given to glob.glob() function + :param path: folder in which to look for log files + :param keep: number of files to keep. + """ + from pathlib import Path + file_list = Path(path).glob(glob_pattern) + file_list = sorted(file_list, key=lambda f: f.stat().st_mtime) + for file in file_list[:-keep]: + try: + file.unlink() + except IOError: + # file might be locked by other Origame, leave it alone + pass + + def get_is_ready(self) -> bool: + """ + Return true if this LogManager can be used: all loggers exist. This is the only method that can + be called after close(). + """ + return (self._syslog is not None) and (self._usrlog is not None) + + def get_logfile_path(self) -> Path: + """Get the log file path, if any (None otherwise)""" + return self._logfile.baseFilename if self._logfile else None + + def get_log_stream(self): + """Get the stream that was given at initialization, if any (None otherwise)""" + return self._stream.stream if self._stream else None + + def close(self): + """ + Shutdown this logging manager. In a multithreaded process (such as for testing batch_sim.Replication), need + to disconnect self from logging system without waiting for gc. Note: once called, only is_ready can be used. + """ + + if self._logfile is not None: + self._syslog.removeHandler(self._logfile) + self._usrlog.removeHandler(self._logfile) + self._logfile.close() + self._logfile = None + + if self._stream is not None: + self._syslog.removeHandler(self._stream) + self._usrlog.removeHandler(self._stream) + self._stream = None + + self._syslog = None + self._usrlog = None + + def __del__(self): + self.close() + + is_ready = property(get_is_ready) + logfile_path = property(get_logfile_path) + log_stream = property(get_log_stream) + + +logging.setLogRecordFactory(LogRecord) + + +class LogCsvFormatter(logging.Formatter): + """Formats log messages in CSV format for files, properly escaping messages that have commas""" + + def format(self, record): + old_record_format = record.csv_format + record.csv_format = True + try: + return super().format(record) + finally: + record.csv_format = old_record_format diff --git a/origame/core/base_fsm.py b/origame/core/base_fsm.py new file mode 100644 index 0000000..8b054cc --- /dev/null +++ b/origame/core/base_fsm.py @@ -0,0 +1,231 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Provide a generic Finite State Machine (FSM) base class for objects that have states + +An object that has states should derive from IFsmOwner and is called "the FSM owner". Each of its states should +derive from BaseFsmState. The default state should be set directly by the FSM owner by setting self._state to +an instance of the proper state class. Transitions are the responsibility of each state: it should call +self._set_state(StateClass) for a transition to occur. This will automatically update the FSM owner with the +new state. State-dependent methods of the FSM owner should delegate to the currently active state. Each +state is assumed to have a numeric ID and string representation, typically achieved by creating a class that +derives from IntEnum listing the possible state, and each state class defines state_id from one of these +enum values. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging +from enum import IntEnum + +# [2. third-party] + +# [3. local] +from ..core import attrib_override_required, override_optional, override_required +from ..core.typing import AnnotationDeclarations + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # public API of module: one line per string + 'BaseFsmState', + 'IFsmOwner' +] + +# -- Module-level objects ----------------------------------------------------------------------- + +log = logging.getLogger('system') + + +class Decl(AnnotationDeclarations): + BaseFsmState = 'BaseFsmState' + + +# -- Function definitions ----------------------------------------------------------------------- + + +# -- Class Definitions -------------------------------------------------------------------------- + +class IFsmOwner: + """ + Any object that uses states should derive from this class. The _state attribute can be used by the derived + class to delegate method calls to the current state. + """ + + def __init__(self): + self._state = None + + def is_state(self, state_id: IntEnum) -> bool: + """Return True if our current state has ID state_id, False otherwise""" + return state_id == self._state.state_id + + def get_state_name(self) -> str: + """Return current state name""" + return self._state.state_name + + def get_state_id(self) -> IntEnum: + """Return current state ID""" + return self._state.state_id + + state_name = property(get_state_name) + state_id = property(get_state_id) + + def _set_state(self, state: Decl.BaseFsmState): + """ + Set the state of the FSM owner. After this is done, the _on_state_changed() is automatically called; derived + class may override as necessary to get notified of state changes. + :param state: new state + """ + prev_state = self._state + self._state = state + self._on_state_changed(prev_state) + + @override_optional + def _on_state_changed(self, prev_state: Decl.BaseFsmState): + """ + Called automatically by _set_state() to indicate a state change. The new state is self._state. + :param prev_state: the previous state + """ + pass + + +class FsmOpUnavailable: + """ + Return value proxy that automatically logs a warning when created and when called. + """ + WARNING_IS_ERROR = True + + class Error(RuntimeError): + pass + + def __init__(self, state_name: str, attr_name: str): + msg = "state '{}' does not have an attribute called '{}'".format(state_name, attr_name) + if self.WARNING_IS_ERROR: + raise self.Error(msg) + else: + log.debug("WARNING: {}", msg) + self.__state_name = state_name + self.__attr_name = attr_name + + def __call__(self, *args, **kwargs): + args = [str(arg) for arg in args] + kwargs = ['{}={}'.format(k, v) for k, v in kwargs.items()] + log.debug("WARNING: ignoring call of method {}({}) on state '{}'", + self.__attr_name, ', '.join(args + kwargs), self.__state_name) + + +class BaseFsmState: + """ + Base class for all states of a FSM. + + Note: + - derived class must override state_id + - derived class can override the base versions of enter_state and exit_state. + - FSM owner must provide _set_state() method + """ + + state_id = attrib_override_required(None) + + __state_name = None # used by get_state_name() + + def __init__(self, prev_state: Decl.BaseFsmState, fsm_owner: IFsmOwner = None): + """ + Initialize data for a new state. Set the previous state to None for the initial state, as this + automatically calls self.enter_state(). + + :param prev_state: previous state; if None, the enter_state() method is automatically called. + :param fsm_owner: the object that owns the FSM for this state. It is assumed to have a _state + attribute which will hold this instance. + """ + + assert self.state_id is not None + + self._fsm_owner = fsm_owner + self._prev_state_class = prev_state.__class__ + if prev_state is None: + log.debug('FSM {} initialized in {}', self.__get_fsm_owner_type_name(), self.state_id.name) + self.enter_state(None) + + @override_optional + def enter_state(self, prev_state: Decl.BaseFsmState): + """ + This will be called automatically by _set_state() after the FSM owner has had its state data member + reset to the new state, but before the previous state's exit_state() method is called. Most classes + don't need to override this, but can be useful if some actions should be taken only after the FSM + has new state. + :param prev_state: state that is being exited + """ + pass + + @override_optional + def exit_state(self, new_state: Decl.BaseFsmState): + """ + States that need to take action on exit can override this to cleanup etc. It is called automatically + when a derived class calls _set_state, before entering new state. + :param new_state: state being transitioned to + """ + pass + + def get_state_name(self) -> str: + """Get the name for this state. It is the string rep of enumeration constant returned by state_id().""" + if self.__state_name is None: + self.__state_name = str(self.state_id).split('.')[-1] + return self.__state_name + + state_name = property(get_state_name) + + def __getattr__(self, attr_name: str): + """Attempt to get an attribute (to read it or call it as a function) that does not exist in this state""" + return FsmOpUnavailable(self.state_name, attr_name) + + def _unsupported_op(self, op_name: str): + """ + A derived class that is base to other states can call this method when a method it provides was + not overridden, indicating that the concrete state does not support it. + """ + log.debug("WARNING: state '{}' does not have an attribute called '{}'", self.state_name, op_name) + + def _set_state(self, state_class, **kwargs): + """ + Transition to a new state. Derived class must call this to cause a transition to a new state. + The new state object is created from state_class, and set as fsm_data._state. Then _self.exit_state(new_state) + is called, followed by new_state.enter_state(). Finally, the sig_state_changed signal is emitted. + + Note: If the current state cannot be exited, or the new state cannot be created or entered, the caller + of this method will have to decide what to do. + + :param state_class: class to use for new state + :param **kwargs: arguments to give to state constructor + """ + # first create the new state, and set in FSM owner + new_state = state_class(self, fsm_owner=self._fsm_owner, **kwargs) if state_class else None + + # if this worked, can exit current state + log.debug("FSM {} exiting state {}", self.__get_fsm_owner_type_name(), self.state_name) + self.exit_state(new_state) + + # and enter new state + log.debug("FSM {} entering state {}", self.__get_fsm_owner_type_name(), new_state.state_name) + self._fsm_owner._set_state(new_state) + + new_state.enter_state(self) + + def __get_fsm_owner_type_name(self) -> str: + """Get class name of FSM owner""" + return self._fsm_owner.__class__.__name__ diff --git a/origame/core/cmd_line_args_parser.py b/origame/core/cmd_line_args_parser.py new file mode 100644 index 0000000..1b3df46 --- /dev/null +++ b/origame/core/cmd_line_args_parser.py @@ -0,0 +1,199 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: The command line argument parsing capability for the Origame application. + +This module contains the following classes: +cmd_line_args_parser: A wrapper class for the argparse module that customizes commandline parsing for the Origame + application. +SimConfig: A helper class defined within the cmd_line_args_parser class. Used to store commandline arguments parsed by + the parent class. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +from argparse import ArgumentParser, Namespace + +# [2. third-party] + +# [3. local] +from .typing import Any, Either, Optional, Callable, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream +from .decorators import override + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # public API of module + 'RunScenCmdLineArgs', + 'LoggingCmdLineArgs', + 'ConsoleCmdLineArgs', + 'BaseCmdLineArgsParser', +] + + +# -- Function definitions ----------------------------------------------------------------------- + + +# -- Class Definitions -------------------------------------------------------------------------- + +class LoggingCmdLineArgs(ArgumentParser): + """ + Common command-line args functionality for all Origame variants. + """ + + def __init__(self): + super().__init__(add_help=False) + + # NOTE: each argument must have a default! + self.add_argument("--dev-log-level", + dest='log_level', type=str, default=None, # default so we know if user wants custom + help="Log level for application (does not propagate to batch replications): " + "DEBUG, INFO, WARNING, ERROR, CRITICAL.") + self.add_argument("--dev-no-save-log", + dest='save_log', default=True, action='store_false', + help="Do not save log to a file") + self.add_argument("--dev-no-dep-warn", + dest='log_deprecated', default=True, action='store_false', + help="Turn off logging of prototype API deprecation warnings") + self.add_argument("--dev-log-raw-events", + dest='log_raw_events', default=False, action='store_true', + help="Turn on logging of sim event push/pops raw data (at warn level)") + self.add_argument("--dev-no-linking-fixes-on-load", + dest='fix_linking_on_load', default=True, action='store_false', + help="Turn off fixing of invalid links on scenario load") + + +class RunScenCmdLineArgs(ArgumentParser): + """ + Command-line arguments related to running a scenario. + """ + + def __init__(self): + super().__init__(add_help=False) + + self.add_argument("scenario_path", type=str, + help="Scenario definition file pathname. Mandatory. Can be relative path.") + + # NOTE: each remaining argument must have a default! + + # common to batch and non-batch: + self.add_argument("--loop-log-level", + type=str, default=None, # this is how we know whether user overrides the app default + help="Log level for each replication's sim loop: DEBUG, INFO, WARNING, ERROR, CRITICAL.") + self.add_argument("-t", "--max-sim-time-days", + type=float, default=None, + help="Simulation cut-off time in days. Optional. Default runs till no events (or max " + "real-time reached, if set; whichever occurs first).") + self.add_argument("-x", "--max-wall-clock-sec", + type=float, default=None, + help="Real-time cut-off time in seconds. Optional. Default runs till no events (or " + "max sim time reached, if set; whichever occurs first).") + + # only in non-batch mode: + self.add_argument("-f", "--realtime-scale", + type=float, default=None, + help="Turn on real-time mode, using the given scale factor. Default is " + "as-fast-as-possible.") + + # only in batch mode: + self.add_argument("-b", "--batch-replic-save", + default=True, action='store_false', + help="Turn off saving of final scenario state by each batch replication") + self.add_argument("-s", "--seed-file-path", + type=str, default=None, + help="Seed file pathname. Optional. Can be relative path. Default causes seeds to be " + "randomly generated.") + self.add_argument("-v", "--num-variants", + type=int, default=1, + help="The number of scenario variants to be run. Optional. Default runs a single " + "variant.") + self.add_argument("-r", "--num-replics-per-variant", + type=int, default=1, + help="The number of scenario replications to be run for a scenario variant. " + "Optional. Default runs a single replication for a variant.") + self.add_argument("-c", "--num-cores", + type=int, default=0, + help="The maximum number of cores to utilize for the configured scenario run. " + "Optional. Zero distributes batch replications across all available cores.") + + +class BaseCmdLineArgsParser(ArgumentParser): + @classmethod + def get_defaults(cls, *required: List[str], dest: Namespace = None) -> Namespace: + """ + Get the default settings. + :param required: values for command line args that are required (don't have defaults) + :param dest: If dest given, attributes are created in dest, else a new namespace is returned + """ + return cls().parse_args(args=required, namespace=dest) + + def parse_args(self, args=None, namespace=None): + """Once the namespace is populated, protect it against changing settings directly""" + if namespace is None: + namespace = AppSettings() + result = ArgumentParser.parse_args(self, args=args, namespace=namespace) + result.protected = True + return result + + +class ConsoleCmdLineArgs(BaseCmdLineArgsParser): + def __init__(self): + log_clap = LoggingCmdLineArgs() + run_scen_clap = RunScenCmdLineArgs() + super().__init__(parents=[log_clap, run_scen_clap]) + + self.add_argument("-l", "--dev-no-stdout-log", + dest='console_logging', default=True, action='store_false', + help="Log system debug messages (assuming logging is ON)") + + +class AppSettings: + """ + Application settings object created from command line arguments. Which settings it contains + depends on the command line args parser; the parser will populate it with all the command + line argument values as well as the default values (for command line args not used). + + Since an instance is basically a data structure, it is very easy to change settings (say for + testing) but this also means that typos will go unnoticed and the default value will be used + (which will typically be difficult bug to figure out as it will appear as though the setting + has no effect). For this reason, once the command line args parser is done creating the + settings object, it sets it in protected mode: the only way to further change settings after + this is via the override() method, which accepts a setting only if it exists already in the + instance. + """ + + def override(self, **kwargs): + """ + Override existing settings. The settings MUST have been obtained from one of the command + line args parsers + """ + if not set(kwargs.keys()).issubset(self.__dict__): + unknown_keys = [repr(s) for s in set(kwargs.keys()).difference(self.__dict__)] + raise ValueError('Invalid kwarg names: {} (valid are {})'.format( + ', '.join(unknown_keys), ', '.join(sorted(self.__dict__)))) + + self.__dict__.update(kwargs) + + def __setattr__(self, key, value): + """Prevent directly settings attributes when protected so that override() MUST be used""" + if key != 'protected' and hasattr(self, 'protected'): + raise RuntimeError('Settings protected, use override(**settings) method') + + object.__setattr__(self, key, value) diff --git a/origame/core/constants.py b/origame/core/constants.py new file mode 100644 index 0000000..f8bf56e --- /dev/null +++ b/origame/core/constants.py @@ -0,0 +1,55 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: This module defines constants and conversion factors common to the entire Origame application. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging + +# [2. third-party] + +# [3. local] + + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + + +__all__ = [ + # public API of module: one line per string + 'SECONDS_PER_DAY', + 'MINUTES_PER_DAYS', + 'HOURS_PER_DAYS', + 'SECONDS_TO_DAYS', + 'MINUTES_TO_DAYS', + 'HOURS_TO_DAYS', +] + +# Time conversion factors +SECONDS_PER_DAY = 86400.0 +MINUTES_PER_DAYS = 1440.0 +HOURS_PER_DAYS = 24.0 +SECONDS_TO_DAYS = 1.0 / SECONDS_PER_DAY +MINUTES_TO_DAYS = 1.0 / MINUTES_PER_DAYS +HOURS_TO_DAYS = 1.0 / HOURS_PER_DAYS + +# -- Function definitions ----------------------------------------------------------------------- + +# -- Class Definitions -------------------------------------------------------------------------- diff --git a/origame/core/decorators.py b/origame/core/decorators.py new file mode 100644 index 0000000..86e2d77 --- /dev/null +++ b/origame/core/decorators.py @@ -0,0 +1,151 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Decorators for various uses + +Decorators for various uses, including annotating function/method signatures. For use anywhere in Origame. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import inspect + +# [2. third-party] + +# [3. local] +from .typing import TypeVar, Any, Either, Optional, Callable, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # defines module members that are public; one line per string + 'override', + 'override_required', + 'override_optional', + 'attrib_override_required', + 'internal', +] + +# -- Module-level objects ----------------------------------------------------------------------- + +TAny = TypeVar('TAny') +TCallable = Callable[[Any], Any] # any callable is accepted +Decorator = Callable[[TCallable], TCallable] + + +# -- Function definitions ----------------------------------------------------------------------- + +def override(base_class: type) -> Decorator: + """ + Indicate that a method is an override of a base class method. For documentation, and checks that the method + indeed exists in the base class. If not, an assertion error will arise at import time. Example: + + >>> class Foo: + ... def base_meth(self): + ... print('foo') + ... + >>> class Bar(Foo): + ... @override(Foo) # if Foo.base_meth does not exist, AssertError will be raised at import time + ... def base_meth(self): + ... Foo.base_meth(self) + ... print('bar') + ... + >>> bar = Bar() + >>> bar.base_meth() + foo + bar + >>> print('name:', bar.base_meth.__name__) + name: base_meth + """ + if not inspect.isclass(base_class): + raise ValueError('Need base class to be given as arg to decorator') + + def check_derived_method(fn): + func_name = fn.__name__ + if not hasattr(base_class, func_name): + err_msg = "Derived method '{}' is not in {}".format(func_name, base_class.__qualname__) + raise AttributeError(err_msg) + return fn + + return check_derived_method + + +def override_required(func: TCallable) -> TCallable: + """ + Use this decorator to indicate that a method MUST be overridden in a derived class. The based class method + should raise NotImplementedError to ensure that calling a non-overridden override_required doesn't go unnoticed. + """ + return func + + +def override_optional(func: TCallable) -> TCallable: + """ + Use this decorator to indicate that a method can safely be overridden in a derived class. The base class + method should provide valid default behavior. + """ + return func + + +def attrib_override_required(default_val: TAny) -> TAny: + """ + When a base class attribute is marked with this "decorator", it MUST be overridden by the derived class. + There is currently no way to enforce this, so this is just a means to make the base class API contract explicit. + :return: default_val + """ + return default_val + + +def internal(*types: List[type]) -> Decorator: + """ + Decorator to indicate that a function should be treated as public only to the types given or, if no + types given, to types defined within the same module; the function should be treated as private for + everything else. Note: The decorator has no way of enforcing that access to the decorated function is + only through specified classes (if specified) or classes of the same module; it can only make the + intent clear to the caller. + + The decorated function must start with one (and only one) underscore (or a ValueError is raised). + + Example: + + >>> class Foo: + ... @internal(Baz) # _meth should be accessed only by Baz, assumed to be in same module or package + ... def _meth(self): + ... pass + ... + >>> + """ + + def check_valid_name(func: Callable): + func_name = func.__name__ + if not func_name.startswith('_') or func_name.startswith('__'): + raise ValueError('All internal function names must start with one and only one underscore') + + # handle the case where no types were specified: + if len(types) == 1 and type(types[0]).__name__ in ('function',): + method = types[0] + check_valid_name(method) + return method + + # when types specified, the return must be the "actual" decorator that will wrap the function: + def decorator(func): + check_valid_name(func) + return func + + return decorator diff --git a/origame/core/meta.py b/origame/core/meta.py new file mode 100644 index 0000000..f74c0ce --- /dev/null +++ b/origame/core/meta.py @@ -0,0 +1,124 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Meta classes and meta programming support. + + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging + +# [2. third-party] + +# [3. local] +from .typing import Any, Either, Optional, Callable, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + + +__all__ = [ + # public API of module: one line per string + 'AttributeAggregator' +] + +log = logging.getLogger('system') + + +# -- Function definitions ----------------------------------------------------------------------- + +# -- Class Definitions -------------------------------------------------------------------------- + + +class AttributeAggregator(type): + """ + This class is a metaclass. It is used by those classes that need to combine attributes consistently. + + This takes the META_AUTO_*_API_EXTEND class attributes of a class being + imported and combines them into the class's AUTO_*_API_CUMUL attribute. Hence each class in the part type hierarchy + ends up with its own AUTO_*_API_CUMUL attribute that contains the EXTEND items of all levels "up". The AUTO + attributes are used by BaePart to provide functionality that is common to all parts, such as editing + a part, searching its properties, accessing its scripting API, and so forth. + + Example: if class A derives from B which derives from BasePart, both A and B can define + META_AUTO_SCRIPTING_API_EXTEND. B.META_AUTO_SCRIPTING_API_EXTEND contains, as per the META_ docs in BasePart, + references to B members that should be available via auto-completion when scripting, such as B.bar1 and B.bar2; + A.META_AUTO_SCRIPTING_API_EXTEND does the same, such as A.aaa1 and A.aaa2. This this meta class will cause + B.AUTO_SCRIPTING_API_CUMUL to be ('bar1', 'bar2'), and A.AUTO_SCRIPTING_API_CUMUL to be + ('bar1', 'bar2', 'aaa1', 'aaa2'). The META_*_EXTEND members are deleted from the class once processed, + so that optional METAs can be ommitted: + + - META_AUTO_EDITING_API_EXTEND and META_AUTO_SCRIPTING_API_EXTEND: required + - META_AUTO_SEARCHING_API_EXTEND: if not given, AUTO_SEARCHING_API_CUMUL will be AUTO_EDITING_API_CUMUL + - META_AUTO_ORI_DIFFING_API_EXTEND: if not given, AUTO_ORI_DIFFING_CUMUL will be AUTO_SEARCHING_API_CUMUL + """ + + def __init__(cls, name, bases, *args): + """ + :param cls: the class that is being imported, and is ready for final initialization (ex FunctionPart, etc) + :param name: the class name + :param bases: the base classes of the class + :param args: unused arguments + """ + assert hasattr(cls, 'META_AUTO_EDITING_API_EXTEND') + + cls.__combine_api_traits(bases, 'META_AUTO_EDITING_API_EXTEND', + 'AUTO_EDITING_API_CUMUL') + cls.__combine_api_traits(bases, 'META_AUTO_SEARCHING_API_EXTEND', + 'AUTO_SEARCHING_API_CUMUL', 'AUTO_EDITING_API_CUMUL') + cls.__combine_api_traits(bases, 'META_AUTO_ORI_DIFFING_API_EXTEND', + 'AUTO_ORI_DIFFING_CUMUL', 'AUTO_SEARCHING_API_CUMUL') + cls.__combine_api_traits(bases, 'META_AUTO_SCRIPTING_API_EXTEND', + 'AUTO_SCRIPTING_API_CUMUL') + + def __combine_api_traits(cls, bases: List[type], trait_members_list_name: str, cumul_name: str, + default_cumul_name: str = None): + base_cumul_list = [] + for base in bases: + if hasattr(base, cumul_name): + base_cumul_list += getattr(base, cumul_name) + + try: + trait_members = getattr(cls, trait_members_list_name) + # must delete so that optional METAs supported: + delattr(cls, trait_members_list_name) + + except AttributeError: + if default_cumul_name is None: + raise ValueError('Class {} does not define required "{}"'.format(cls.__name__, trait_members_list_name)) + setattr(cls, cumul_name, getattr(cls, default_cumul_name)) + + else: + cls_cumul_list = [] + for item in trait_members: + attrib_names = dir(cls) + found = False + for attrib_name in attrib_names: + if getattr(cls, attrib_name) is item: + cls_cumul_list.append(attrib_name) + found = True + break + + if not found: + raise RuntimeError('BUG: attrib "{}" could not be matched to an object in class {}' + .format(attrib_name, cls.__name__)) + + assert len(cls_cumul_list) == len(trait_members) + setattr(cls, cumul_name, tuple(base_cumul_list + cls_cumul_list)) diff --git a/origame/core/signaling.py b/origame/core/signaling.py new file mode 100644 index 0000000..012dc8e --- /dev/null +++ b/origame/core/signaling.py @@ -0,0 +1,247 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Provide raw signaling class that mimics PyQt's QObject class + +Backend objects that do not interface with UI can derive from BackendEmitter and define BackendSignals. +Those that do should derive from BridgeEmitter and define BridgeSignal. Those objects will automatically +get the correct signaling baseclass as determined by the UI. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging + +# [2. third-party] + +# [3. local] +from .decorators import override_optional +from .typing import Any, Either, Optional, TypeVar, Callable, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream +from .typing import AnnotationDeclarations + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + 'BackendEmitter', + 'BackendSignal', + 'BridgeEmitter', + 'BridgeSignal', + 'safe_slot', +] + +log = logging.getLogger('system') + +TCallable = Callable[[Any], Any] # any callable is accepted + + +class Decl(AnnotationDeclarations): + BackendEmitter = 'BackendEmitter' + + +# -- Function definitions ----------------------------------------------------------------------- + +def safe_slot(fn: TCallable) -> TCallable: + """ + Return a "safetied" wrapper of fn, suitable for connecting to signals. This is needed only to match + the API of signaling systems used in GUI, since core and scenario use Qt signals and slots when imported + in GUI variant. + """ + return fn + + +# -- Class Definitions -------------------------------------------------------------------------- + +class _BackendSignalBound: + """ + This should never be instantiated directly: bound signals can only be created by object that derive + from BackendEmitter, which does this automatically. The methods are documented in the unbound version of + this class. + """ + + def __init__(self, types: List[type]): + self.__slots = [] + self.__types = types + + def connect(self, slot: Callable): + if slot not in self.__slots: + self.__slots.append(slot) + + def emit(self, *data: List[Any]): + """Call each slot with the provided data""" + for slot in self.__slots: + slot(*data) + + def disconnect(self, slot: Callable = None): + """Disconnect provided slot. If no slot provided, disconnect all slots from this signal.""" + if slot is None: + self.__slots = [] + elif slot in self.__slots: + self.__slots.remove(slot) + + def __call__(self, *args): + """Support chaining of signals (using a signal as a slot for another signal)""" + self.emit(*args) + + +class BackendSignal: + """ + Represent a (unbound) Backend Signal object. This class is designed to be a drop-in replacement for + pyqtSignal when the class that emits the signal must work with PyQt QObject. + + As with PyQt signals, define an *instance* of this class in a class that + emits pure backend signals (i.e., signals that never connect to GUI objects). The emitting instance + must derive from BackendEmitter. + + Note: The BackendEmitter creates a bound signal for the instance, from the class-wide + unbound signal, whenever the signal is accessed on the instance. Example: + + class Foo(BackendEmitter): + sig_something = BackendSignal() # unbound + + def update(): + self.sig_something.emit() # bound signal, created at runtime + + A "Foo.sig_something" refers to class-wide unbound signal object. But as soon as code uses "foo.sig_something", + where foo is an instance of Foo, BackendEmitter intercepts this to create a BridgeSignalBound instance on foo. + This is same strategy as used by PyQt for pyQtSignal's), with which BackendSignal must be compatible. Unbound + signals do not have implementations for emit, connect or disconnect. However, + in order to provide for code completion from IDE, stub methods are provided for these. + """ + + def __init__(self, *types: List[type]): + """ + :param types: array of types accepted as payload when emitted + """ + self.__types = types + self.__bound_signals = {} + + def __get__(self, obj: Any, obj_type: type) -> _BackendSignalBound: + """ + Intercept access to unbound signal on an object and create a signal bound to the object. + Note: NO LONGER USED. A different technique is used that requires BackendEmitter initialization + but is faster. It is kept here because it is too early to tell if the other technique + has limitations. + + :param obj: the object derived from BackendEmitter + :param obj_type: should be BackendEmitter + :return: the new bound signal + """ + if obj is None: + # we are being called on a class, nothing to do: + return self + + if obj in self.__bound_signals: + # we have already been called on this instance, return the cached signal + return self.__bound_signals[obj] + + # return new bound signal, after caching + obj_signal = _BackendSignalBound(self.__types) + self.__bound_signals[obj] = obj_signal + return obj_signal + + def new_bound(self) -> _BackendSignalBound: + return _BackendSignalBound(self.__types) + + def connect(self, slot: Callable): + """Connect this signal to given slot, which an be any callable. The callable will be called + with the arguments given to emit(). """ + raise NotImplementedError('BackendSignal.connect() not implemented by bound signal') + + def emit(self, *args: List[Any]): + """Emit the signal, with given arguments. The arguments should have the same types as the sequence + given to initializer of this class. """ + raise NotImplementedError('BackendSignal.emit() not implemented by bound signal') + + def disconnect(self, slot: Callable = None): + """Disconnect this signal from given slot, or from all slots if none given. """ + raise NotImplementedError('BackendSignal.disconnect() not implemented by bound signal') + + +class BackendEmitter: + """ + Base class for any signal-emitting object in the backend of Origame. Derive from this class and + define signals as class-wide BackendSignal instances. Notes: + - some methods on this class are provided strictly so BackendEmitter can be a drop-in replacement for + QObject when application does not have a GUI. + - + """ + + __signals = {} # will hold a reference to each unbound signal defined on derived classes + + def __init__(self, emitter_parent: Decl.BackendEmitter = None, thread: Any = None, thread_is_main: bool = None): + """ + Derived class must initialize base: this will find all class-wide BackendSignal instances and + create instance-specific BackendSignalBound objects that can be used to connect to, emit, and disconnect + from slots. + """ + assert thread is None, "The caller is probably expecting to be using BridgeEmitter, not BackendEmitter" + assert thread_is_main in (None, False, True) + self._emitter_parent = emitter_parent + + if BackendEmitter.__signals: + for (attr, value) in self.__signals.items(): + setattr(self, attr, value.new_bound()) + + else: + for (attr, value) in vars(self.__class__).items(): + if isinstance(value, BackendSignal): + BackendEmitter.__signals[attr] = value + setattr(self, attr, value.new_bound()) + + def getParent(self) -> Decl.BackendEmitter: + return self._emitter_parent + + def moveToThread(self, thread): + raise NotImplementedError('BackendEmitter.moveToThread() override function has not been implemented.') + + def thread(self): + raise NotImplementedError('BackendEmitter.thread() override function has not been implemented.') + + def deleteLater(self): + raise NotImplementedError('BackendEmitter.deleteLater() override function has not been implemented.') + + def startTimer(self, event: Any) -> int: + raise RuntimeError("This should never be called in console variant") + + @override_optional + def timerEvent(self, event: Any): + """This method will only be called if startTimer() was called from GUI. Never called in Console.""" + raise NotImplementedError('BackendEmitter.timerEvent() override function has not been implemented.') + + def killTimer(self, id: int): + raise RuntimeError("This should never be called in console variant") + + +"""Class to use for signals that *could* interface with UI objects when a module is imported in the GUI variant. """ +BridgeSignal = BackendSignal + +"""Base class to use for classes that use BridgeSignal.""" +BridgeEmitter = BackendEmitter + + +def setup_bridge_for_console(): + """Used only during testing: switch back to using backend classes for bridge.""" + global BridgeSignal, BridgeEmitter + BridgeSignal = BackendSignal + BridgeEmitter = BackendEmitter + + from .. import core + core.BridgeSignal = BackendSignal + core.BridgeEmitter = BackendEmitter diff --git a/origame/core/singleton.py b/origame/core/singleton.py new file mode 100644 index 0000000..a5cb255 --- /dev/null +++ b/origame/core/singleton.py @@ -0,0 +1,62 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Provides a Singleton class + +Classes that represent singletons should derive from it. +Users create instances normally but get the same instance instead. + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] + +# [2. third-party] + +# [3. local] + + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +__all__ = [ + # defines module members that are public; one line per string + 'Singleton', +] + + +# -- Class Definitions -------------------------------------------------------------------------- + + +class Singleton: + """ + Derive from this class to make the derived class a singleton. Then any derived class + instantiation is actually getting the same object. Example: + + >>> class Foo(Singleton): pass + >>> foo = Foo() + >>> foo2 = Foo() + >>> assert foo is foo2 + >>> assert id(foo) == id(foo2) + """ + + _instance = None + + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) + return cls._instance diff --git a/origame/core/typing.py b/origame/core/typing.py new file mode 100644 index 0000000..cc0412d --- /dev/null +++ b/origame/core/typing.py @@ -0,0 +1,104 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Annotation symbols standard in R4. + +See docs for the standard "typing" and "collections.abc" modules. +Use type aliases when the annotation is too verbose:: + + Range = Either[int, str, slice, List[int]] + + def func(abc: Range) -> int: + pass + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +from typing import Any # any type of object +from typing import Optional # Ex: def func(abc: Optional[int]): a can be int or None +from typing import Callable # Ex: def func(on_done: Callable[[int, str], List[int]]: on_done is a callable + # that takes an int and str (in that order), and returns a list of integers + +from typing import TextIO # Ex: def func(writer: TextIO): writer is an object that has write(str) +from typing import BinaryIO # Ex: def func(writer: BinaryIO): writer is an object that has write(bytes) + +from typing import Tuple # Ex: def func(a1: Tuple[int, int, str]): a1 is a tuple with an 2 ints and a str +from typing import List, Sequence # Ex: def func(a1: List[int], a2: Sequence[str]): a1 is a list of integers, + # whereas a2 can be a list or a tuple or other iteratable object +from typing import Set, FrozenSet # Ex: def func(s1: Set[int], s2: FrozenSet[str]): s1 is a set() of integers, + # s2 is a frozenset() of strings +from typing import NamedTuple # Ex: def func(nt: NamedTuple('Employee', [('name', str), ('id', int)])): + # nt is a collections.namedtuple('Employee', ['name', 'id']) +from typing import Iterable # iterable is a generic, dynamically generated sequence of items + # Ex: def func(iter: Iterable): iter can be used in a for loop/list comprehension + # as many times as desired +from typing import Generator # a function that has yield + +from typing import Dict # type is dict; Ex: def func(d1: Dict[int, str]): d1 maps ints to strings +from typing import KeysView # Ex: def func(m1: KeysView[int, str]): m1 is a Dict[int, str].keys() +from typing import ValuesView # Ex: def func(m1: ValuesView[int, str]): m1 is a Dict[int, str].values() +from typing import ItemsView # Ex: def func(m1: ItemsView[int, str]): m1 is a Dict[int, str].items() + +from typing import Generic, TypeVar + +# [2. third-party] + +# [3. local] + + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 6971 $" + +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + +# the following lines are solely so PyCharm can find "Either" as a symbol and provide code completion +from typing import Union as _Union, Iterator as _Iterator + +Either = _Union # Ex: def func(abc: Either[int, str, None]): abc can be int or str or None +Stream = _Iterator # iterable that can only be used once (usually because it was created by calling a + # generator function (a function that yields); once loop to end, can't loop again + +from pathlib import Path +PathType = Either[str, Path] + + +class AnnotationDeclarations: + """ + Used to define *forward declarations* for type hints (annotations). + These are only needed where a class defines methods that take and/or returns objects of its own + type, or when two objects' type hints need to refer to each other. Example: + + # in the globals section of a module: + + class Decl(AnnotationDeclarations): + Foo = 'Foo' + Bar = 'Bar' + + # further down in the module: + + class Foo: + def method(self, foo: Decl.Foo, bar: Decl.Bar): + ... + + class Bar: + def method(self, foo: Decl.Foo, bar: Decl.Bar): + ... + + The AnnotationDeclarations base class must be used and will ensure (at import type) that the derived + class name is Decl and that all symbols match their string value. + """ + pass \ No newline at end of file diff --git a/origame/core/utils.py b/origame/core/utils.py new file mode 100644 index 0000000..17dc66d --- /dev/null +++ b/origame/core/utils.py @@ -0,0 +1,601 @@ +# This file is part of Origame. See the __license__ variable below for licensing information. +# +# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# +# For coding standards that apply to this file, see the project's Coding Standards document, +# r4_coding_standards.html, in the project's docs/CodingStandards/html folder. + +""" +*Project - R4 HR TDP*: Various core utility functions and classes + +Version History: See SVN log. +""" + +# -- Imports ------------------------------------------------------------------------------------ + +# [1. standard library] +import logging +import re +import keyword +from datetime import timedelta +from time import time +from cProfile import Profile +from enum import Enum +from pathlib import Path +import sched + +# [2. third-party] +from dateutil.relativedelta import relativedelta + +# [3. local] +from .typing import Any, Either, Optional, Callable, TypeVar, PathType, TextIO, BinaryIO +from .typing import List, Tuple, Sequence, Set, Dict, Iterable, Stream + +# -- Meta-data ---------------------------------------------------------------------------------- + +__version__ = "$Revision: 5800$" +__license__ = """This file can ONLY be copied, used or modified according to the terms and conditions + described in the LICENSE.txt located in the root folder of the Origame package.""" +__copyright__ = "(c) Her Majesty the Queen in Right of Canada" + +# -- Module-level objects ----------------------------------------------------------------------- + + +__all__ = [ + # public API of module: one line per string + 'validate_python_name', + 'get_valid_python_name', + 'InvalidPythonNameError', + 'get_enum_val_name', + 'UniqueIdGenerator', + 'BlockProfiler', + 'ori_profile', + 'ClockTimer', + 'plural_if', + 'bool_to_not', + 'GuardFlag', + 'rel_to_timedelta', + 'timedelta_to_rel', +] + +log = logging.getLogger('system') + +TAny = TypeVar('TAny') +TCallable = Callable[[Any], Any] # any callable is accepted + + +# -- Function definitions ----------------------------------------------------------------------- + +def get_verified_eval(value_in_str: str): + """ + Checks if a string can pass eval(). If it can, the eval() value will be returned; otherwise a SyntaxError will be + thrown. + :param value_in_str: The string to be checked + :return: The return value of the eval(value_in_str) + :raises: whatever exception is raised by eval(); an additional field 'text' is created, holding value_in_str + """ + try: + obj_verified = eval(value_in_str) + except Exception as e: + e.text = value_in_str + raise + + return obj_verified + + +def get_verified_repr(val: Any) -> str: + """ + Getting a verified repr from val means eval(repr(val)) == val is true. + :param val: The object from which the repr is derived + :return: The repr on the val + :raise: Exception if repr() or eval() fails. + :raise: RuntimeError if eval(repr(val)) == val is false. + """ + cell_repr = repr(val) + cell_eval = eval(cell_repr) + + if val != cell_eval: + raise RuntimeError("The string representation of the given value cannot pass eval()") + + return cell_repr + + +def validate_python_name(name: str): + """ + This function validates whether or not the input name is a valid Python name. If the name is valid, the function + returns; however, if the input name is invalid, an InvalidPythonNameError is raised describing the format error + contains a proposal for a corrected version of the name. + + Invalid names are names that: (Note: Corresponding auto-corrections applied are shown in brackets.) + - Are reserved keywords (prepend 'Obj_' to name) + - Start with a number (prepend underscore '_' to name) + - Contain any non-alpha-numeric character except the underscore (replace invalid character with underscore '_') + + :param name: The name to be validated. + :raises: InvalidPythonNameError - An exception containing a description of the error and a proposed corrected + name. + """ + # No name case + if name is None: + raise InvalidPythonNameError(msg='Name cannot be None', invalid_name=name, proposed_name='unnamed') + + # This case covers a valid name + regex_py_lex = '[_A-Za-z][_a-zA-Z0-9]*' + if re.fullmatch(regex_py_lex, name) and not keyword.iskeyword(name): + return + + # For invalid names, the following apply + + # Invalid case: keyword used (prepend 'Obj_') + if keyword.iskeyword(name): + new_name = 'Obj_{}'.format(name) + raise InvalidPythonNameError( + msg="Name cannot be a Python keyword.", invalid_name=name, proposed_name=new_name) + + # Invalid case: invalid characters used + # - numeric character is the first character (prepend '_') + # - non-alpha-numeric character(s) used (replace with '_') + + bad_format = False + orig_name = name + regex_num_first = '[0-9]' + if re.fullmatch(regex_num_first, name[0]): + name = '_{}'.format(name) + bad_format = True + + regex_valid_char = '[_a-zA-Z0-9]' + name = list(name) # str -> list[char]: allows assignment at index + for index, char in enumerate(name): + if not re.fullmatch(regex_valid_char, char): + name[index] = '_' + bad_format = True + name = "".join(name) # list -> str + + if bad_format: + raise InvalidPythonNameError( + msg="Name can only contain letters and underscores and must not commence with a numeral.", + invalid_name=orig_name, proposed_name=name) + + +def get_valid_python_name(name: str) -> str: + """ + This function validates whether the input name is a valid Python name. If the name is valid it is returned as-is. + If the input name is not valid, a corrected version of the name is returned. + + Invalid names are names that: (Note: Corresponding auto-corrections applied are shown in brackets.) + - Are reserved keywords (prepend 'Obj_' to name) + - Start with a number (prepend underscore '_' to name) + - Contain any non-alpha-numeric character except the underscore (replace invalid character with underscore '_') + + :param name: the name to be verified and augmented if required. + :returns: The original ìnput 'name', if valid, or a corrected version of the input 'name' if invalid. + """ + invalid = True + while invalid: + try: + validate_python_name(name) + invalid = False + except InvalidPythonNameError as e: + log.warning('Invalid part or link name: {}. {} Changing to: {}.', name, str(e), e.proposed_name) + name = e.proposed_name + return name + + +# -- Class Definitions -------------------------------------------------------------------------- + + +class InvalidPythonNameError(ValueError): + """ + This class provides a class-specific implementation of the built-in ValueError exception. + It is raised when a string is determined to be an invalid Python name. + """ + + def __init__(self, msg: str, invalid_name: str = None, proposed_name: str = None, scenario_location: str = None): + """ + :param msg: A message describing why the Python name is invalid. + :param invalid_name: The name that is the subject of the Error. + :param proposed_name: A proposed correction for the invalid name. + :param scenario_location: The scenario hierarchy location of the invalid name. + """ + super(InvalidPythonNameError, self).__init__(msg) + self.invalid_name = invalid_name + self.proposed_name = proposed_name + self.scenario_location = scenario_location + + +def get_enum_val_name(enum_obj: Enum) -> str: + """Get the name for an enumeration value. MyEnum.some_val returns "some_val".""" + return enum_obj.name + + +def rel_to_timedelta(delta: relativedelta) -> timedelta: + """Convert a dateutil.relativedelta to a datetime.timedelta""" + return timedelta(days=delta.days, hours=delta.hours, minutes=delta.minutes, + seconds=delta.seconds, microseconds=delta.microseconds) + + +def timedelta_to_rel(delta: timedelta) -> relativedelta: + """Convert a datetime.timedelta to a dateutil.relativedelta""" + # the normalized() distributes the days/seconds/micro so hours and minutes attributes have integer values + return relativedelta(days=delta.days, seconds=delta.seconds, microseconds=delta.microseconds).normalized() + + +class UniqueIdGenerator: + """ + Generates a unique id every time the static method get_new_id() is called. + This class is *not* multi-thread safe (there is a possibility that two threads + would get the same id). The start ID can be configured. + """ + + __registry = [] + + def __init__(self): + self.__next_id = 0 + self.__registry.append(self) + + def __del__(self): + self.__registry.remove(self) + + def get_new_id(self) -> int: + """ + This function returns an application-unique ID each time it is called. + """ + part_id = self.__next_id + self.__next_id += 1 + return part_id + + @classmethod + def reset(cls): + """Reset the ID counter. This should only be used in unit tests.""" + for gen in cls.__registry: + gen.__next_id = 0 + + +def select_object(objects: List[TAny], attr_path: str, val: TAny) -> TAny: + """ + Find the object that has the given attribute equal to the given value. + + :param objects: set of objects to look through + :param attr_path: the attribute path, in dot notation + :param val: the value to match + :return: the object, or None if none found + + Example: + + >>> objects = [part1, part2, part3, part4] + >>> obj = select_object(objects, "part_frame.name", "foo") + >>> assert obj.part_frame.name == "foo" # passes if there is such an object + >>> obj = select_object(objects, "part_frame.size", 123) + >>> assert obj.part_frame.width == 123 # passes if there is such an object + """ + path = attr_path.split('.') + for obj in objects: + orig_obj = obj + for p in path: + obj = getattr(obj, p) + if obj == val: + return orig_obj + return None + + +class BlockProfiler(Profile): + """ + This can be used to profile various portions of Origame. Use like this: + + with BlockProfiler(scenario_path): + ...stuff to profile... + + If scenario_path is c:\\folder\path.ori, then when the "with" clauses is done, the profiling data is + automatically saved to c:\\folder\path.pstats and can be opened with any pstats-compatible tool + (PyCharm, gprof2d, etc). If out_info data was given, like this: + + with BlockProfiler(scenario_path, v=1, r=2): + ...stuff to profile... + + then the output file will be c:\\folder\path_v_1_r_2.pstats so it is easy to use the profile in multiple + places in one run (out_data can be an identifier for section of code). + """ + + def __init__(self, scen_path: PathType, **out_info): + """If out_info is not empty, appends their string rep to the stats file path name""" + Profile.__init__(self) + scen_path = Path(scen_path) + if out_info: + extra = ['{}_{}'.format(name[0], val) for name, val in out_info.items()] + extra_str = '_'.join(extra) + scen_path = scen_path.with_name(scen_path.stem + '_' + extra_str) + self.out_path = scen_path.with_suffix('.pstats') + + def __enter__(self): + log.warning("Profiling starting") + self.enable() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.disable() + self.dump_stats(str(self.out_path)) + log.warning("Profiling data saved to {}", self.out_path) + return False + + +def ori_profile(func: TCallable, scen_path: PathType, **out_info) -> TCallable: + """ + Decorator that can be used to cause every call to given function to get profiled to a .pstats file. + + :param func: the function to be profiled when called + :param scen_path: the scenario file path + :param out_info: additional optional info to insert in output file path + :return: the callable that calls func such that it can be profiled + + Note: scen_path and out_info are the same as for BlockProfiler (see class docs and its __init__ docs). + """ + import functools + + @functools.wraps(func) + def wrapper(*args, **kwargs): + with BlockProfiler(scen_path, **out_info): + result = func(*args, **kwargs) + return result + + return wrapper + + +class ClockTimer: + """ + Track wall-clock time. The time stops increasing after pause(), resumes increasing + after resume(). The get_total_time_sec() (and associated property) only update on read. + """ + + def __init__(self, pause: bool = False): + """ + Start a timer. By default, start advancing time immediately + :param pause: if True, do not start timing immediately, will start at next resume() + """ + self._start_time_sec = time() + self._total_time_sec = 0 + self._paused = pause + + def reset(self, seconds: float = 0.0, pause: bool = False): + """ + Reset the timer. + :param seconds: reset the total_time_sec to this value and, if pause=True, pause (don't track time until + next resume()); if pause=False, immediately resume (next call to total_time_sec is almost certain to be + larger than seconds) + :param pause: if true, pause the timer, otherwise resume (starts timing) immediately + """ + self._start_time_sec = time() + self._total_time_sec = seconds + self._paused = pause + + def pause(self): + """Pause timer. The total_time_sec() will return constant value until resume() called again.""" + if not self._paused: + self._total_time_sec += (time() - self._start_time_sec) + self._paused = True + + def resume(self): + """Resume the timer. The time starts counting time again.""" + if self._paused: + self._start_time_sec = time() + self._paused = False + + def get_is_paused(self) -> bool: + return self._paused + + def get_total_time_sec(self) -> float: + """Get time in seconds since __init__(), not including pause periods.""" + if self._paused: + return self._total_time_sec + + new_time = time() + self._total_time_sec += (new_time - self._start_time_sec) + self._start_time_sec = new_time + return self._total_time_sec + + total_time_sec = property(get_total_time_sec) + is_paused = property(get_is_paused) + + +def plural_if(condition: Either[List[Any], bool], plural: str = 's', singular: str = '') -> str: + """ + Choose between plural and singular based on a condition. + + :param condition: if a boolean, True indicates pluralize, False do not. If container, pluralize if more than 1 item + :param plural: the letter to return if plural + :param singular: when singular, what to return + :return: plural if condition is True else return singular + + Example: + "Found {} item{}".format(num_items, plural_if(num_items > 1)) + "Found {} item{}".format(len(found), plural_if(found))) + "Found {} {}".format(len(found), plural_if(found, 'geese', 'goose'))) + """ + try: + num_nodes = len(condition) + condition = (num_nodes > 1) + except TypeError: + # not a container, use condition as boolean + condition = bool(condition) + + return plural if condition else singular + + +def bool_to_not(flag: bool) -> str: + """ + Returns empty string if flag is False, or "not " otherwise. Example: + + log.info("This flag is {}true", bool_to_not(your_flag)) + + will log "This flag is true" if your_flag is True, but "This flag is not true" otherwise. Note the + missing space between the placeholder and what will follow the "not" + """ + return "" if flag else "not " + + +class FileLock: + """ + Context manager to lock a scenario input or output file to synchronize access by simultaneously + executing replications. The file name of the lock is the file to be locked suffixed with "_lock_indicator". + """ + + def __init__(self, file_name: str, max_attempts: int = 50, attempt_interval: int = 3): + """ + :param file_name: The name of the file that is to be locked. + :param max_attempts: The max number of the attempts of acquiring a lock. + :param attempt_interval: The interval between two consecutive attempts. In seconds. + """ + self.__path = Path(file_name + "_lock_indicator") + self.__max_attempts = max_attempts + self.__attempt_interval = attempt_interval + self.__file = None + + def __enter__(self): + """ + Locks the file given in the constructor. + """ + con_scheduler = sched.scheduler() + locking_failed = True + + def attempt_to_lock(num_attempt=0): + nonlocal locking_failed + if num_attempt < self.__max_attempts: + try: + self.__file = self.__path.open('x+') + locking_failed = False + except: + log.debug("Unable to lock: path={}, num_attempt={}", str(self.__path), num_attempt) + nxt = num_attempt + 1 + con_scheduler.enter(self.__attempt_interval, 1, attempt_to_lock, argument=(nxt,)) + + con_scheduler.enter(0, 1, attempt_to_lock) + con_scheduler.run() + + if locking_failed: + err_msg = "Unable to lock the file after {} attempt{}. The file: {}".format( + self.__max_attempts, plural_if(self.__max_attempts > 1), self.__path) + log.error(err_msg) + raise TimeoutError(err_msg) + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + Unlocks the file given in the constructor. + :param exc_type: (unused) + :param exc_val: (unused) + :param exc_tb: (unused) + """ + try: + self.__file.close() + self.__path.unlink() + except: + log.debug("Unable to delete: path={}", str(self.__path)) + + def __del__(self): + try: + self.__file.close() + self.__path.unlink() + except: + log.debug("Unable to delete: path={}", str(self.__path)) + + +class IJsonable: + """ + Classes that represent data structures that must be output to a JSON-compatible format can derive + from this class. The class provides two methods to generate a JSON-compatible representation of self, + and the other to set self attributes from a JSON-compatible representation of self. + """ + + def __init__(self, _unknown: Dict[str, Any], *prop_names: List[str]): + """ + :param prop_names: optional, list of property names to package into and out of JSON-compatible representations + :param _unknown: dict of parameters not recognized (create via **unknown) + """ + if _unknown: + msg = "These JSON fields are not recognized (likely an obsolete schema): {}" + fields = ', '.join(_unknown) + log.error(msg, fields) + raise ValueError(msg.format(fields)) + + self.__json_prop_names = prop_names + + def to_json(self) -> Dict[str, Any]: + """ + Return a JSON-compatible map of public attributes of self. Note: properties are not + considered public attributes. To include public properties, define their names in the initializer. + """ + return {key: getattr(self, key) for key in self.__get_valid_keys_derived()} + + def from_json(self, data: Dict[str, Any]): + """ + Set the state of the derived class from the JSON data provided. Each key MUST be the name of an attribute + that already exists in self, either as a pure data member or as a property. A ValueError will be raised + otherwise. + """ + valid_keys = self.__get_valid_keys_derived() + for key in data: + if key in valid_keys: + setattr(self, key, data[key]) + else: + raise ValueError('Invalid key "{}" in JSON data', key) + + def __str__(self): + def attr_val(key): + return key.capitalize().replace('_', ' '), getattr(self, key) + + return '\n'.join('{}: {}'.format(*attr_val(key)) for key in sorted(self.__get_valid_keys_derived())) + + def __get_valid_keys_derived(self) -> List[str]: + valid_keys = {attr_name for attr_name in vars(self) if not attr_name.startswith('_')} + valid_keys.update(self.__json_prop_names) + return valid_keys + + +class GuardFlag: + """ + Facilitates the use of "guard flags" by making them exception-safe and automatically restored, even + across nested calls. Guard flags are flags that are set before calling a method, so that some nested + action will not occur; the flag must be set back to default when method done. Without this class, + + - it is a pain to ensure the flag is reset despite exception being raised by method; + - it is a pain to determine what value the flag should be reset to (normally, the value on entry) + + Example: + class Foo: + def __init__(self): + self.__nested = GuardFlag(False) + def doABC(self): + # called when user clicks button, or by doAC + ...do A... + self.__doC() + ...do B... + def doAC(self): + # called when user selects text + with self.__nested(True): + self.doABC() + def __doC(self): + if not self.__nested: + do C + """ + + def __init__(self, init: bool): + self.__flag_value = init + self.__flag_on_enter = [] + + def set(self, value: bool): + self.__flag_value = value + + def __call__(self, on_entry: bool): + self.__on_entry_value = on_entry + return self + + def __bool__(self): + return self.__flag_value + + def __enter__(self): + self.__flag_on_enter.append(self.__flag_value) + self.__flag_value = self.__on_entry_value + return self.__flag_value + + def __exit__(self, exc_type, exc_val, exc_tb): + self.__flag_value = self.__flag_on_enter.pop() + return False diff --git a/origame/docs/ORIGAME Tutorial DRDC-RDDC-2018-D173.PDF b/origame/docs/ORIGAME Tutorial DRDC-RDDC-2018-D173.PDF new file mode 100644 index 0000000..3a312d9 Binary files /dev/null and b/origame/docs/ORIGAME Tutorial DRDC-RDDC-2018-D173.PDF differ diff --git a/origame/docs/Origame 0.7.0 beta (2017-09-13) - User Manual.pdf b/origame/docs/Origame 0.7.0 beta (2017-09-13) - User Manual.pdf new file mode 100644 index 0000000..9f2055c Binary files /dev/null and b/origame/docs/Origame 0.7.0 beta (2017-09-13) - User Manual.pdf differ diff --git a/origame/docs/examples_html/example_1.html b/origame/docs/examples_html/example_1.html new file mode 100644 index 0000000..e945af1 --- /dev/null +++ b/origame/docs/examples_html/example_1.html @@ -0,0 +1,13 @@ + + + + + Origame Example 1 + + + + Home + +

The example 1

+ + \ No newline at end of file diff --git a/origame/docs/examples_html/example_2.html b/origame/docs/examples_html/example_2.html new file mode 100644 index 0000000..b4dd6f4 --- /dev/null +++ b/origame/docs/examples_html/example_2.html @@ -0,0 +1,13 @@ + + + + + Origame Example 2 + + + + Home + +

The example 2

+ + \ No newline at end of file diff --git a/origame/docs/examples_html/example_3.html b/origame/docs/examples_html/example_3.html new file mode 100644 index 0000000..59e01f5 --- /dev/null +++ b/origame/docs/examples_html/example_3.html @@ -0,0 +1,13 @@ + + + + + Origame Example 3 + + + + Home + +

The example 3

+ + \ No newline at end of file diff --git a/origame/docs/examples_html/index.html b/origame/docs/examples_html/index.html new file mode 100644 index 0000000..96e97a3 --- /dev/null +++ b/origame/docs/examples_html/index.html @@ -0,0 +1,13 @@ + + + + + Origame Examples + + + +

Example 1

+

Example 2

+

Example 3

+ + \ No newline at end of file diff --git a/origame/docs/licensing/LICENSE.html b/origame/docs/licensing/LICENSE.html new file mode 100644 index 0000000..00bfc78 --- /dev/null +++ b/origame/docs/licensing/LICENSE.html @@ -0,0 +1,903 @@ + + + + + + + + + + + + + + + + + + +
+ +

************************

+ +

ORIGAME SOFTWARE LICENSE

+ +

************************

+ +

 

+ +

 

+ +

Ownership and Administration

+ +

============================

+ +

 

+ +

The ORIGAME software and all accompanying documentation and +material (hereinafter

+ +

called "the Software") are subject to copyright, +with all rights reserved to Her

+ +

Majesty the Queen in Right of Canada.

+ +

 

+ +

The Software is administered by Defence +Research & Development Canada (DRDC), located at

+ +

60 Moodie Drive, Ottawa, Ontario, K1A 0K2.

+ +

 

+ +

 

+ +

Approved Users

+ +

==============

+ +

 

+ +

The Software may only be used by the following individuals +(hereinafter called "Approved Users"):

+ +

 

+ +

1. Employees of the Government of Canada.

+ +

 

+ +

2. Contractors that are currently engaged in a contract with +the Government of

+ +

   Canada and that have a requirement to use the +Software in the execution of their work

+ +

   for the Government +of Canada.

+ +

 

+ +

Individuals other than Approved Users may not use the +Software and must destroy any copies of the

+ +

Software in their possession unless they have obtained prior +written permission from DRDC to use

+ +

the Software.

+ +

 

+ +

 

+ +

Approved Use

+ +

============

+ +

 

+ +

Users of the Software must adhere to the following +restrictions regarding their use

+ +

of the Software (herinafter called +"Approved Use"):

+ +

 

+ +

1. The Software must only be used to support the execution of +work

+ +

   for the Government +of Canada.

+ +

 

+ +

2. The Software must not be modified without prior written +permission from DRDC.

+ +

 

+ +

3. The Software must not be provided to others unless the +recipients are

+ +

   Approved Users and +their use of the Software adheres with the Approved Use.

+ +

 

+ +

4. Contractors must further adhere to the terms of their contract +with the

+ +

   Government of +Canada with respect to their use of the Software.

+ +

 

+ +

 

+ +

Contact

+ +

=======

+ +

 

+ +

    Stephen Okazawa

+ +

    Defence Scientist, DRDC

+ +

    101 Colonel By Drive, Ottawa, Ontario, K1A 0K2

+ +

    Tel.: (613) +901-9772

+ +

    E-mail: +stephen.okazawa@forces.gc.ca

+ +

 

+ +

 

+ +
+ + + + diff --git a/origame/docs/licensing/LICENSE_files/colorschememapping.xml b/origame/docs/licensing/LICENSE_files/colorschememapping.xml new file mode 100644 index 0000000..6a0069c --- /dev/null +++ b/origame/docs/licensing/LICENSE_files/colorschememapping.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/origame/docs/licensing/LICENSE_files/filelist.xml b/origame/docs/licensing/LICENSE_files/filelist.xml new file mode 100644 index 0000000..bd74243 --- /dev/null +++ b/origame/docs/licensing/LICENSE_files/filelist.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/origame/docs/licensing/LICENSE_files/themedata.thmx b/origame/docs/licensing/LICENSE_files/themedata.thmx new file mode 100644 index 0000000..3d2a437 Binary files /dev/null and b/origame/docs/licensing/LICENSE_files/themedata.thmx differ diff --git a/origame/docs/python_reference.chm b/origame/docs/python_reference.chm new file mode 100644 index 0000000..6710321 Binary files /dev/null and b/origame/docs/python_reference.chm differ diff --git a/origame/docs/python_tutorials.chm b/origame/docs/python_tutorials.chm new file mode 100644 index 0000000..6710321 Binary files /dev/null and b/origame/docs/python_tutorials.chm differ diff --git a/origame/docs/user_manual_html/_images/2d_model_view.png b/origame/docs/user_manual_html/_images/2d_model_view.png new file mode 100644 index 0000000..1789018 Binary files /dev/null and b/origame/docs/user_manual_html/_images/2d_model_view.png differ diff --git a/origame/docs/user_manual_html/_images/actor_part_and_hierarchy.png b/origame/docs/user_manual_html/_images/actor_part_and_hierarchy.png new file mode 100644 index 0000000..a305ab0 Binary files /dev/null and b/origame/docs/user_manual_html/_images/actor_part_and_hierarchy.png differ diff --git a/origame/docs/user_manual_html/_images/alerts.png b/origame/docs/user_manual_html/_images/alerts.png new file mode 100644 index 0000000..2b9a6f0 Binary files /dev/null and b/origame/docs/user_manual_html/_images/alerts.png differ diff --git a/origame/docs/user_manual_html/_images/application_log.png b/origame/docs/user_manual_html/_images/application_log.png new file mode 100644 index 0000000..9072720 Binary files /dev/null and b/origame/docs/user_manual_html/_images/application_log.png differ diff --git a/origame/docs/user_manual_html/_images/application_status.png b/origame/docs/user_manual_html/_images/application_status.png new file mode 100644 index 0000000..91c1afc Binary files /dev/null and b/origame/docs/user_manual_html/_images/application_status.png differ diff --git a/origame/docs/user_manual_html/_images/batch_data_processing.png b/origame/docs/user_manual_html/_images/batch_data_processing.png new file mode 100644 index 0000000..385dde4 Binary files /dev/null and b/origame/docs/user_manual_html/_images/batch_data_processing.png differ diff --git a/origame/docs/user_manual_html/_images/batch_sim_settings.png b/origame/docs/user_manual_html/_images/batch_sim_settings.png new file mode 100644 index 0000000..8d60b46 Binary files /dev/null and b/origame/docs/user_manual_html/_images/batch_sim_settings.png differ diff --git a/origame/docs/user_manual_html/_images/console_variant_batch_mode.png b/origame/docs/user_manual_html/_images/console_variant_batch_mode.png new file mode 100644 index 0000000..796e49a Binary files /dev/null and b/origame/docs/user_manual_html/_images/console_variant_batch_mode.png differ diff --git a/origame/docs/user_manual_html/_images/context_help.png b/origame/docs/user_manual_html/_images/context_help.png new file mode 100644 index 0000000..a430305 Binary files /dev/null and b/origame/docs/user_manual_html/_images/context_help.png differ diff --git a/origame/docs/user_manual_html/_images/debugger.png b/origame/docs/user_manual_html/_images/debugger.png new file mode 100644 index 0000000..f86e197 Binary files /dev/null and b/origame/docs/user_manual_html/_images/debugger.png differ diff --git a/origame/docs/user_manual_html/_images/editor_actor.png b/origame/docs/user_manual_html/_images/editor_actor.png new file mode 100644 index 0000000..f9b2558 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_actor.png differ diff --git a/origame/docs/user_manual_html/_images/editor_button.png b/origame/docs/user_manual_html/_images/editor_button.png new file mode 100644 index 0000000..e7d2eb8 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_button.png differ diff --git a/origame/docs/user_manual_html/_images/editor_clock.png b/origame/docs/user_manual_html/_images/editor_clock.png new file mode 100644 index 0000000..33d0957 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_clock.png differ diff --git a/origame/docs/user_manual_html/_images/editor_data.png b/origame/docs/user_manual_html/_images/editor_data.png new file mode 100644 index 0000000..2482027 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_data.png differ diff --git a/origame/docs/user_manual_html/_images/editor_datetime.png b/origame/docs/user_manual_html/_images/editor_datetime.png new file mode 100644 index 0000000..2f95f50 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_datetime.png differ diff --git a/origame/docs/user_manual_html/_images/editor_function.png b/origame/docs/user_manual_html/_images/editor_function.png new file mode 100644 index 0000000..a6d4076 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_function.png differ diff --git a/origame/docs/user_manual_html/_images/editor_info.png b/origame/docs/user_manual_html/_images/editor_info.png new file mode 100644 index 0000000..a478e4f Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_info.png differ diff --git a/origame/docs/user_manual_html/_images/editor_library.png b/origame/docs/user_manual_html/_images/editor_library.png new file mode 100644 index 0000000..ce10398 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_library.png differ diff --git a/origame/docs/user_manual_html/_images/editor_plot.png b/origame/docs/user_manual_html/_images/editor_plot.png new file mode 100644 index 0000000..8b509ce Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_plot.png differ diff --git a/origame/docs/user_manual_html/_images/editor_pulse.png b/origame/docs/user_manual_html/_images/editor_pulse.png new file mode 100644 index 0000000..ef1684b Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_pulse.png differ diff --git a/origame/docs/user_manual_html/_images/editor_sheet.png b/origame/docs/user_manual_html/_images/editor_sheet.png new file mode 100644 index 0000000..83b7cb5 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_sheet.png differ diff --git a/origame/docs/user_manual_html/_images/editor_sql.png b/origame/docs/user_manual_html/_images/editor_sql.png new file mode 100644 index 0000000..4b80f3f Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_sql.png differ diff --git a/origame/docs/user_manual_html/_images/editor_table.png b/origame/docs/user_manual_html/_images/editor_table.png new file mode 100644 index 0000000..1fde94a Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_table.png differ diff --git a/origame/docs/user_manual_html/_images/editor_time.png b/origame/docs/user_manual_html/_images/editor_time.png new file mode 100644 index 0000000..4cbc496 Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_time.png differ diff --git a/origame/docs/user_manual_html/_images/editor_variable.png b/origame/docs/user_manual_html/_images/editor_variable.png new file mode 100644 index 0000000..d0888bf Binary files /dev/null and b/origame/docs/user_manual_html/_images/editor_variable.png differ diff --git a/origame/docs/user_manual_html/_images/event_queue.png b/origame/docs/user_manual_html/_images/event_queue.png new file mode 100644 index 0000000..7a71ff6 Binary files /dev/null and b/origame/docs/user_manual_html/_images/event_queue.png differ diff --git a/origame/docs/user_manual_html/_images/example_ifx_levels.png b/origame/docs/user_manual_html/_images/example_ifx_levels.png new file mode 100644 index 0000000..0050554 Binary files /dev/null and b/origame/docs/user_manual_html/_images/example_ifx_levels.png differ diff --git a/origame/docs/user_manual_html/_images/frames_visible_invisible.png b/origame/docs/user_manual_html/_images/frames_visible_invisible.png new file mode 100644 index 0000000..cba9dd6 Binary files /dev/null and b/origame/docs/user_manual_html/_images/frames_visible_invisible.png differ diff --git a/origame/docs/user_manual_html/_images/ifx_parts_marker_bar.png b/origame/docs/user_manual_html/_images/ifx_parts_marker_bar.png new file mode 100644 index 0000000..8702832 Binary files /dev/null and b/origame/docs/user_manual_html/_images/ifx_parts_marker_bar.png differ diff --git a/origame/docs/user_manual_html/_images/ifx_parts_ports_and_up_marker.png b/origame/docs/user_manual_html/_images/ifx_parts_ports_and_up_marker.png new file mode 100644 index 0000000..94d52e1 Binary files /dev/null and b/origame/docs/user_manual_html/_images/ifx_parts_ports_and_up_marker.png differ diff --git a/origame/docs/user_manual_html/_images/import_symbols.png b/origame/docs/user_manual_html/_images/import_symbols.png new file mode 100644 index 0000000..3adfd58 Binary files /dev/null and b/origame/docs/user_manual_html/_images/import_symbols.png differ diff --git a/origame/docs/user_manual_html/_images/indicators_1.png b/origame/docs/user_manual_html/_images/indicators_1.png new file mode 100644 index 0000000..a786794 Binary files /dev/null and b/origame/docs/user_manual_html/_images/indicators_1.png differ diff --git a/origame/docs/user_manual_html/_images/indicators_2.png b/origame/docs/user_manual_html/_images/indicators_2.png new file mode 100644 index 0000000..a29a8e1 Binary files /dev/null and b/origame/docs/user_manual_html/_images/indicators_2.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_0.png b/origame/docs/user_manual_html/_images/link_creation_0.png new file mode 100644 index 0000000..873ee85 Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_0.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_1.png b/origame/docs/user_manual_html/_images/link_creation_1.png new file mode 100644 index 0000000..d02c219 Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_1.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_2.png b/origame/docs/user_manual_html/_images/link_creation_2.png new file mode 100644 index 0000000..66aaabc Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_2.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_3.png b/origame/docs/user_manual_html/_images/link_creation_3.png new file mode 100644 index 0000000..8dd6ed4 Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_3.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_4.png b/origame/docs/user_manual_html/_images/link_creation_4.png new file mode 100644 index 0000000..f3f8ebb Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_4.png differ diff --git a/origame/docs/user_manual_html/_images/link_creation_5.png b/origame/docs/user_manual_html/_images/link_creation_5.png new file mode 100644 index 0000000..27e05c0 Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_creation_5.png differ diff --git a/origame/docs/user_manual_html/_images/link_renaming.png b/origame/docs/user_manual_html/_images/link_renaming.png new file mode 100644 index 0000000..ee94393 Binary files /dev/null and b/origame/docs/user_manual_html/_images/link_renaming.png differ diff --git a/origame/docs/user_manual_html/_images/links_symbols_imports.png b/origame/docs/user_manual_html/_images/links_symbols_imports.png new file mode 100644 index 0000000..8f67637 Binary files /dev/null and b/origame/docs/user_manual_html/_images/links_symbols_imports.png differ diff --git a/origame/docs/user_manual_html/_images/main_sim_settings.png b/origame/docs/user_manual_html/_images/main_sim_settings.png new file mode 100644 index 0000000..a748393 Binary files /dev/null and b/origame/docs/user_manual_html/_images/main_sim_settings.png differ diff --git a/origame/docs/user_manual_html/_images/main_window_default_view.png b/origame/docs/user_manual_html/_images/main_window_default_view.png new file mode 100644 index 0000000..be24344 Binary files /dev/null and b/origame/docs/user_manual_html/_images/main_window_default_view.png differ diff --git a/origame/docs/user_manual_html/_images/navigation_actor_2d_view_title_bar.png b/origame/docs/user_manual_html/_images/navigation_actor_2d_view_title_bar.png new file mode 100644 index 0000000..58766e7 Binary files /dev/null and b/origame/docs/user_manual_html/_images/navigation_actor_2d_view_title_bar.png differ diff --git a/origame/docs/user_manual_html/_images/non_creatable_parts.png b/origame/docs/user_manual_html/_images/non_creatable_parts.png new file mode 100644 index 0000000..1878d4e Binary files /dev/null and b/origame/docs/user_manual_html/_images/non_creatable_parts.png differ diff --git a/origame/docs/user_manual_html/_images/object_properties.png b/origame/docs/user_manual_html/_images/object_properties.png new file mode 100644 index 0000000..45ff2bb Binary files /dev/null and b/origame/docs/user_manual_html/_images/object_properties.png differ diff --git a/origame/docs/user_manual_html/_images/origame.png b/origame/docs/user_manual_html/_images/origame.png new file mode 100644 index 0000000..9812750 Binary files /dev/null and b/origame/docs/user_manual_html/_images/origame.png differ diff --git a/origame/docs/user_manual_html/_images/origame_icon.png b/origame/docs/user_manual_html/_images/origame_icon.png new file mode 100644 index 0000000..170ea20 Binary files /dev/null and b/origame/docs/user_manual_html/_images/origame_icon.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_actor.png b/origame/docs/user_manual_html/_images/part_and_editor_actor.png new file mode 100644 index 0000000..1ccae66 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_actor.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_button.png b/origame/docs/user_manual_html/_images/part_and_editor_button.png new file mode 100644 index 0000000..b97d021 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_button.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_clock.png b/origame/docs/user_manual_html/_images/part_and_editor_clock.png new file mode 100644 index 0000000..dba10dc Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_clock.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_data.png b/origame/docs/user_manual_html/_images/part_and_editor_data.png new file mode 100644 index 0000000..b022f39 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_data.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_datetime.png b/origame/docs/user_manual_html/_images/part_and_editor_datetime.png new file mode 100644 index 0000000..7ff37dc Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_datetime.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_file.png b/origame/docs/user_manual_html/_images/part_and_editor_file.png new file mode 100644 index 0000000..b33e583 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_file.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_function.png b/origame/docs/user_manual_html/_images/part_and_editor_function.png new file mode 100644 index 0000000..f1ee42d Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_function.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_info.png b/origame/docs/user_manual_html/_images/part_and_editor_info.png new file mode 100644 index 0000000..4a7ec92 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_info.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_library.png b/origame/docs/user_manual_html/_images/part_and_editor_library.png new file mode 100644 index 0000000..9ed6070 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_library.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_plot.png b/origame/docs/user_manual_html/_images/part_and_editor_plot.png new file mode 100644 index 0000000..bf00d7a Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_plot.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_pulse.png b/origame/docs/user_manual_html/_images/part_and_editor_pulse.png new file mode 100644 index 0000000..b057aa1 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_pulse.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_sheet.png b/origame/docs/user_manual_html/_images/part_and_editor_sheet.png new file mode 100644 index 0000000..b8a55b1 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_sheet.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_sql.png b/origame/docs/user_manual_html/_images/part_and_editor_sql.png new file mode 100644 index 0000000..8e29adf Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_sql.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_table.png b/origame/docs/user_manual_html/_images/part_and_editor_table.png new file mode 100644 index 0000000..3240fe1 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_table.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_time.png b/origame/docs/user_manual_html/_images/part_and_editor_time.png new file mode 100644 index 0000000..0aa58bb Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_time.png differ diff --git a/origame/docs/user_manual_html/_images/part_and_editor_variable.png b/origame/docs/user_manual_html/_images/part_and_editor_variable.png new file mode 100644 index 0000000..eed9323 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_and_editor_variable.png differ diff --git a/origame/docs/user_manual_html/_images/part_editor_common.png b/origame/docs/user_manual_html/_images/part_editor_common.png new file mode 100644 index 0000000..5507c9e Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_editor_common.png differ diff --git a/origame/docs/user_manual_html/_images/part_hub.png b/origame/docs/user_manual_html/_images/part_hub.png new file mode 100644 index 0000000..d079cb2 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_hub.png differ diff --git a/origame/docs/user_manual_html/_images/part_multiplier.png b/origame/docs/user_manual_html/_images/part_multiplier.png new file mode 100644 index 0000000..eb255c0 Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_multiplier.png differ diff --git a/origame/docs/user_manual_html/_images/part_node.png b/origame/docs/user_manual_html/_images/part_node.png new file mode 100644 index 0000000..90afd1f Binary files /dev/null and b/origame/docs/user_manual_html/_images/part_node.png differ diff --git a/origame/docs/user_manual_html/_images/resizing.png b/origame/docs/user_manual_html/_images/resizing.png new file mode 100644 index 0000000..c9d8b6c Binary files /dev/null and b/origame/docs/user_manual_html/_images/resizing.png differ diff --git a/origame/docs/user_manual_html/_images/run_setup_parts.png b/origame/docs/user_manual_html/_images/run_setup_parts.png new file mode 100644 index 0000000..dd0ec3a Binary files /dev/null and b/origame/docs/user_manual_html/_images/run_setup_parts.png differ diff --git a/origame/docs/user_manual_html/_images/scenario_browser.png b/origame/docs/user_manual_html/_images/scenario_browser.png new file mode 100644 index 0000000..6bb7bdd Binary files /dev/null and b/origame/docs/user_manual_html/_images/scenario_browser.png differ diff --git a/origame/docs/user_manual_html/_images/simulation_control.png b/origame/docs/user_manual_html/_images/simulation_control.png new file mode 100644 index 0000000..6a67991 Binary files /dev/null and b/origame/docs/user_manual_html/_images/simulation_control.png differ diff --git a/origame/docs/user_manual_html/_images/simulation_control_batch.png b/origame/docs/user_manual_html/_images/simulation_control_batch.png new file mode 100644 index 0000000..a3d2f3f Binary files /dev/null and b/origame/docs/user_manual_html/_images/simulation_control_batch.png differ diff --git a/origame/docs/user_manual_html/_images/simulation_control_main.png b/origame/docs/user_manual_html/_images/simulation_control_main.png new file mode 100644 index 0000000..d847661 Binary files /dev/null and b/origame/docs/user_manual_html/_images/simulation_control_main.png differ diff --git a/origame/docs/user_manual_html/_images/simulation_status.png b/origame/docs/user_manual_html/_images/simulation_status.png new file mode 100644 index 0000000..8278c05 Binary files /dev/null and b/origame/docs/user_manual_html/_images/simulation_status.png differ diff --git a/origame/docs/user_manual_html/_images/toolbar.png b/origame/docs/user_manual_html/_images/toolbar.png new file mode 100644 index 0000000..4cb52e8 Binary files /dev/null and b/origame/docs/user_manual_html/_images/toolbar.png differ diff --git a/origame/docs/user_manual_html/_static/ajax-loader.gif b/origame/docs/user_manual_html/_static/ajax-loader.gif new file mode 100644 index 0000000..61faf8c Binary files /dev/null and b/origame/docs/user_manual_html/_static/ajax-loader.gif differ diff --git a/origame/docs/user_manual_html/_static/alabaster.css b/origame/docs/user_manual_html/_static/alabaster.css new file mode 100644 index 0000000..a88ce29 --- /dev/null +++ b/origame/docs/user_manual_html/_static/alabaster.css @@ -0,0 +1,693 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif; + font-size: 17px; + background-color: #fff; + color: #000; + margin: 0; + padding: 0; +} + + +div.document { + width: 940px; + margin: 30px auto 0 auto; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 220px; +} + +div.sphinxsidebar { + width: 220px; + font-size: 14px; + line-height: 1.5; +} + +hr { + border: 1px solid #B1B4B6; +} + +div.body { + background-color: #fff; + color: #3E4349; + padding: 0 30px 0 30px; +} + +div.body > .section { + text-align: left; +} + +div.footer { + width: 940px; + margin: 20px auto 30px auto; + font-size: 14px; + color: #888; + text-align: right; +} + +div.footer a { + color: #888; +} + +p.caption { + font-family: inherit; + font-size: inherit; +} + + +div.relations { + display: none; +} + + +div.sphinxsidebar a { + color: #444; + text-decoration: none; + border-bottom: 1px dotted #999; +} + +div.sphinxsidebar a:hover { + border-bottom: 1px solid #999; +} + +div.sphinxsidebarwrapper { + padding: 18px 10px; +} + +div.sphinxsidebarwrapper p.logo { + padding: 0; + margin: -10px 0 0 0px; + text-align: center; +} + +div.sphinxsidebarwrapper h1.logo { + margin-top: -10px; + text-align: center; + margin-bottom: 5px; + text-align: left; +} + +div.sphinxsidebarwrapper h1.logo-name { + margin-top: 0px; +} + +div.sphinxsidebarwrapper p.blurb { + margin-top: 0; + font-style: normal; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-family: 'Garamond', 'Georgia', serif; + color: #444; + font-size: 24px; + font-weight: normal; + margin: 0 0 5px 0; + padding: 0; +} + +div.sphinxsidebar h4 { + font-size: 20px; +} + +div.sphinxsidebar h3 a { + color: #444; +} + +div.sphinxsidebar p.logo a, +div.sphinxsidebar h3 a, +div.sphinxsidebar p.logo a:hover, +div.sphinxsidebar h3 a:hover { + border: none; +} + +div.sphinxsidebar p { + color: #555; + margin: 10px 0; +} + +div.sphinxsidebar ul { + margin: 10px 0; + padding: 0; + color: #000; +} + +div.sphinxsidebar ul li.toctree-l1 > a { + font-size: 120%; +} + +div.sphinxsidebar ul li.toctree-l2 > a { + font-size: 110%; +} + +div.sphinxsidebar input { + border: 1px solid #CCC; + font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif; + font-size: 1em; +} + +div.sphinxsidebar hr { + border: none; + height: 1px; + color: #AAA; + background: #AAA; + + text-align: left; + margin-left: 0; + width: 50%; +} + +/* -- body styles ----------------------------------------------------------- */ + +a { + color: #004B6B; + text-decoration: underline; +} + +a:hover { + color: #6D4100; + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Garamond', 'Georgia', serif; + font-weight: normal; + margin: 30px 0px 10px 0px; + padding: 0; +} + +div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } +div.body h2 { font-size: 180%; } +div.body h3 { font-size: 150%; } +div.body h4 { font-size: 130%; } +div.body h5 { font-size: 100%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #DDD; + padding: 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + color: #444; + background: #EAEAEA; +} + +div.body p, div.body dd, div.body li { + line-height: 1.4em; +} + +div.admonition { + margin: 20px 0px; + padding: 10px 30px; + background-color: #EEE; + border: 1px solid #CCC; +} + +div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { + background-color: ; + border-bottom: 1px solid #fafafa; +} + +dd div.admonition { + margin-left: -60px; + padding-left: 60px; +} + +div.admonition p.admonition-title { + font-family: 'Garamond', 'Georgia', serif; + font-weight: normal; + font-size: 24px; + margin: 0 0 10px 0; + padding: 0; + line-height: 1; +} + +div.admonition p.last { + margin-bottom: 0; +} + +div.highlight { + background-color: #fff; +} + +dt:target, .highlight { + background: #FAF3E8; +} + +div.warning { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.danger { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.error { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.caution { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.attention { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.important { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.note { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.tip { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.hint { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.seealso { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.topic { + background-color: #EEE; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre, tt, code { + font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; + font-size: 0.9em; +} + +.hll { + background-color: #FFC; + margin: 0 -12px; + padding: 0 12px; + display: block; +} + +img.screenshot { +} + +tt.descname, tt.descclassname, code.descname, code.descclassname { + font-size: 0.95em; +} + +tt.descname, code.descname { + padding-right: 0.08em; +} + +img.screenshot { + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils { + border: 1px solid #888; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils td, table.docutils th { + border: 1px solid #888; + padding: 0.25em 0.7em; +} + +table.field-list, table.footnote { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +table.footnote { + margin: 15px 0; + width: 100%; + border: 1px solid #EEE; + background: #FDFDFD; + font-size: 0.9em; +} + +table.footnote + table.footnote { + margin-top: -15px; + border-top: none; +} + +table.field-list th { + padding: 0 0.8em 0 0; +} + +table.field-list td { + padding: 0; +} + +table.field-list p { + margin-bottom: 0.8em; +} + +table.footnote td.label { + width: .1px; + padding: 0.3em 0 0.3em 0.5em; +} + +table.footnote td { + padding: 0.3em 0.5em; +} + +dl { + margin: 0; + padding: 0; +} + +dl dd { + margin-left: 30px; +} + +blockquote { + margin: 0 0 0 30px; + padding: 0; +} + +ul, ol { + /* Matches the 30px from the narrow-screen "li > ul" selector below */ + margin: 10px 0 10px 30px; + padding: 0; +} + +pre { + background: #EEE; + padding: 7px 30px; + margin: 15px 0px; + line-height: 1.3em; +} + +div.viewcode-block:target { + background: #ffd; +} + +dl pre, blockquote pre, li pre { + margin-left: 0; + padding-left: 30px; +} + +dl dl pre { + margin-left: -90px; + padding-left: 90px; +} + +tt, code { + background-color: #ecf0f3; + color: #222; + /* padding: 1px 2px; */ +} + +tt.xref, code.xref, a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fff; +} + +a.reference { + text-decoration: none; + border-bottom: 1px dotted #004B6B; +} + +/* Don't put an underline on images */ +a.image-reference, a.image-reference:hover { + border-bottom: none; +} + +a.reference:hover { + border-bottom: 1px solid #6D4100; +} + +a.footnote-reference { + text-decoration: none; + font-size: 0.7em; + vertical-align: top; + border-bottom: 1px dotted #004B6B; +} + +a.footnote-reference:hover { + border-bottom: 1px solid #6D4100; +} + +a:hover tt, a:hover code { + background: #EEE; +} + + +@media screen and (max-width: 870px) { + + div.sphinxsidebar { + display: none; + } + + div.document { + width: 100%; + + } + + div.documentwrapper { + margin-left: 0; + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + } + + div.bodywrapper { + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + margin-left: 0; + } + + ul { + margin-left: 0; + } + + li > ul { + /* Matches the 30px from the "ul, ol" selector above */ + margin-left: 30px; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .bodywrapper { + margin: 0; + } + + .footer { + width: auto; + } + + .github { + display: none; + } + + + +} + + + +@media screen and (max-width: 875px) { + + body { + margin: 0; + padding: 20px 30px; + } + + div.documentwrapper { + float: none; + background: #fff; + } + + div.sphinxsidebar { + display: block; + float: none; + width: 102.5%; + margin: 50px -30px -20px -30px; + padding: 10px 20px; + background: #333; + color: #FFF; + } + + div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, + div.sphinxsidebar h3 a { + color: #fff; + } + + div.sphinxsidebar a { + color: #AAA; + } + + div.sphinxsidebar p.logo { + display: none; + } + + div.document { + width: 100%; + margin: 0; + } + + div.footer { + display: none; + } + + div.bodywrapper { + margin: 0; + } + + div.body { + min-height: 0; + padding: 0; + } + + .rtd_doc_footer { + display: none; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .footer { + width: auto; + } + + .github { + display: none; + } +} + + +/* misc. */ + +.revsys-inline { + display: none!important; +} + +/* Make nested-list/multi-paragraph items look better in Releases changelog + * pages. Without this, docutils' magical list fuckery causes inconsistent + * formatting between different release sub-lists. + */ +div#changelog > div.section > ul > li > p:only-child { + margin-bottom: 0; +} + +/* Hide fugly table cell borders in ..bibliography:: directive output */ +table.docutils.citation, table.docutils.citation td, table.docutils.citation th { + border: none; + /* Below needed in some edge cases; if not applied, bottom shadows appear */ + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} \ No newline at end of file diff --git a/origame/docs/user_manual_html/_static/basic.css b/origame/docs/user_manual_html/_static/basic.css new file mode 100644 index 0000000..2b513f0 --- /dev/null +++ b/origame/docs/user_manual_html/_static/basic.css @@ -0,0 +1,604 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox input[type="text"] { + width: 170px; +} + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable dl, table.indextable dd { + margin-top: 0; + margin-bottom: 0; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.field-list ul { + padding-left: 1em; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.field-list td, table.field-list th { + border: 0 !important; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, .highlighted { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/origame/docs/user_manual_html/_static/comment-bright.png b/origame/docs/user_manual_html/_static/comment-bright.png new file mode 100644 index 0000000..551517b Binary files /dev/null and b/origame/docs/user_manual_html/_static/comment-bright.png differ diff --git a/origame/docs/user_manual_html/_static/comment-close.png b/origame/docs/user_manual_html/_static/comment-close.png new file mode 100644 index 0000000..09b54be Binary files /dev/null and b/origame/docs/user_manual_html/_static/comment-close.png differ diff --git a/origame/docs/user_manual_html/_static/comment.png b/origame/docs/user_manual_html/_static/comment.png new file mode 100644 index 0000000..92feb52 Binary files /dev/null and b/origame/docs/user_manual_html/_static/comment.png differ diff --git a/origame/docs/user_manual_html/_static/custom.css b/origame/docs/user_manual_html/_static/custom.css new file mode 100644 index 0000000..2a924f1 --- /dev/null +++ b/origame/docs/user_manual_html/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/origame/docs/user_manual_html/_static/doctools.js b/origame/docs/user_manual_html/_static/doctools.js new file mode 100644 index 0000000..8163495 --- /dev/null +++ b/origame/docs/user_manual_html/_static/doctools.js @@ -0,0 +1,287 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s == 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node) { + if (node.nodeType == 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { + var span = document.createElement("span"); + span.className = className; + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this); + }); + } + } + return this.each(function() { + highlight(this); + }); +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated == 'undefined') + return string; + return (typeof translated == 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated == 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) == 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this == '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); \ No newline at end of file diff --git a/origame/docs/user_manual_html/_static/down-pressed.png b/origame/docs/user_manual_html/_static/down-pressed.png new file mode 100644 index 0000000..7c30d00 Binary files /dev/null and b/origame/docs/user_manual_html/_static/down-pressed.png differ diff --git a/origame/docs/user_manual_html/_static/down.png b/origame/docs/user_manual_html/_static/down.png new file mode 100644 index 0000000..f48098a Binary files /dev/null and b/origame/docs/user_manual_html/_static/down.png differ diff --git a/origame/docs/user_manual_html/_static/file.png b/origame/docs/user_manual_html/_static/file.png new file mode 100644 index 0000000..254c60b Binary files /dev/null and b/origame/docs/user_manual_html/_static/file.png differ diff --git a/origame/docs/user_manual_html/_static/jquery-1.11.1.js b/origame/docs/user_manual_html/_static/jquery-1.11.1.js new file mode 100644 index 0000000..d4b67f7 --- /dev/null +++ b/origame/docs/user_manual_html/_static/jquery-1.11.1.js @@ -0,0 +1,10308 @@ +/*! + * jQuery JavaScript Library v1.11.1 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-05-01T17:42Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper window is present, + // execute the factory and get jQuery + // For environments that do not inherently posses a window with a document + // (such as Node.js), expose a jQuery-making factory as module.exports + // This accentuates the need for the creation of a real window + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +// + +var deletedIds = []; + +var slice = deletedIds.slice; + +var concat = deletedIds.concat; + +var push = deletedIds.push; + +var indexOf = deletedIds.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "1.11.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1, IE<9 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( support.ownLast ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1, IE<9 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + while ( j < len ) { + first[ i++ ] = second[ j++ ]; + } + + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: function() { + return +( new Date() ); + }, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v1.10.19 + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-04-18 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== strundefined && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, + doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", function() { + setDocument(); + }, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", function() { + setDocument(); + }); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { + div.innerHTML = "
"; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowclip^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !(--remaining) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * Clean-up method for dom ready events + */ +function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } +} + +/** + * The ready event handler and self cleanup method + */ +function completed() { + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + + +var strundefined = typeof undefined; + + + +// Support: IE<9 +// Iteration over object's inherited properties before its own +var i; +for ( i in jQuery( support ) ) { + break; +} +support.ownLast = i !== "0"; + +// Note: most support tests are defined in their respective modules. +// false until the test is run +support.inlineBlockNeedsLayout = false; + +// Execute ASAP in case we need to set body.style.zoom +jQuery(function() { + // Minified: var a,b,c,d + var val, div, body, container; + + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { + // Return for frameset docs that don't have a body + return; + } + + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); + + if ( typeof div.style.zoom !== strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; + + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); +}); + + + + +(function() { + var div = document.createElement( "div" ); + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( elem ) { + var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], + nodeType = +elem.nodeType || 1; + + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : + + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute("classid") === noData; +}; + + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + +function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[0], + attrs = elem && elem.attributes; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; +}; +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + // Minified: var a,b,c + var input = document.createElement( "input" ), + div = document.createElement( "div" ), + fragment = document.createDocumentFragment(); + + // Setup + div.innerHTML = "
a"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; + + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); + div.innerHTML = ""; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + support.noCloneEvent = true; + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } +})(); + + +(function() { + var i, eventName, + div = document.createElement( "div" ); + + // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) + for ( i in { submit: true, change: true, focusin: true }) { + eventName = "on" + i; + + if ( !(support[ i + "Bubbles" ] = eventName in window) ) { + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!support.noCloneEvent || !support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + deletedIds.push( id ); + } + } + } + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optmization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "