diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 84b744b..0000000 --- a/.appveyor.yml +++ /dev/null @@ -1,43 +0,0 @@ -environment: - - PYTHON_ARCH: "64" - PYTHON: "C:\\Miniconda38-x64" - - matrix: - - PYTHON_VERSION: "3.8" - -install: - # windows config (for installation) - - cmd: "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - - cmd: setlocal - - cmd: set ANACONDA_API_TOKEN= - # conda config - - conda config --set always_yes yes --set changeps1 no - - conda update -q conda - - conda install conda-build anaconda-client - - pip install -i https://pypi.anaconda.org/psyplot/simple --no-deps psyplot-ci-orb - - conda config --add channels conda-forge - - conda config --add channels psyplot - - conda info -a - - conda list - # windows config - - cmd: endlocal - - cmd: 'SET PYTHONWARNINGS=ignore:mode:DeprecationWarning:docutils.io:245' - - cmd: "IF NOT DEFINED APPVEYOR_REPO_TAG_NAME (SET GIT_BRANCH=%APPVEYOR_REPO_BRANCH%)" - - cmd: "IF NOT DEFINED APPVEYOR_REPO_TAG_NAME (conda config --add channels psyplot/label/%APPVEYOR_REPO_BRANCH%)" - -build: off - -test_script: - - cmd: setlocal - - cmd: set ANACONDA_API_TOKEN= - - cmd: conda build ci/conda-recipe --python %PYTHON_VERSION% - - cmd: endlocal - -deploy_script: - - cmd: " - IF NOT DEFINED APPVEYOR_REPO_TAG_NAME ( - deploy-conda-recipe -l %APPVEYOR_REPO_BRANCH% -py %PYTHON_VERSION% ci/conda-recipe - ) ELSE ( - deploy-conda-recipe -py %PYTHON_VERSION% ci/conda-recipe - )" diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 1809591..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,113 +0,0 @@ -version: 2.1 - -orbs: - psyplot: psyplot/psyplot-ci-orb@1.5.22 - mattermost-plugin-notify: nathanaelhoun/mattermost-plugin-notify@1.2.0 - -executors: - default: psyplot/default - macos: psyplot/macos - -parameters: - unit-test-executor: - description: Executor for the unit tests. Can be default or macos - type: string - default: default - deploy-release: - description: Deploy the comment as a new release to github and pypi - type: boolean - default: false - run-tests: - description: Run the test suite - type: boolean - default: true - build_docs: - description: Build the documentation - type: boolean - default: true - -workflows: - build-and-test: - unless: << pipeline.parameters.deploy-release >> - jobs: - - psyplot/install-and-build: - name: install - exec_environment: << pipeline.parameters.unit-test-executor >> - setup_env: true - build_args: "--no-test" - build_docs: << pipeline.parameters.build_docs >> - - psyplot/test-parallel: - name: run-tests - parallelism: 2 - pytest_args: --cov=psyplot_gui - run-job: << pipeline.parameters.run-tests >> - requires: - - install - - psyplot/build-docs: - name: test-docs - run-job: << pipeline.parameters.build_docs >> - builders: linkcheck - requires: - - install - - mattermost-plugin-notify/approval-notification: - name: notify-deploy - context: mattermost - message: >- - Hello @all! A workflow on https://app.circleci.com/pipelines/github/psyplot/psyplot-gui is awaiting your approval. - Please check the uploaded docs and builds prior to approval. - requires: - - run-tests - - test-docs - - hold-for-deploy: - type: approval - requires: - - notify-deploy - - psyplot/deploy-pkg: - exec_environment: << pipeline.parameters.unit-test-executor >> - context: anaconda - requires: - - hold-for-deploy - - psyplot/deploy-docs: - fingerprint: "19:54:3e:9e:7b:73:1c:45:ee:4c:7b:73:8a:46:96:3a" - run-job: << pipeline.parameters.build_docs >> - requires: - - hold-for-deploy - filters: - branches: - only: master - - psyplot/trigger-release-workflow: - context: trigger-release - filters: - branches: - only: master - requires: - - psyplot/deploy-pkg - - psyplot/deploy-docs - publish-release: - when: << pipeline.parameters.deploy-release >> - jobs: - - psyplot/create-tag: - ssh-fingerprints: "19:54:3e:9e:7b:73:1c:45:ee:4c:7b:73:8a:46:96:3a" - context: psyplot-admin - user-name: psyplot-admin - publish-release: true - publish-version-tag: true - - mattermost-plugin-notify/approval-notification: - name: notify-release - context: mattermost - message: >- - Hello @all! A new release has been created at https://github.com/psyplot/psyplot-gui/releases. - Please review it carefully, publish it and approve the upload to pypi. - requires: - - psyplot/create-tag - - hold-for-pypi: - type: approval - requires: - - notify-release - - psyplot/deploy-pypi: - context: pypi - requires: - - hold-for-pypi - filters: - branches: - only: master diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index f611cdb..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -psyplot_gui/_version.py export-subst diff --git a/.github/ISSUE_TEMPLATE/change_feature.md b/.github/ISSUE_TEMPLATE/change_feature.md deleted file mode 100644 index 436208c..0000000 --- a/.github/ISSUE_TEMPLATE/change_feature.md +++ /dev/null @@ -1,17 +0,0 @@ -#### Summary -[Describe the requested change in one or two lines. -This should also be mentioned in the title of this issue.] - -#### Reason -[Why do you think, this is useful?] - -#### Current behaviour -[How is the current behaviour/framework?] - -#### New behaviour -[Provide here some more explanation that goes beyond the summary above -(or delete this paragraph, if everything is explained above), -and describe the changes you would like to see] - -#### Examples -[images, code-snippets or URLs to other repositories] diff --git a/.github/ISSUE_TEMPLATE/new_feature.md b/.github/ISSUE_TEMPLATE/new_feature.md deleted file mode 100644 index cdb2e79..0000000 --- a/.github/ISSUE_TEMPLATE/new_feature.md +++ /dev/null @@ -1,13 +0,0 @@ -#### Summary -[Describe the new requested feature in one or two lines. -This should also be mentioned in the title of this issue.] - -#### Reason -[Why do you think, this is useful?] - -#### Detailed explanation -[Provide here some more explanation that goes beyond the summary above -(or delete this paragraph, if everything is explained above)] - -#### Examples -[images, code-snippets or URLs to other repositories] diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index 142a180..0000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,30 +0,0 @@ -#### Code Sample, a copy-pastable example if possible - -```python -# Your code here - -``` -#### Problem description - -[this should explain **why** the current behavior is a problem and why the expected output is a better solution.] - -#### Expected Output -What should have been expected? You can hide large error messages within ``
`` tags, e.g. - -
-very long error message -
- -#### Output of ``psyplot -aV`` - -
-# Paste the output of the command ``psyplot -aV`` (ran from the command line) - -
- -#### NOTE -This is a bug report. - -For requesting new features, use [this template](https://github.com/psyplot/psyplot-gui/issues/new?template=new_feature.md&title=NEW+FEATURE:). - -For changing existing features, use [this template](https://github.com/psyplot/psyplot-gui/issues/new?template=change_feature.md&title=CHANGE+FEATURE:). diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 4eb59a1..0000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,4 +0,0 @@ - - [ ] Closes #xxxx (remove if there is no corresponding issue, which should only be the case for minor changes) - - [ ] Tests added (for all bug fixes or enhancements) - - [ ] Tests passed (for all non-documentation changes) - - [ ] Fully documented, including `CHANGELOG.rst` for all changes diff --git a/.gitignore b/.gitignore index 875a53c..e1e5892 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,8 @@ __pycache__/ # C extensions *.so -# mypy cache -.mypy_cache +# MyPy cache +.mypy_cache/ # Distribution / packaging .Python @@ -55,9 +55,17 @@ coverage.xml *.log # Sphinx documentation -docs/api/ docs/_build/ +docs/examples/ docs/index.doctree +docs/ + +# test results +*psyplot_testresults +tests/envs/cov_psyplot_py* +tests/envs/psyplot_py*.html +tests/reference_figures +tests/test_figures # PyBuilder target/ @@ -68,12 +76,5 @@ target/ # Example ipython notebook checkpoints *.ipynb_checkpoints/ -# rc files -*matplotlibrc -*psyplotguirc.yml -*psyplotrc.yml -*debug_psyplot.log* - # conda build files -ci/conda_recipe/psyplot-gui/meta.yaml ci/conda-recipe/recipe_append.yaml diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..3e09a4a --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,5 @@ +version: 2 + +python: + version: "3.8" + system_packages: true diff --git a/CHANGELOG.rst b/CHANGELOG.rst deleted file mode 100644 index 5e164a9..0000000 --- a/CHANGELOG.rst +++ /dev/null @@ -1,106 +0,0 @@ -v1.4.0 -====== -Compatibility fixes and LGPL license - -As with psyplot 1.4.0, psyplot-gui is now continuously tested and deployed with -CircleCI. - - -Changed -------- -- Documentation is now hosted with Github Pages at https://psyplot.github.io/psyplot-gui. - Redirects from the old documentation at https://psyplot-gui.readthedocs.io have been - configured. -- We use CicleCI now for a standardized CI/CD pipeline to build and test - the code and docs all at one place, see `#28 `__ - - - -v1.3.0 -====== -Presets and more variable info - -Changed -------- -- psyplot-gui has been moved from https://github.com/Chilipp/psyplot-gui to https://github.com/psyplot/psyplot-gui, - see `#10 `__ -- variables in the dataset tree show now more content, - see `#16 `__ -- setting the rcparam ``help_explorer.use_intersphinx`` to None, will not use - intersphinx on windows, see `#20 `__ - -Added ------ -- The psyplot gui can now load and save preset files, - see `psyplot#24 `__ and - `#17 https://github.com/psyplot/psyplot-gui/pull/17`__ -- Add option to start the GUI without importing QtWebEngineWidgets - `#11 `__ -- Dockmixins (i.e. plugins) can now reimplement the `position_dock` method that - controls where the dock is exactly placed in the GUI - (see `#12 `__) - -v1.2.4 -====== -New release with better OpenGL support (see ``psyplot --help``) - -v1.2.3 -====== -Minor release without major API changes. - -v1.2.2 -====== -From now one, python 2.7 is not supported anymore. - -Added ------ -- Added the possibility to change the central widget of the GUI -- Added `remove_plugin` method for psyplot GUI plugins - -Changed -------- -- removed MacOS app folder in python dist - -v1.2.1 -====== -monkey patch for ipykernel < 5.1.1 to fix -https://github.com/ipython/ipykernel/issues/370 - -v1.2.0 -====== -Changed -------- -- The HTML help explorer now also shows a table of contents in the intro - and in the side bar to navigate to previously visited objects - -v1.1.0 -====== -This release mainly adds the possibility to create plugins into the -psyplot-gui and it adds a new framework to allow the formatoptions to provide -a custom interface to the formatoptions widget. - -Added ------ -- Added layout windows menu and default layout -- Added ``script`` and ``command`` command line arguments -- The ``pwd`` command line arguments now changes the working directory of the - running GUI -- Added callbacks to the ``MainWindow`` class. This framework can be used on a - low level to interact with the current GUI. -- The DataFrameEditor. A widget to display dataframes -- The implementation of the ``psyplot.plotter.Formatoption.get_fmt_widget`` - method. Formatoptions now can add a custom widget to the formatoptions widget - - -v1.0.1 -====== -.. image:: https://zenodo.org/badge/55793611.svg - :target: https://zenodo.org/badge/latestdoi/55793611 - -Added ------ -- added changelog - -Changed -------- -- fixed bug that prevented startup on Windows diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 5c34d70..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,5 +0,0 @@ -# Contributing to psyplot-gui - -:+1::tada: First off, thanks for taking the time to contribute! :tada::+1: - -For some guidelines, please see the [contribution guidelines for psyplot](https://github.com/psyplot/psyplot/blob/master/CONTRIBUTING.md). diff --git a/LICENSE b/LICENSE index c8db4cc..1d7ff42 100644 --- a/LICENSE +++ b/LICENSE @@ -1,296 +1,21 @@ -psyplot-gui: Graphical user interface for the psyplot package -Copyright (C) 2017 Philipp S. Sommer - -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 2 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. - -A copy of the GNU General Public License is provided down below. - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE 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. - - END OF TERMS AND CONDITIONS +MIT License + +Copyright (c) 2021 Philipp S. Sommer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 3fb481e..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,9 +0,0 @@ -include README.rst -include LICENSE -include psyplot_gui/sphinx_supp/_static/* -include psyplot_gui/sphinx_supp/conf.py -include psyplot_gui/sphinx_supp/psyplot.rst -include psyplot_gui/icons/*.png -include psyplot_gui/icons/*.svg -include versioneer.py -include psyplot_gui/_version.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..dbaae1f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# psyplot-gui branch for redirecting docs + +Dummy repository for redirecting to from RTD to github diff --git a/README.rst b/README.rst deleted file mode 100644 index bc17829..0000000 --- a/README.rst +++ /dev/null @@ -1,99 +0,0 @@ -Graphical User Interface for the psyplot package -================================================ - -.. start-badges - -.. list-table:: - :stub-columns: 1 - :widths: 10 90 - - * - docs - - |docs| - * - tests - - |circleci| |appveyor| |requires| |codecov| - * - package - - |version| |conda| |github| |zenodo| - * - implementations - - |supported-versions| |supported-implementations| - -.. |docs| image:: http://readthedocs.org/projects/psyplot-gui/badge/?version=latest - :alt: Documentation Status - :target: http://psyplot-gui.readthedocs.io/en/latest/?badge=latest - -.. |circleci| image:: https://circleci.com/gh/psyplot/psyplot-gui/tree/master.svg?style=svg - :alt: CircleCI - :target: https://circleci.com/gh/psyplot/psyplot-gui/tree/master - -.. |appveyor| image:: https://ci.appveyor.com/api/projects/status/bud4ov6lddrjvt88/branch/master?svg=true - :alt: AppVeyor - :target: https://ci.appveyor.com/project/psyplot/psyplot-gui-q726s - -.. |codecov| image:: https://codecov.io/gh/psyplot/psyplot-gui/branch/master/graph/badge.svg - :alt: Coverage - :target: https://codecov.io/gh/psyplot/psyplot-gui - -.. |requires| image:: https://requires.io/github/psyplot/psyplot-gui/requirements.svg?branch=master - :alt: Requirements Status - :target: https://requires.io/github/psyplot/psyplot-gui/requirements/?branch=master - -.. |version| image:: https://img.shields.io/pypi/v/psyplot-gui.svg?style=flat - :alt: PyPI Package latest release - :target: https://pypi.python.org/pypi/psyplot-gui - -.. |conda| image:: https://anaconda.org/conda-forge/psyplot-gui/badges/version.svg - :alt: conda - :target: https://anaconda.org/conda-forge/psyplot-gui - -.. |supported-versions| image:: https://img.shields.io/pypi/pyversions/psyplot-gui.svg?style=flat - :alt: Supported versions - :target: https://pypi.python.org/pypi/psyplot-gui - -.. |supported-implementations| image:: https://img.shields.io/pypi/implementation/psyplot-gui.svg?style=flat - :alt: Supported implementations - :target: https://pypi.python.org/pypi/psyplot-gui - -.. |zenodo| image:: https://zenodo.org/badge/55793611.svg - :alt: Zenodo - :target: https://zenodo.org/badge/latestdoi/55793611 - -.. |github| image:: https://img.shields.io/github/release/psyplot/psyplot-gui.svg - :target: https://github.com/psyplot/psyplot-gui/releases/latest - :alt: Latest github release - - -.. end-badges - -Welcome! This package enhances the interactive visualization framework -psyplot_ with a graphical user interface using PyQt_. See the homepage of the -main project on examples on the possibilities with psyplot_. - -You can see the full documentation under -`readthedocs.org `__ - -.. _PyQt: https://riverbankcomputing.com/software/pyqt/intro -.. _psyplot: http://psyplot.readthedocs.io/en/latest/ - - -Copyright ---------- -Copyright (C) 2021 Helmholtz-Zentrum Hereon - -Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht - -Copyright (C) 2016-2021 University of Lausanne - -psyplot-gui is released under the GNU LGPL-3.O license. -See COPYING and COPYING.LESSER in the root of the repository for full -licensing details. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License version 3.0 as -published by the Free Software Foundation. - -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 LGPL-3.0 license for more details. - -You should have received a copy of the GNU LGPL-3.0 license -along with this program. If not, see . diff --git a/ci/conda-recipe/bld.bat b/ci/conda-recipe/bld.bat deleted file mode 100644 index 52b19de..0000000 --- a/ci/conda-recipe/bld.bat +++ /dev/null @@ -1,11 +0,0 @@ -%PYTHON% -m pip install . --no-deps --ignore-installed -vvv -if errorlevel 1 exit 1 - -set MENU_DIR=%PREFIX%\Menu -IF NOT EXIST (%MENU_DIR%) mkdir %MENU_DIR% - -copy %RECIPE_DIR%\psyplot.ico %MENU_DIR%\psyplot.ico -if errorlevel 1 exit 1 - -copy %RECIPE_DIR%\menu-windows.json %MENU_DIR%\psyplot_shortcut.json -if errorlevel 1 exit 1 diff --git a/ci/conda-recipe/build.sh b/ci/conda-recipe/build.sh deleted file mode 100644 index 614ec75..0000000 --- a/ci/conda-recipe/build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -$PYTHON -m pip install . --no-deps --ignore-installed -vvv diff --git a/ci/conda-recipe/logo.png b/ci/conda-recipe/logo.png deleted file mode 100644 index b0d09f5..0000000 Binary files a/ci/conda-recipe/logo.png and /dev/null differ diff --git a/ci/conda-recipe/menu-windows.json b/ci/conda-recipe/menu-windows.json deleted file mode 100644 index b6414a0..0000000 --- a/ci/conda-recipe/menu-windows.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "menu_name": "Psyplot", - "menu_items": - [ - { - "name": "Psyplot", - "pywscript": "${PYTHON_SCRIPTS}/psyplot-script.py", - "workdir": "${PERSONALDIR}", - "icon": "${MENU_DIR}/psyplot.ico" - } - ] -} diff --git a/ci/conda-recipe/meta.yaml b/ci/conda-recipe/meta.yaml deleted file mode 100644 index 5c2d806..0000000 --- a/ci/conda-recipe/meta.yaml +++ /dev/null @@ -1,73 +0,0 @@ -{% set data = load_setup_py_data() %} -{% set name = "psyplot-gui" %} - -package: - name: {{ name|lower }} - version: {{ data.get('version') }} - -source: - git_url: ../.. - -build: - number: {{ environ.get('GIT_DESCRIBE_NUMBER', 0) }} - string: py{{ environ.get('CONDA_PY') }}{% if environ.get("BUILD_STR_END") %}_{{ environ.get("BUILD_STR_END") }}{% endif %} - skip: true # [py == 27] - -requirements: - host: - - python - - pip - run: - - python - - psyplot >=1.3.0 - - pyqt >=5 - - qtconsole - - fasteners - - sphinx - - sphinx_rtd_theme - -test: - imports: - - psyplot_gui - - psyplot_gui.main - - psyplot_gui.compat - - psyplot_gui.compat.qtcompat - - psyplot_gui.config - - psyplot_gui.sphinx_supp - - requires: - - pytest - - pytest-cov - - codecov - - dask - - netcdf4 - - seaborn - - psy-simple - - pip - source_files: - - tests - - commands: - - pip install tests/test_plugin/ - - psyplot --help - - pytest -sv --cov=psyplot_gui - - codecov - -app: - entry: psyplot - icon: logo.png - summary: Psyplot visualization software - type: desk - -about: - home: https://github.com/psyplot/psyplot-gui - license: GPL-2.0-only - license_family: GPL - license_file: LICENSE - summary: Graphical user interface for the psyplot package - - description: | - This package provides a graphical user interface to interact with the - psyplot framework. - doc_url: http://psyplot.github.io/psyplot-gui - dev_url: https://github.com/psyplot/psyplot-gui diff --git a/ci/conda-recipe/psyplot.ico b/ci/conda-recipe/psyplot.ico deleted file mode 100644 index 441a5d4..0000000 Binary files a/ci/conda-recipe/psyplot.ico and /dev/null differ diff --git a/ci/environment.yml b/ci/environment.yml deleted file mode 100644 index 0f8588f..0000000 --- a/ci/environment.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: psyplot_gui_docs -channels: - - local - - psyplot/label/master - - conda-forge -dependencies: - - python=3.8 - - scipy - - netcdf4=1.5.7 - - h5py=3.4.0 - - hdf5=1.12.1 - - pytest-qt - - psy-simple - - psyplot-gui - - pytest-cov - - psutil - - pip - - pip: - - ../tests/test_plugin/ \ No newline at end of file diff --git a/docs/_build/doctrees/api/psy_simple.colors.doctree b/docs/_build/doctrees/api/psy_simple.colors.doctree new file mode 100644 index 0000000..0655a0e Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.colors.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.doctree b/docs/_build/doctrees/api/psy_simple.doctree new file mode 100644 index 0000000..5909ea8 Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.plotters.doctree b/docs/_build/doctrees/api/psy_simple.plotters.doctree new file mode 100644 index 0000000..71da720 Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.plotters.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.plugin.doctree b/docs/_build/doctrees/api/psy_simple.plugin.doctree new file mode 100644 index 0000000..7639864 Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.plugin.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.widgets.colors.doctree b/docs/_build/doctrees/api/psy_simple.widgets.colors.doctree new file mode 100644 index 0000000..39bbdaf Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.widgets.colors.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.widgets.doctree b/docs/_build/doctrees/api/psy_simple.widgets.doctree new file mode 100644 index 0000000..760dac5 Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.widgets.doctree differ diff --git a/docs/_build/doctrees/api/psy_simple.widgets.texts.doctree b/docs/_build/doctrees/api/psy_simple.widgets.texts.doctree new file mode 100644 index 0000000..f18ecaf Binary files /dev/null and b/docs/_build/doctrees/api/psy_simple.widgets.texts.doctree differ diff --git a/docs/_build/doctrees/changelog.doctree b/docs/_build/doctrees/changelog.doctree new file mode 100644 index 0000000..8fe055a Binary files /dev/null and b/docs/_build/doctrees/changelog.doctree differ diff --git a/docs/_build/doctrees/contribute.doctree b/docs/_build/doctrees/contribute.doctree new file mode 100644 index 0000000..a100bb9 Binary files /dev/null and b/docs/_build/doctrees/contribute.doctree differ diff --git a/docs/_build/doctrees/environment.pickle b/docs/_build/doctrees/environment.pickle new file mode 100644 index 0000000..7d68e54 Binary files /dev/null and b/docs/_build/doctrees/environment.pickle differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.barplot.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.barplot.doctree new file mode 100644 index 0000000..2cd53f8 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.barplot.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.combined.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.combined.doctree new file mode 100644 index 0000000..3b21745 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.combined.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.density.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.density.doctree new file mode 100644 index 0000000..cd67953 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.density.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.fldmean.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.fldmean.doctree new file mode 100644 index 0000000..d0f6cd7 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.fldmean.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.lineplot.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.lineplot.doctree new file mode 100644 index 0000000..7363170 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.lineplot.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.plot2d.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.plot2d.doctree new file mode 100644 index 0000000..52a3862 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.plot2d.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.vector.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.vector.doctree new file mode 100644 index 0000000..5840f7d Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.vector.doctree differ diff --git a/docs/_build/doctrees/generated/psyplot.project.plot.violinplot.doctree b/docs/_build/doctrees/generated/psyplot.project.plot.violinplot.doctree new file mode 100644 index 0000000..6a64c11 Binary files /dev/null and b/docs/_build/doctrees/generated/psyplot.project.plot.violinplot.doctree differ diff --git a/docs/_build/doctrees/index.doctree b/docs/_build/doctrees/index.doctree new file mode 100644 index 0000000..35daa10 Binary files /dev/null and b/docs/_build/doctrees/index.doctree differ diff --git a/docs/_build/doctrees/installing.doctree b/docs/_build/doctrees/installing.doctree new file mode 100644 index 0000000..76c5008 Binary files /dev/null and b/docs/_build/doctrees/installing.doctree differ diff --git a/docs/_build/doctrees/plot_methods.doctree b/docs/_build/doctrees/plot_methods.doctree new file mode 100644 index 0000000..d268ebf Binary files /dev/null and b/docs/_build/doctrees/plot_methods.doctree differ diff --git a/docs/_build/html/.buildinfo b/docs/_build/html/.buildinfo new file mode 100644 index 0000000..4b6a178 --- /dev/null +++ b/docs/_build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 1d50483337eb779add1fca7e73a4c7f1 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/_build/html/_sources/api/psy_simple.colors.rst.txt b/docs/_build/html/_sources/api/psy_simple.colors.rst.txt new file mode 100644 index 0000000..2f81f55 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.colors.rst.txt @@ -0,0 +1,9 @@ +psy\_simple.colors module +========================= + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.colors.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/api/psy_simple.plotters.rst.txt b/docs/_build/html/_sources/api/psy_simple.plotters.rst.txt new file mode 100644 index 0000000..ca5e961 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.plotters.rst.txt @@ -0,0 +1,10 @@ +psy\_simple.plotters module +=========================== + + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.plotters.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/api/psy_simple.plugin.rst.txt b/docs/_build/html/_sources/api/psy_simple.plugin.rst.txt new file mode 100644 index 0000000..049df78 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.plugin.rst.txt @@ -0,0 +1,10 @@ +psy\_simple.plugin module +========================= + + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.plugin.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/api/psy_simple.rst.txt b/docs/_build/html/_sources/api/psy_simple.rst.txt new file mode 100644 index 0000000..6a24f89 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.rst.txt @@ -0,0 +1,32 @@ +API Reference +=================== + + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.html. + You should be redirected within 5 seconds. +

+ + +Subpackages +----------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psy_simple.widgets + +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psy_simple.base + psy_simple.colors + psy_simple.plotters + psy_simple.plugin diff --git a/docs/_build/html/_sources/api/psy_simple.widgets.colors.rst.txt b/docs/_build/html/_sources/api/psy_simple.widgets.colors.rst.txt new file mode 100644 index 0000000..fbba686 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.widgets.colors.rst.txt @@ -0,0 +1,10 @@ +psy\_simple.widgets.colors module +================================= + + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.colors.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/api/psy_simple.widgets.rst.txt b/docs/_build/html/_sources/api/psy_simple.widgets.rst.txt new file mode 100644 index 0000000..2b143ac --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.widgets.rst.txt @@ -0,0 +1,20 @@ +psy\_simple.widgets package +=========================== + + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.html. + You should be redirected within 5 seconds. +

+ +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psy_simple.widgets.colors + psy_simple.widgets.texts diff --git a/docs/_build/html/_sources/api/psy_simple.widgets.texts.rst.txt b/docs/_build/html/_sources/api/psy_simple.widgets.texts.rst.txt new file mode 100644 index 0000000..44c5806 --- /dev/null +++ b/docs/_build/html/_sources/api/psy_simple.widgets.texts.rst.txt @@ -0,0 +1,9 @@ +psy\_simple.widgets.texts module +================================ + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.texts.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/changelog.rst.txt b/docs/_build/html/_sources/changelog.rst.txt new file mode 100644 index 0000000..17cdc29 --- /dev/null +++ b/docs/_build/html/_sources/changelog.rst.txt @@ -0,0 +1,11 @@ +.. _changelog: + +Changelog +********* + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/changelog.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/contribute.rst.txt b/docs/_build/html/_sources/contribute.rst.txt new file mode 100644 index 0000000..933074d --- /dev/null +++ b/docs/_build/html/_sources/contribute.rst.txt @@ -0,0 +1,11 @@ +.. _how-to-contribute: + +Contributing to psy-simple +========================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/contribute.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.barplot.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.barplot.rst.txt new file mode 100644 index 0000000..15d41ef --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.barplot.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.barplot +============================ + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.barplot.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.combined.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.combined.rst.txt new file mode 100644 index 0000000..4451c62 --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.combined.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.combined +============================= + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.combined.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.density.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.density.rst.txt new file mode 100644 index 0000000..ad87abf --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.density.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.density +============================ + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.density.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.fldmean.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.fldmean.rst.txt new file mode 100644 index 0000000..14706e9 --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.fldmean.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.fldmean +============================ + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.fldmean.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.lineplot.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.lineplot.rst.txt new file mode 100644 index 0000000..78f60bb --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.lineplot.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.lineplot +============================= + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.lineplot.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.plot2d.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.plot2d.rst.txt new file mode 100644 index 0000000..ba8f43e --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.plot2d.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.plot2d +=========================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.plot2d.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.vector.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.vector.rst.txt new file mode 100644 index 0000000..cf85af4 --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.vector.rst.txt @@ -0,0 +1,9 @@ +psyplot.project.plot.vector +=========================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.vector.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/generated/psyplot.project.plot.violinplot.rst.txt b/docs/_build/html/_sources/generated/psyplot.project.plot.violinplot.rst.txt new file mode 100644 index 0000000..38b80d9 --- /dev/null +++ b/docs/_build/html/_sources/generated/psyplot.project.plot.violinplot.rst.txt @@ -0,0 +1,10 @@ +psyplot.project.plot.violinplot +=============================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.violinplot.html. + You should be redirected within 5 seconds. +

+ diff --git a/docs/_build/html/_sources/index.rst.txt b/docs/_build/html/_sources/index.rst.txt new file mode 100644 index 0000000..0d9b16f --- /dev/null +++ b/docs/_build/html/_sources/index.rst.txt @@ -0,0 +1,36 @@ +.. psyplot documentation master file, created by + sphinx-quickstart on Wed Sep 22 19:43:59 2021. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +.. _psy-simple: + +psy-simple: The psyplot plugin for simple visualizations +======================================================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/. + You should be redirected within 5 seconds. +

+ + +.. toctree:: + :maxdepth: 1 + :hidden: + + installing + plot_methods + contribute + api/psy_simple + changelog + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/_build/html/_sources/installing.rst.txt b/docs/_build/html/_sources/installing.rst.txt new file mode 100644 index 0000000..ba56852 --- /dev/null +++ b/docs/_build/html/_sources/installing.rst.txt @@ -0,0 +1,13 @@ +.. _install: + +.. highlight:: bash + +Installation +============ + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/installing.html. + You should be redirected within 5 seconds. +

diff --git a/docs/_build/html/_sources/plot_methods.rst.txt b/docs/_build/html/_sources/plot_methods.rst.txt new file mode 100644 index 0000000..20a661e --- /dev/null +++ b/docs/_build/html/_sources/plot_methods.rst.txt @@ -0,0 +1,25 @@ +.. _plot_methods: + +psyplot plot methods +==================== + +.. raw:: html + +

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/plot_methods.html. + You should be redirected within 5 seconds. +

+ + + +.. toctree:: + :hidden: + + generated/psyplot.project.plot.lineplot + generated/psyplot.project.plot.vector + generated/psyplot.project.plot.violinplot + generated/psyplot.project.plot.plot2d + generated/psyplot.project.plot.combined + generated/psyplot.project.plot.density + generated/psyplot.project.plot.barplot + generated/psyplot.project.plot.fldmean diff --git a/docs/_build/html/_static/alabaster.css b/docs/_build/html/_static/alabaster.css new file mode 100644 index 0000000..0eddaeb --- /dev/null +++ b/docs/_build/html/_static/alabaster.css @@ -0,0 +1,701 @@ +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: Georgia, 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: 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: Georgia, serif; + font-size: 1em; +} + +div.sphinxsidebar hr { + border: none; + height: 1px; + color: #AAA; + background: #AAA; + + text-align: left; + margin-left: 0; + width: 50%; +} + +div.sphinxsidebar .badge { + border-bottom: none; +} + +div.sphinxsidebar .badge:hover { + border-bottom: none; +} + +/* To address an issue with donation coming after search */ +div.sphinxsidebar h3.donation { + margin-top: 10px; +} + +/* -- 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: 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: #FBFBFB; + border-bottom: 1px solid #fafafa; +} + +div.admonition p.admonition-title { + font-family: 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', 'DejaVu 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; +} + +/* Cloned from + * https://github.com/sphinx-doc/sphinx/commit/ef60dbfce09286b20b7385333d63a60321784e68 + */ +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +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; +} + +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; +} + + +/* relbar */ + +.related { + line-height: 30px; + width: 100%; + font-size: 0.9rem; +} + +.related.top { + border-bottom: 1px solid #EEE; + margin-bottom: 20px; +} + +.related.bottom { + border-top: 1px solid #EEE; +} + +.related ul { + padding: 0; + margin: 0; + list-style: none; +} + +.related li { + display: inline; +} + +nav#rellinks { + float: right; +} + +nav#rellinks li+li:before { + content: "|"; +} + +nav#breadcrumbs li+li:before { + content: "\00BB"; +} + +/* Hide certain items when printing */ +@media print { + div.related { + display: none; + } +} \ No newline at end of file diff --git a/docs/_build/html/_static/basic.css b/docs/_build/html/_static/basic.css new file mode 100644 index 0000000..912859b --- /dev/null +++ b/docs/_build/html/_static/basic.css @@ -0,0 +1,904 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- 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 form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +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 p.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%; + margin-left: auto; + margin-right: auto; +} + +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 ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +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; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +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; +} + +a.brackets:before, +span.brackets > a:before{ + content: "["; +} + +a.brackets:after, +span.brackets > a:after { + content: "]"; +} + +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; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 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; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +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.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; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- 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; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +dl.footnote > dt, +dl.citation > dt { + float: left; + margin-right: 0.5em; +} + +dl.footnote > dd, +dl.citation > dd { + margin-bottom: 0em; +} + +dl.footnote > dd:after, +dl.citation > dd:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dt:after { + content: ":"; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.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; +} + +.classifier:before { + font-style: normal; + margin: 0.5em; + content: ":"; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +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 { + margin: 1em 0; +} + +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; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- 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/docs/_build/html/_static/custom.css b/docs/_build/html/_static/custom.css new file mode 100644 index 0000000..2a924f1 --- /dev/null +++ b/docs/_build/html/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/docs/_build/html/_static/doctools.js b/docs/_build/html/_static/doctools.js new file mode 100644 index 0000000..8cbf1b1 --- /dev/null +++ b/docs/_build/html/_static/doctools.js @@ -0,0 +1,323 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2021 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 + * + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL + */ +jQuery.urldecode = function(x) { + if (!x) { + return 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, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + 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); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * 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(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * 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 && $.browser.mozilla) + 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).keydown(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box, textarea, dropdown or button + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' + && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey + && !event.shiftKey) { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + break; + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + break; + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/docs/_build/html/_static/documentation_options.js b/docs/_build/html/_static/documentation_options.js new file mode 100644 index 0000000..018c277 --- /dev/null +++ b/docs/_build/html/_static/documentation_options.js @@ -0,0 +1,12 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '1.3.1', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false +}; \ No newline at end of file diff --git a/docs/_build/html/_static/file.png b/docs/_build/html/_static/file.png new file mode 100644 index 0000000..a858a41 Binary files /dev/null and b/docs/_build/html/_static/file.png differ diff --git a/docs/_build/html/_static/jquery-3.5.1.js b/docs/_build/html/_static/jquery-3.5.1.js new file mode 100644 index 0000000..5093733 --- /dev/null +++ b/docs/_build/html/_static/jquery-3.5.1.js @@ -0,0 +1,10872 @@ +/*! + * jQuery JavaScript Library v3.5.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2020-05-04T22:49Z + */ +( function( global, factory ) { + + "use strict"; + + 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 have a `window` with a `document` + // (such as Node.js), expose a 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 ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.5.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 ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // 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 all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // 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; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + 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 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + 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(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, 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" && !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 ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // 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() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // 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 ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + 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 length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + 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 flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.5 + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://js.foundation/ + * + * Date: 2020-03-14 + */ +( 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" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ( {} ).hasOwnProperty, + arr = [], + pop = arr.pop, + pushNative = arr.push, + push = arr.push, + slice = arr.slice, + + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[ 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 + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] + // or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // 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 + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "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" ) + }, + + rhtml = /HTML$/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 = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android<4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + pushNative.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 m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && + + // Support: IE 8 only + // Exclude object elements + ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + if ( newContext !== context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + 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 element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = 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 = arr.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 && + a.sourceIndex - b.sourceIndex; + + // 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 :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * 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 !== "undefined" && 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 ) { + var namespace = elem.namespaceURI, + docElem = ( elem.ownerDocument || elem ).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); +}; + +/** + * 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, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, + // Safari 4 - 5 only, Opera <=11.6 - 12.x only + // IE/Edge & older browsers don't support the :scope pseudo-class. + // Support: Safari 6.0 only + // Safari 6.0 supports :scope but it's an alias of :root there. + support.scope = assert( function( el ) { + docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); + return typeof el.querySelectorAll !== "undefined" && + !el.querySelectorAll( ":scope fieldset div" ).length; + } ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert( function( el ) { + el.className = "i"; + return !el.getAttribute( "className" ); + } ); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert( function( el ) { + el.appendChild( document.createComment( "" ) ); + return !el.getElementsByTagName( "*" ).length; + } ); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find[ "TAG" ] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + 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 !== "undefined" && 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 https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + // 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 + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).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 + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + + // 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 ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + } ); + + assert( function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.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 ( el.querySelectorAll( ":enabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: Opera 10 - 11 only + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll( "*,:x" ); + rbuggyQSA.push( ",.*:" ); + } ); + } + + if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector ) ) ) ) { + + assert( function( el ) { + + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[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 self-exclusive + // 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 + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + 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 + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document || a.ownerDocument == preferredDoc && + contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document || b.ownerDocument == preferredDoc && + contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( 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 ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + return a == document ? -1 : + b == document ? 1 : + /* eslint-enable eqeqeq */ + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( 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 + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + ap[ i ] == preferredDoc ? -1 : + bp[ i ] == preferredDoc ? 1 : + /* eslint-enable eqeqeq */ + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( support.matchesSelector && documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !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 ) { + nonnativeSelectorCache( expr, true ); + } + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + 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.escape = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +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 !== "undefined" && + 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 += ""; + + /* eslint-disable max-len */ + + 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.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + /* eslint-enable max-len */ + + }; + }, + + "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, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + 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 + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && 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 ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // 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 ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + uniqueCache[ 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( 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 ); + + // Don't keep the element (issue #299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + "has": markFunction( function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + } ), + + "contains": markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || 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": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( 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 ) { + // eslint-disable-next-line no-unused-expressions + 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 > length ? + 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, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "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 ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator 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 ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || + ( outerCache[ elem.uniqueID ] = {} ); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = uniqueCache[ key ] ) && + 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 + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +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( 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( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + 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 ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // 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; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, 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 ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + 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 only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + 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, + !context || 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-35+ +// 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( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert( function( el ) { + el.innerHTML = ""; + return el.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( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.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( el ) { + return el.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; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + 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; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : 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, + + // 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 <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ 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; + + // Option to run 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 ( 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 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).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[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + 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.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.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.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + 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 indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + 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 ) { + while ( ( cur = cur[ dir ] ) && 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 dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], 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" ? + 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, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + 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.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + 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; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).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 = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + 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( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + 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, + + // 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; + } + + // 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 ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !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 < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( 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 public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", 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 = dataPriv.get( 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 rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + 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 || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 - 11+ +// focus() and blur() are asynchronous, except when they are no-op. +// So expect focus to be synchronous when the element is already active, +// and blur to be synchronous when the element is not already active. +// (focus and blur are always synchronous in other supported browsers, +// this just defines when we can count on it). +function expectSync( elem, type ) { + return ( elem === safeActiveElement() ) === ( type === "focus" ); +} + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // 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 ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + 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 elem; + } + + 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 elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * 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 handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + 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; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, 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 = Object.create( null ); + } + 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 !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + 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 if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( 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; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + 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 data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + 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() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.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 i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", returnTrue ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( 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; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, expectSync ) { + + // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add + if ( !expectSync ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var notAsync, result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + // Saved data should be false in such cases, but might be a leftover capture object + // from an async native handler (gh-4350) + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + // Support: IE <=9 - 11+ + // focus() and blur() are asynchronous + notAsync = expectSync( this, type ); + this[ type ](); + result = dataPriv.get( this, type ); + if ( saved !== result || notAsync ) { + dataPriv.set( this, type, false ); + } else { + result = {}; + } + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + return result.value; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering the + // native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + + // Support: IE <=9 - 11+ + // Extend with the prototype to reset the above stopImmediatePropagation() + jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event + event.stopImmediatePropagation(); + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, 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: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // 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 || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, expectSync ); + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +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 mouseenter/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; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, 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 ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + 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 ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ 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 || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + 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 ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, 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 domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + 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 && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + 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 ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px"; + tr.style.height = "1px"; + trChild.style.height = "9px"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "gridArea": true, + "gridColumn": true, + "gridColumnEnd": true, + "gridColumnStart": true, + "gridRow": true, + "gridRowEnd": true, + "gridRowStart": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( isValidValue ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = classesToArray( value ); + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = 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( "." ) > -1 ) { + + // 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.rnamespace = 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 && !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() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( + dataPriv.get( cur, "events" ) || Object.create( null ) + )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && 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 ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && isFunction( elem[ type ] ) && !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; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + 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 ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + 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 ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script + if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.colors module¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.colors.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.html b/docs/_build/html/api/psy_simple.html new file mode 100644 index 0000000..04dc483 --- /dev/null +++ b/docs/_build/html/api/psy_simple.html @@ -0,0 +1,121 @@ + + + + + + + + + API Reference — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

API Reference¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.html. + You should be redirected within 5 seconds. +

+

Subpackages¶

+
+
+
+
+

Submodules¶

+
+
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.plotters.html b/docs/_build/html/api/psy_simple.plotters.html new file mode 100644 index 0000000..5731311 --- /dev/null +++ b/docs/_build/html/api/psy_simple.plotters.html @@ -0,0 +1,113 @@ + + + + + + + + + psy_simple.plotters module — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.plotters module¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.plotters.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.plugin.html b/docs/_build/html/api/psy_simple.plugin.html new file mode 100644 index 0000000..3dcbd0f --- /dev/null +++ b/docs/_build/html/api/psy_simple.plugin.html @@ -0,0 +1,113 @@ + + + + + + + + + psy_simple.plugin module — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.plugin module¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.plugin.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.widgets.colors.html b/docs/_build/html/api/psy_simple.widgets.colors.html new file mode 100644 index 0000000..517b439 --- /dev/null +++ b/docs/_build/html/api/psy_simple.widgets.colors.html @@ -0,0 +1,115 @@ + + + + + + + + + psy_simple.widgets.colors module — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.widgets.colors module¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.colors.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.widgets.html b/docs/_build/html/api/psy_simple.widgets.html new file mode 100644 index 0000000..9a8667b --- /dev/null +++ b/docs/_build/html/api/psy_simple.widgets.html @@ -0,0 +1,118 @@ + + + + + + + + + psy_simple.widgets package — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.widgets package¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.html. + You should be redirected within 5 seconds. +

+

Submodules¶

+
+
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/api/psy_simple.widgets.texts.html b/docs/_build/html/api/psy_simple.widgets.texts.html new file mode 100644 index 0000000..a50344a --- /dev/null +++ b/docs/_build/html/api/psy_simple.widgets.texts.html @@ -0,0 +1,115 @@ + + + + + + + + + psy_simple.widgets.texts module — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy_simple.widgets.texts module¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/api/psy_simple.widgets.texts.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/changelog.html b/docs/_build/html/changelog.html new file mode 100644 index 0000000..918201f --- /dev/null +++ b/docs/_build/html/changelog.html @@ -0,0 +1,109 @@ + + + + + + + + + Changelog — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Changelog¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/changelog.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/contribute.html b/docs/_build/html/contribute.html new file mode 100644 index 0000000..79810b0 --- /dev/null +++ b/docs/_build/html/contribute.html @@ -0,0 +1,111 @@ + + + + + + + + + Contributing to psy-simple — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Contributing to psy-simple¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/contribute.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.barplot.html b/docs/_build/html/generated/psyplot.project.plot.barplot.html new file mode 100644 index 0000000..fcca7f5 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.barplot.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.barplot — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.barplot¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.barplot.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.combined.html b/docs/_build/html/generated/psyplot.project.plot.combined.html new file mode 100644 index 0000000..9ba57e5 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.combined.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.combined — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.combined¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.combined.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.density.html b/docs/_build/html/generated/psyplot.project.plot.density.html new file mode 100644 index 0000000..61d45e2 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.density.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.density — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.density¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.density.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.fldmean.html b/docs/_build/html/generated/psyplot.project.plot.fldmean.html new file mode 100644 index 0000000..128a971 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.fldmean.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.fldmean — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.fldmean¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.fldmean.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.lineplot.html b/docs/_build/html/generated/psyplot.project.plot.lineplot.html new file mode 100644 index 0000000..c3c1972 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.lineplot.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.lineplot — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.lineplot¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.lineplot.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.plot2d.html b/docs/_build/html/generated/psyplot.project.plot.plot2d.html new file mode 100644 index 0000000..02e7591 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.plot2d.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.plot2d — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.plot2d¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.plot2d.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.vector.html b/docs/_build/html/generated/psyplot.project.plot.vector.html new file mode 100644 index 0000000..72e8da1 --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.vector.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.vector — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.vector¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.vector.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/generated/psyplot.project.plot.violinplot.html b/docs/_build/html/generated/psyplot.project.plot.violinplot.html new file mode 100644 index 0000000..562ba5d --- /dev/null +++ b/docs/_build/html/generated/psyplot.project.plot.violinplot.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot.project.plot.violinplot — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot.project.plot.violinplot¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/generated/psyplot.project.plot.violinplot.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/genindex.html b/docs/_build/html/genindex.html new file mode 100644 index 0000000..bcce678 --- /dev/null +++ b/docs/_build/html/genindex.html @@ -0,0 +1,103 @@ + + + + + + + + Index — psy-simple 1.3.1 documentation + + + + + + + + + + + + + +
+
+
+ + +
+ + +

Index

+ +
+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/index.html b/docs/_build/html/index.html new file mode 100644 index 0000000..812dbb5 --- /dev/null +++ b/docs/_build/html/index.html @@ -0,0 +1,119 @@ + + + + + + + + + psy-simple: The psyplot plugin for simple visualizations — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psy-simple: The psyplot plugin for simple visualizations¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/. + You should be redirected within 5 seconds. +

+
+
+
+

Indices and tables¶

+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/installing.html b/docs/_build/html/installing.html new file mode 100644 index 0000000..14e2a16 --- /dev/null +++ b/docs/_build/html/installing.html @@ -0,0 +1,111 @@ + + + + + + + + + Installation — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Installation¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/installing.html. + You should be redirected within 5 seconds. +

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/objects.inv b/docs/_build/html/objects.inv new file mode 100644 index 0000000..f297de6 Binary files /dev/null and b/docs/_build/html/objects.inv differ diff --git a/docs/_build/html/plot_methods.html b/docs/_build/html/plot_methods.html new file mode 100644 index 0000000..4be586d --- /dev/null +++ b/docs/_build/html/plot_methods.html @@ -0,0 +1,113 @@ + + + + + + + + + psyplot plot methods — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

psyplot plot methods¶

+

+ The documentation of psy-simple is now hosted at, https://psyplot.github.io/psy-simple/plot_methods.html. + You should be redirected within 5 seconds. +

+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/search.html b/docs/_build/html/search.html new file mode 100644 index 0000000..aef1648 --- /dev/null +++ b/docs/_build/html/search.html @@ -0,0 +1,122 @@ + + + + + + + + Search — psy-simple 1.3.1 documentation + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Search

+ + + + +

+ Searching for multiple words only shows matches that contain + all words. +

+ + +
+ + + +
+ + + +
+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/_build/html/searchindex.js b/docs/_build/html/searchindex.js new file mode 100644 index 0000000..6caac05 --- /dev/null +++ b/docs/_build/html/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["api/psy_simple","api/psy_simple.colors","api/psy_simple.plotters","api/psy_simple.plugin","api/psy_simple.widgets","api/psy_simple.widgets.colors","api/psy_simple.widgets.texts","changelog","contribute","generated/psyplot.project.plot.barplot","generated/psyplot.project.plot.combined","generated/psyplot.project.plot.density","generated/psyplot.project.plot.fldmean","generated/psyplot.project.plot.lineplot","generated/psyplot.project.plot.plot2d","generated/psyplot.project.plot.vector","generated/psyplot.project.plot.violinplot","index","installing","plot_methods"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":4,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,sphinx:56},filenames:["api/psy_simple.rst","api/psy_simple.colors.rst","api/psy_simple.plotters.rst","api/psy_simple.plugin.rst","api/psy_simple.widgets.rst","api/psy_simple.widgets.colors.rst","api/psy_simple.widgets.texts.rst","changelog.rst","contribute.rst","generated/psyplot.project.plot.barplot.rst","generated/psyplot.project.plot.combined.rst","generated/psyplot.project.plot.density.rst","generated/psyplot.project.plot.fldmean.rst","generated/psyplot.project.plot.lineplot.rst","generated/psyplot.project.plot.plot2d.rst","generated/psyplot.project.plot.vector.rst","generated/psyplot.project.plot.violinplot.rst","index.rst","installing.rst","plot_methods.rst"],objects:{},objnames:{},objtypes:{},terms:{"5":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],The:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19],api:[1,2,3,4,5,6],document:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],gener:[9,10,11,12,13,14,15,16],github:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],host:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],html:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19],http:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],index:17,io:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],modul:17,now:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],page:17,plot_method:19,psy:[0,1,2,3,4,5,6,7,9,10,11,12,13,14,15,16,18,19],psy_simpl:0,psyplot:[0,1,2,3,4,5,6,7,8,18],redirect:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],search:17,second:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],should:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],simpl:[0,1,2,3,4,5,6,7,9,10,11,12,13,14,15,16,18,19],within:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],you:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]},titles:["API Reference","psy_simple.colors module","psy_simple.plotters module","psy_simple.plugin module","psy_simple.widgets package","psy_simple.widgets.colors module","psy_simple.widgets.texts module","Changelog","Contributing to psy-simple","psyplot.project.plot.barplot","psyplot.project.plot.combined","psyplot.project.plot.density","psyplot.project.plot.fldmean","psyplot.project.plot.lineplot","psyplot.project.plot.plot2d","psyplot.project.plot.vector","psyplot.project.plot.violinplot","psy-simple: The psyplot plugin for simple visualizations","Installation","psyplot plot methods"],titleterms:{The:17,api:0,barplot:9,changelog:7,color:[1,5],combin:10,contribut:8,densiti:11,fldmean:12,indic:17,instal:18,lineplot:13,method:19,modul:[1,2,3,5,6],packag:4,plot2d:14,plot:[9,10,11,12,13,14,15,16,19],plotter:2,plugin:[3,17],project:[9,10,11,12,13,14,15,16],psy:[8,17],psy_simpl:[1,2,3,4,5,6],psyplot:[9,10,11,12,13,14,15,16,17,19],refer:0,simpl:[8,17],submodul:[0,4],subpackag:0,tabl:17,text:6,vector:15,violinplot:16,visual:17,widget:[4,5,6]}}) \ No newline at end of file diff --git a/psyplot_gui/sphinx_supp/_static/.gitignore b/docs/_templates/.gitignore similarity index 100% rename from psyplot_gui/sphinx_supp/_static/.gitignore rename to docs/_templates/.gitignore diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html new file mode 100644 index 0000000..de23d11 --- /dev/null +++ b/docs/_templates/layout.html @@ -0,0 +1,5 @@ +{% extends "!layout.html" %} + +{% block extrahead %} + +{% endblock %} \ No newline at end of file diff --git a/docs/api/psyplot_gui.backend.rst b/docs/api/psyplot_gui.backend.rst new file mode 100644 index 0000000..7a6c4b3 --- /dev/null +++ b/docs/api/psyplot_gui.backend.rst @@ -0,0 +1,9 @@ +psyplot\_gui.backend module +=========================== + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.backend.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.common.rst b/docs/api/psyplot_gui.common.rst new file mode 100644 index 0000000..80aabcd --- /dev/null +++ b/docs/api/psyplot_gui.common.rst @@ -0,0 +1,10 @@ +psyplot\_gui.common module +========================== + +. +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.common.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.compat.qtcompat.rst b/docs/api/psyplot_gui.compat.qtcompat.rst new file mode 100644 index 0000000..1ef242d --- /dev/null +++ b/docs/api/psyplot_gui.compat.qtcompat.rst @@ -0,0 +1,10 @@ +psyplot\_gui.compat.qtcompat module +=================================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.compat.qtcompat.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.compat.rst b/docs/api/psyplot_gui.compat.rst new file mode 100644 index 0000000..0912cb1 --- /dev/null +++ b/docs/api/psyplot_gui.compat.rst @@ -0,0 +1,20 @@ +psyplot\_gui.compat package +=========================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.compat.html. + You should be redirected within 5 seconds. +

+ + +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psyplot_gui.compat.qtcompat diff --git a/docs/api/psyplot_gui.config.rcsetup.rst b/docs/api/psyplot_gui.config.rcsetup.rst new file mode 100644 index 0000000..9d5c381 --- /dev/null +++ b/docs/api/psyplot_gui.config.rcsetup.rst @@ -0,0 +1,10 @@ +psyplot\_gui.config.rcsetup module +================================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.config.rcsetup.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.config.rst b/docs/api/psyplot_gui.config.rst new file mode 100644 index 0000000..f9e896c --- /dev/null +++ b/docs/api/psyplot_gui.config.rst @@ -0,0 +1,20 @@ +psyplot\_gui.config package +=========================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.config.html. + You should be redirected within 5 seconds. +

+ + +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psyplot_gui.config.rcsetup diff --git a/docs/api/psyplot_gui.console.rst b/docs/api/psyplot_gui.console.rst new file mode 100644 index 0000000..4e41511 --- /dev/null +++ b/docs/api/psyplot_gui.console.rst @@ -0,0 +1,10 @@ +psyplot\_gui.console module +=========================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.console.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.content_widget.rst b/docs/api/psyplot_gui.content_widget.rst new file mode 100644 index 0000000..c724615 --- /dev/null +++ b/docs/api/psyplot_gui.content_widget.rst @@ -0,0 +1,10 @@ +psyplot\_gui.content\_widget module +=================================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.content_widget.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.dataframeeditor.rst b/docs/api/psyplot_gui.dataframeeditor.rst new file mode 100644 index 0000000..7872ef7 --- /dev/null +++ b/docs/api/psyplot_gui.dataframeeditor.rst @@ -0,0 +1,9 @@ +psyplot\_gui.dataframeeditor module +=================================== + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.dataframeeditor.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.dependencies.rst b/docs/api/psyplot_gui.dependencies.rst new file mode 100644 index 0000000..0bf897b --- /dev/null +++ b/docs/api/psyplot_gui.dependencies.rst @@ -0,0 +1,9 @@ +psyplot\_gui.dependencies module +================================ + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.dependencies.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.fmt_widget.rst b/docs/api/psyplot_gui.fmt_widget.rst new file mode 100644 index 0000000..fac7a75 --- /dev/null +++ b/docs/api/psyplot_gui.fmt_widget.rst @@ -0,0 +1,10 @@ +psyplot\_gui.fmt\_widget module +=============================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.fmw_widget.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.help_explorer.rst b/docs/api/psyplot_gui.help_explorer.rst new file mode 100644 index 0000000..5dd4054 --- /dev/null +++ b/docs/api/psyplot_gui.help_explorer.rst @@ -0,0 +1,9 @@ +psyplot\_gui.help\_explorer module +================================== + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.help_explorer.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.main.rst b/docs/api/psyplot_gui.main.rst new file mode 100644 index 0000000..5d47f7f --- /dev/null +++ b/docs/api/psyplot_gui.main.rst @@ -0,0 +1,10 @@ +psyplot\_gui.main module +======================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.main.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.plot_creator.rst b/docs/api/psyplot_gui.plot_creator.rst new file mode 100644 index 0000000..bc3aea2 --- /dev/null +++ b/docs/api/psyplot_gui.plot_creator.rst @@ -0,0 +1,9 @@ +psyplot\_gui.plot\_creator module +================================= + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.plot_creator.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.preferences.rst b/docs/api/psyplot_gui.preferences.rst new file mode 100644 index 0000000..6f19b9b --- /dev/null +++ b/docs/api/psyplot_gui.preferences.rst @@ -0,0 +1,10 @@ +psyplot\_gui.preferences module +=============================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.preferences.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.rst b/docs/api/psyplot_gui.rst new file mode 100644 index 0000000..7a53c24 --- /dev/null +++ b/docs/api/psyplot_gui.rst @@ -0,0 +1,41 @@ +API Reference +==================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.html. + You should be redirected within 5 seconds. +

+ + +Subpackages +----------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psyplot_gui.compat + psyplot_gui.config + psyplot_gui.sphinx_supp + +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psyplot_gui.backend + psyplot_gui.common + psyplot_gui.console + psyplot_gui.content_widget + psyplot_gui.dataframeeditor + psyplot_gui.dependencies + psyplot_gui.fmt_widget + psyplot_gui.help_explorer + psyplot_gui.main + psyplot_gui.plot_creator + psyplot_gui.preferences diff --git a/docs/api/psyplot_gui.sphinx_supp.conf.rst b/docs/api/psyplot_gui.sphinx_supp.conf.rst new file mode 100644 index 0000000..0d6abb1 --- /dev/null +++ b/docs/api/psyplot_gui.sphinx_supp.conf.rst @@ -0,0 +1,10 @@ +psyplot\_gui.sphinx\_supp.conf module +===================================== + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.sphinx_supp.conf.html. + You should be redirected within 5 seconds. +

diff --git a/docs/api/psyplot_gui.sphinx_supp.rst b/docs/api/psyplot_gui.sphinx_supp.rst new file mode 100644 index 0000000..8a0fbba --- /dev/null +++ b/docs/api/psyplot_gui.sphinx_supp.rst @@ -0,0 +1,20 @@ +psyplot\_gui.sphinx\_supp package +================================= + + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/api/psyplot_gui.sphinx_supp.html. + You should be redirected within 5 seconds. +

+ + +Submodules +---------- + +.. toctree:: + :maxdepth: 4 + :hidden: + + psyplot_gui.sphinx_supp.conf diff --git a/docs/apigen.bash b/docs/apigen.bash deleted file mode 100755 index d3344c6..0000000 --- a/docs/apigen.bash +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -set -e -# script to automatically generate the psyplot api documentation using -# sphinx-apidoc and sed -sphinx-apidoc -f -M -e -T -o api ../psyplot_gui/ -# replace chapter title in psyplot.rst -sed -i -e '1,1s/.*/API Reference/' api/psyplot_gui.rst - -sphinx-autogen -o generated *.rst */*.rst diff --git a/docs/changelog.rst b/docs/changelog.rst index c393d07..f5b6a47 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ .. _changelog: Changelog -********* +========= -.. include:: ../CHANGELOG.rst + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/changelog.html. + You should be redirected within 5 seconds. +

diff --git a/docs/command_line.rst b/docs/command_line.rst index 81c39af..3f77c1d 100644 --- a/docs/command_line.rst +++ b/docs/command_line.rst @@ -1,21 +1,14 @@ +.. highlight:: bash + .. _command-line: Command line usage ================== -The ``psyplot-gui`` module extends the -`command line usage of the psyplot module`_. You can open one (or more) files -in the graphical user interface simply via:: - - $ psyplot myfile.nc -By default, if the gui is already running, the file is opened in this gui -unless you specify the ``ni`` option. - -.. highlight:: bash -.. argparse:: - :module: psyplot_gui - :func: get_parser - :prog: psyplot +.. raw:: html -.. _command line usage of the psyplot module: http://psyplot.github.io/psyplot/command_line.html +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/command_line.html. + You should be redirected within 5 seconds. +

diff --git a/docs/conf.py b/docs/conf.py index 487f03b..1605082 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,207 +1,57 @@ -# -*- coding: utf-8 -*- +# Configuration file for the Sphinx documentation builder. # -# psyplot documentation build configuration file, created by -# sphinx-quickstart on Mon Jul 20 18:01:33 2015. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. # -# All configuration values have a default; values that are commented out -# serve to show the default. +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) -import sphinx -import os -import os.path as osp -import subprocess as spr -import re -import six -from itertools import product -import psyplot_gui -import matplotlib as mpl -import warnings +# -- Project information ----------------------------------------------------- -warnings.filterwarnings( - 'ignore', message=r"\s*The Panel class is removed from pandas") +project = 'psyplot-gui' +copyright = '2021, Philipp S. Sommer' +author = 'Philipp S. Sommer' +# The full version, including alpha/beta/rc tags +release = '1.3.1' -mpl.use('agg') -# -- General configuration ------------------------------------------------ +# -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.doctest', - 'sphinx.ext.intersphinx', - 'sphinx.ext.autosummary', - 'sphinx.ext.todo', - 'sphinx.ext.viewcode', - 'matplotlib.sphinxext.plot_directive', - 'IPython.sphinxext.ipython_console_highlighting', - 'IPython.sphinxext.ipython_directive', - 'sphinxarg.ext', - 'psyplot.sphinxext.extended_napoleon', - 'autodocsumm', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] -# create the api documentation -if not osp.exists(osp.join(osp.dirname(__file__), 'api')): - spr.check_call(['bash', 'apigen.bash']) - -napoleon_use_admonition_for_examples = True - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = '.rst' - -# The master toctree document. -master_doc = 'index' - -autodoc_default_options = { - 'show_inheritance': True, - 'autosummary': True, -} - -autoclass_content = 'both' - -not_document_data = ['psyplot_gui.config.rcsetup.defaultParams', - 'psyplot_gui.config.rcsetup.rcParams'] - -ipython_savefig_dir = os.path.join(os.path.dirname(__file__), '_static') - -# General information about the project. -project = 'psyplot-gui' -copyright = ", ".join( - psyplot_gui.__copyright__.strip().replace("Copyright (C) ", "").splitlines() -) -author = psyplot_gui.__author__ - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = re.match(r'\d+\.\d+\.\d+', psyplot_gui.__version__).group() -# The full version, including alpha/beta/rc tags. -release = psyplot_gui.__version__ - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] +# The master toctree document. +master_doc = 'index' -# -- Options for HTML output ---------------------------------------------- +# -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. - -html_theme = 'sphinx_rtd_theme' - -# otherwise, readthedocs.org uses their theme by default, so no need to specify +# +html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] - -# Output file base name for HTML help builder. -htmlhelp_basename = 'psyplotguidoc' - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # Additional stuff for the LaTeX preamble. - 'preamble': '\setcounter{tocdepth}{10}' -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'psyplot-gui.tex', u'psyplot GUI Documentation', - author, 'manual'), -] - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'psyplot-gui', u'psyplot GUI Documentation', - [author], 1) -] - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'psyplot-gui', u'psyplot GUI Documentation', - author, 'psyplot-gui', 'Graphical user interface for the psyplot package', - 'Visualization'), -] - -# -- Options for Epub output ---------------------------------------------- - -# Bibliographic Dublin Core info. -epub_title = project -epub_author = author -epub_publisher = author -epub_copyright = copyright - -# A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), - 'numpy': ('https://docs.scipy.org/doc/numpy/', None), - 'matplotlib': ('https://matplotlib.org/stable/', None), - 'sphinx': ('https://www.sphinx-doc.org/en/stable/', None), - 'xarray': ('https://xarray.pydata.org/en/stable/', None), - 'cartopy': ('https://scitools.org.uk/cartopy/docs/latest/', None), - 'mpl_toolkits': ('https://matplotlib.org/basemap/', None), - 'psyplot': ('https://psyplot.github.io/psyplot/', None), - 'python': ('https://docs.python.org/3/', None), -} - -replacements = { - '`psyplot.rcParams`': '`~psyplot.config.rcsetup.rcParams`', - '`psyplot.InteractiveList`': '`~psyplot.data.InteractiveList`', - '`psyplot.InteractiveArray`': '`~psyplot.data.InteractiveArray`', - '`psyplot.open_dataset`': '`~psyplot.data.open_dataset`', - '`psyplot.open_mfdataset`': '`~psyplot.data.open_mfdataset`', - } - - -def link_aliases(app, what, name, obj, options, lines): - for (key, val), (i, line) in product(six.iteritems(replacements), - enumerate(lines)): - lines[i] = line.replace(key, val) - - -def setup(app): - app.connect('autodoc-process-docstring', link_aliases) - return {'version': sphinx.__display_version__, 'parallel_read_safe': True} diff --git a/docs/configuration.rst b/docs/configuration.rst index 238dac3..234d3de 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -3,22 +3,9 @@ Configuration of the GUI ======================== -As psyplot is configured by the :attr:`psyplot.config.rcsetup.rcParams`, -psyplot-gui is configured by the :attr:`psyplot_gui.config.rcsetup.rcParams` -dictionary. +.. raw:: html -Both dictionaries can also be modified through the *Preferences* -widget (on MacOS, :kbd:`Command+,`, on Windows and Linux: -:menuselection:`Help --> Preferences`). - -As for ``psyplot``, the rcParams are stored in the psyplot configuration -directory, which is, under Linux and OSX by default, located at -``$HOME/.config/psyplot/psyplotguirc.yml`` and under Windows at -``$HOME/.psyplot/psyplotguirc.yml``. -This file might look like - -.. ipython:: - - In [1]: from psyplot_gui import rcParams - - In [2]: print(rcParams.dump()) +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/configuration.html. + You should be redirected within 5 seconds. +

diff --git a/docs/contribute.rst b/docs/contribute.rst index ba0163d..265242b 100644 --- a/docs/contribute.rst +++ b/docs/contribute.rst @@ -1,8 +1,11 @@ .. _how-to-contribute: Contributing to psyplot-gui -=========================== +========================== -First off, thanks for taking the time to contribute! +.. raw:: html -Please see the section about :ref:`contributing to psyplot ` for details. +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/contribute.html. + You should be redirected within 5 seconds. +

diff --git a/docs/environment.yml b/docs/environment.yml deleted file mode 100644 index 7cd0fa5..0000000 --- a/docs/environment.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: psyplot_gui_docs -channels: - - local - - psyplot/label/master - - conda-forge -dependencies: - - python=3.8 - - qtconsole - - dask - - netcdf4 - - sphinx_rtd_theme - - ipykernel - - pexpect - - pygments - - pyqt - - sphinx - - psy-simple - - psyplot-gui - - autodocsumm - - fasteners - - sphinx-argparse diff --git a/docs/explained_screenshot.pdf b/docs/explained_screenshot.pdf deleted file mode 100644 index 86a5da0..0000000 Binary files a/docs/explained_screenshot.pdf and /dev/null differ diff --git a/docs/explained_screenshot.png b/docs/explained_screenshot.png deleted file mode 100644 index ed74c82..0000000 Binary files a/docs/explained_screenshot.png and /dev/null differ diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 49f9904..785259f 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -3,144 +3,10 @@ Getting started =============== -.. image:: explained_screenshot.png - :width: 100% -The Screenshot above shows you the essential parts of the GUI: +.. raw:: html -- :ref:`console`: An IPython console -- :ref:`help-explorer`: A browser to display help and browse in the internet -- :ref:`plot-creator`: A widget to create new plots and open datasets -- :ref:`project-content`: A widget to interact with the psyplot project -- :ref:`formatoptions`: A widget to update and change formatoptions - -Starting the GUI ----------------- -Starting the GUI is straight forward but depends on how you installed it. If -you installed it via `conda` or `pip`, just open a terminal (or Command Window -``cmd`` on Windows) and type ``psyplot``. - -.. _console: - -The Console ------------ -The central widget in the GUI is an in-process IPython_ console that provides -the possibility to communicate with the psyplot package via the command line -and to load any other module or to run any other script. - -It is based on the qtconsole module and it is, by default, connected to the -:ref:`help explorer `. If you type, for example, - -.. code-block:: python - - np.sum( - -it will show you the documentation of the :func:`numpy.sum` module in the -:ref:`help explorer `. The same comes, if you type:: - - np.sum? - -This feature is motivated from the Spyder_ editor and can be disabled via -the rcParams key ``console.connect_to_help`` (see :ref:`configuration`) or the -little |ipython_console| symbol at the top of the help explorer. - -Furthermore, is connected to the current psyplot project (see -:func:`psyplot.project.scp` and :func:`psyplot.project.gcp`). Those are - -sp - This variable links to the current subproject (``psy.gcp()``) -mp - This variable links to the current main project (``psy.gcp(True)``) - -The following example, which you can just copy and paste in the console of the -GUI, illustrates this: - -.. ipython:: - - @suppress - In [1]: import matplotlib as mpl - ...: mpl.use('agg') - ...: import psyplot.project as psy - ...: import xarray as xr - ...: sp = psy.gcp() - ...: mp = psy.gcp(True) - - # in the beginning, sp and mp are empty - In [1]: print(sp) - ...: print(mp) - - In [2]: psy.plot.lineplot(xr.DataArray([1, 2, 3], name='test').to_dataset()) - - @suppress - In [3]: sp = psy.gcp() - ...: mp = psy.gcp(True) - - # now they both contain this data - In [3]: print(sp) - ...: print(mp) - - # lets create a second one - In [4]: psy.plot.lineplot(xr.DataArray([1, 2, 3], name='test2').to_dataset()) - - @suppress - In [5]: sp = psy.gcp() - - # sp now only contains the new one, mp contains both - In [5]: print(sp) - ...: print(mp) - -If you do not wish this behaviour, set the ``console.auto_set_mp`` and -``console.auto_set_sp`` rcParams to ``False``. - -.. |ipython_console| image:: ipython_console.png - -.. _IPython: http://ipython.readthedocs.io/en/stable/ -.. _qtconsole: https://qtconsole.readthedocs.io/en/stable/ -.. _Spyder: https://www.spyder-ide.org/ - -.. _help-explorer: - -The Help Explorer ------------------ -The help explorer provides you access to python objects and online information. -It can be used as a webbrowser if the |world| icon is not clicked or the -``help_explorer.online`` rcParams key is True (see :ref:`configuration`). - -It is motivated by the Help of the Spyder_ editor and uses Sphinx to -automatically render python documentation written in restructured Text. - -By default, the help explorer uses the ``intersphinx`` extension to link to -different online libraries. This however always consumes time at the startup -and can be disabled by the ``help_explorer.use_intersphinx`` rcParams key. - -It is also connected to the information functions of psyplot, e.g. the -:func:`psyplot.plotter.Plotter.show_keys` function. For example - -.. ipython:: - - In [1]: psy.plot.lineplot.keys() - -would be converted to HTML and shown in the help explorer. - -.. |world| image:: world.png - -.. _plot-creator: - -The Plot Creator ----------------- -The plot creator is used to create new plots from a :class:`xarray.Dataset`. -You can open it via :menuselection:`File --> New Plot`. - -.. _project-content: - -The Project content -------------------- -The project content shows you the current project (see -:func:`psyplot.project.gcp`). The selected arrays are the current subproject. - -.. _formatoptions: - -The formatoptions widget ------------------------- -The formatoption widget can be used to update the formatoptions of the current -subproject or to show their help. +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/getting_started.html. + You should be redirected within 5 seconds. +

diff --git a/docs/index.rst b/docs/index.rst index 6a896f8..245945a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,122 +1,27 @@ -.. psyplot-gui documentation master file +.. psyplot documentation master file, created by + sphinx-quickstart on Wed Sep 22 19:43:59 2021. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. .. _psyplot-gui: -Graphical User Interface for the psyplot package -================================================ +psyplot-gui: The psyplot plugin for simple visualizations +======================================================== -Welcome! This package enhances the interactive visualization framework -psyplot_ with a graphical user interface using PyQt_. See the homepage of the -main project on examples on the possibilities with psyplot_. +.. raw:: html -.. only:: html and not epub +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/. + You should be redirected within 5 seconds. +

- .. list-table:: - :stub-columns: 1 - :widths: 10 90 - - * - docs - - |docs| - * - tests - - |circleci| |appveyor| |requires| |codecov| - * - package - - |version| |conda| |github| |zenodo| - * - implementations - - |supported-versions| |supported-implementations| - - .. |docs| image:: http://readthedocs.org/projects/psyplot-gui/badge/?version=latest - :alt: Documentation Status - :target: http://psyplot-gui.readthedocs.io/en/latest/?badge=latest - - .. |circleci| image:: https://circleci.com/gh/psyplot/psyplot-gui/tree/master.svg?style=svg - :alt: CircleCI - :target: https://circleci.com/gh/psyplot/psyplot-gui/tree/master - - .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/bud4ov6lddrjvt88/branch/master?svg=true - :alt: AppVeyor - :target: https://ci.appveyor.com/project/psyplot/psyplot-gui-q726s - - .. |codecov| image:: https://codecov.io/gh/psyplot/psyplot-gui/branch/master/graph/badge.svg - :alt: Coverage - :target: https://codecov.io/gh/psyplot/psyplot-gui - - .. |requires| image:: https://requires.io/github/psyplot/psyplot-gui/requirements.svg?branch=master - :alt: Requirements Status - :target: https://requires.io/github/psyplot/psyplot-gui/requirements/?branch=master - - .. |version| image:: https://img.shields.io/pypi/v/psyplot-gui.svg?style=flat - :alt: PyPI Package latest release - :target: https://pypi.python.org/pypi/psyplot-gui - - .. |conda| image:: https://anaconda.org/conda-forge/psyplot-gui/badges/version.svg - :alt: conda - :target: https://anaconda.org/conda-forge/psyplot-gui - - .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/psyplot-gui.svg?style=flat - :alt: Supported versions - :target: https://pypi.python.org/pypi/psyplot-gui - - .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/psyplot-gui.svg?style=flat - :alt: Supported implementations - :target: https://pypi.python.org/pypi/psyplot-gui - - .. |zenodo| image:: https://zenodo.org/badge/55793611.svg - :alt: Zenodo - :target: https://zenodo.org/badge/latestdoi/55793611 - - .. |github| image:: https://img.shields.io/github/release/psyplot/psyplot-gui.svg - :target: https://github.com/psyplot/psyplot-gui/releases/latest - :alt: Latest github release - - -Documentation -------------- .. toctree:: :maxdepth: 1 + :hidden: installing - getting_started - configuration - command_line - plugins + plot_methods contribute api/psyplot_gui changelog - todos - -.. _PyQt: https://riverbankcomputing.com/software/pyqt/intro -.. _psyplot: https://psyplot.github.io/psyplot/ - - -Copyright ---------- -Copyright (C) 2021 Helmholtz-Zentrum Hereon - -Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht - -Copyright (C) 2016-2021 University of Lausanne - -psyplot-gui is released under the GNU LGPL-3.O license. -See COPYING and COPYING.LESSER in the root of the repository for full -licensing details. - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License version 3.0 as -published by the Free Software Foundation. - -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 LGPL-3.0 license for more details. - -You should have received a copy of the GNU LGPL-3.0 license -along with the program. If not, see . - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/installing.rst b/docs/installing.rst index 93f9d68..84bc278 100644 --- a/docs/installing.rst +++ b/docs/installing.rst @@ -4,54 +4,10 @@ Installation ============ -This package requires the psyplot package which is installed alongside if you -use ``conda`` or ``pip``. However see the psyplot_ documentation for further -informations. -How to install --------------- +.. raw:: html -Installation using conda -^^^^^^^^^^^^^^^^^^^^^^^^ -We highly recommend to use conda_ for installing psyplot-gui. - -You can then install psyplot-gui simply via:: - - $ conda install -c conda-forge psyplot-gui - - -Installation using pip -^^^^^^^^^^^^^^^^^^^^^^ -If you do not want to use conda for managing your python packages, you can also -use the python package manager ``pip`` and install via:: - - $ pip install psyplot-gui - - -Dependencies ------------- -Required dependencies -^^^^^^^^^^^^^^^^^^^^^ -Psyplot has been tested for python 2.7 and >=3.7. Furthermore the package is -built upon multiple other packages, namely - -- psyplot_>=1.4: The underlying framework for data visualization -- qtconsole_>=4.1.1: A package providing the necessary objects for running - an inprocess ipython console in a Qt widget -- fasteners_: Which provides an inprocess lock to communicate to the psyplot - mainwindow -- PyQt5_: Python bindings to the Qt_ software - -Optional dependencies -^^^^^^^^^^^^^^^^^^^^^ -We furthermore recommend to use - -- sphinx_>=1.3.5: To use all features of the interactive documentation access - -.. _conda: https://docs.conda.io/en/latest/ -.. _psyplot: https://psyplot.github.io/psyplot/installing.html -.. _qtconsole: https://qtconsole.readthedocs.io/en/latest/ -.. _fasteners: http://fasteners.readthedocs.org/en/latest/index.html -.. _sphinx: https://www.sphinx-doc.org/en/master/index.html -.. _PyQt5: https://www.riverbankcomputing.com/static/Docs/PyQt5/installation.html -.. _Qt: https://www.qt.io/ +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/installing.html. + You should be redirected within 5 seconds. +

diff --git a/docs/ipython_console.png b/docs/ipython_console.png deleted file mode 100644 index 07e277e..0000000 Binary files a/docs/ipython_console.png and /dev/null differ diff --git a/docs/plugins.rst b/docs/plugins.rst index 8d6da62..794d4c9 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -1,59 +1,11 @@ -.. currentmodule:: psyplot_gui.main - .. _plugins: Plugin configuration ==================== -The psyplot GUI has several built-in plugins, e.g. the -:attr:`~MainWindow.help_explorer` or the :attr:`~MainWindow.fmt_widget`. -External libraries can :ref:`add plugins ` and the user can -disable or enable them with through the :ref:`configuration `. - -.. note:: - - These plugins should only affect the GUI. For other plugins that define - new plotmethods, etc., see the - :ref:`psyplot documentation ` - -.. _plugin-config: - -Plugin configuration --------------------- -You can include and exclude plugins either through the ``include-plugins`` and -``exclude-plugins`` command line option (see :ref:`command-line`), or you -do it permanently with the :attr:`~psyplot_gui.config.rcsetup.rcParams` (see -:ref:`configuration`). - -.. _develop-plugins: - -Developing plugins ------------------- -External libraries insert the GUI as an entry point. In the ``setup.py`` -script of a package, include the following: - -.. code-block:: python - - setup(..., - entry_points={'psyplot_gui': [ - 'widget-name1=widget-module1:widget-class-name1', - 'widget-name2=widget-module2:widget-class-name2', - ...], - }, - ...) - -Here, `widget-name1` is an arbitrary name you want to assign to the widget, -`widget-module1` is the module from where to import the plugin, and -`widget-class-name1` is the name of the class that inherits the -:class:`psyplot_gui.common.DockMixin` class. - -For the :attr:`~MainWindow.help_explorer`, this, for example, would like like - -.. code-block:: python +.. raw:: html - setup(..., - entry_points={'psyplot_gui': [ - 'help=psyplot_gui.help_explorer:HelpExplorer', - ], - }, - ...) +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/plugins.html. + You should be redirected within 5 seconds. +

diff --git a/docs/todos.rst b/docs/todos.rst index 5b6c5dc..4b9106f 100644 --- a/docs/todos.rst +++ b/docs/todos.rst @@ -1,4 +1,12 @@ +.. _todo: + ToDos ===== -.. todolist:: + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/todos.html. + You should be redirected within 5 seconds. +

diff --git a/docs/user-guide.rst b/docs/user-guide.rst new file mode 100644 index 0000000..a18205b --- /dev/null +++ b/docs/user-guide.rst @@ -0,0 +1,11 @@ +.. _user-guide: + +User guide +=============== + +.. raw:: html + +

+ The documentation of psyplot-gui is now hosted at, https://psyplot.github.io/psyplot-gui/user-guide.html. + You should be redirected within 5 seconds. +

diff --git a/docs/world.png b/docs/world.png deleted file mode 100644 index 41ca13a..0000000 Binary files a/docs/world.png and /dev/null differ diff --git a/psyplot_gui/__init__.py b/psyplot_gui/__init__.py deleted file mode 100644 index 9a675a1..0000000 --- a/psyplot_gui/__init__.py +++ /dev/null @@ -1,487 +0,0 @@ -"""Core package for the psyplot graphical user interface""" -import sys -import os -import os.path as osp -import six -import tempfile -import yaml -import socket -import atexit -import fasteners -import time -import pickle -import datetime as dt -import logging -import argparse -import xarray as xr -import psyplot -from psyplot.__main__ import make_plot -from psyplot_gui.config.rcsetup import rcParams -import psyplot_gui.config as config -from itertools import chain -from psyplot.config.rcsetup import get_configdir, safe_list -from psyplot.docstring import docstrings -from psyplot.warning import warn -from psyplot.compat.pycompat import map - - -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions - - -from psyplot.compat.pycompat import get_default_value - -__author__ = "Philipp S. Sommer" -__copyright__ = "Copyright 2016 - 2020, Philipp S. Sommer" -__credits__ = ["Philipp S. Sommer"] -__license__ = "GPL-2.0-only" - -__maintainer__ = "Philipp S. Sommer" -__email__ = "philipp.sommer@hzg.de" - -__status__ = "Production" - -logger = logging.getLogger(__name__) -logger.debug( - "%s: Initializing psyplot gui, version %s", - dt.datetime.now().isoformat(), __version__) -logger.debug("psyplot version: %s", psyplot.__version__) -logger.debug("Logging configuration file: %s", config.logcfg_path) -logger.debug("Configuration file: %s", config.config_path) - - -rcParams.HEADER += "\n\npsyplot gui version: " + __version__ - - -logger = logging.getLogger(__name__) - - -def get_versions(requirements=True): - ret = {'version': __version__} - if requirements: - req = ret['requirements'] = {} - try: - import qtconsole - except Exception: - logger.error('Could not load qtconsole!', exc_info=True) - else: - req['qtconsole'] = qtconsole.__version__ - try: - from psyplot_gui.compat.qtcompat import PYQT_VERSION, QT_VERSION - except Exception: - logger.error('Could not load qt and pyqt!', exc_info=True) - else: - req['qt'] = QT_VERSION - req['pyqt'] = PYQT_VERSION - return ret - - -@docstrings.get_sections(base='psyplot_gui.start_app') -@docstrings.dedent -def start_app(fnames=[], name=[], dims=None, plot_method=None, - output=None, project=None, engine=None, formatoptions=None, - tight=False, encoding=None, enable_post=False, - seaborn_style=None, output_project=None, - concat_dim=get_default_value(xr.open_mfdataset, 'concat_dim'), - chname={}, - backend=False, new_instance=False, rc_file=None, - rc_gui_file=None, include_plugins=rcParams['plugins.include'], - exclude_plugins=rcParams['plugins.exclude'], offline=False, - pwd=None, script=None, command=None, exec_=True, use_all=False, - callback=None, preset=None, - opengl_implementation=None, webengineview=True): - """ - Eventually start the QApplication or only make a plot - - Parameters - ---------- - %(make_plot.parameters)s - backend: None or str - The backend to use. By default, the ``'gui.backend'`` key in the - :attr:`~psyplot_gui.config.rcsetup.rcParams` dictionary is used. - Otherwise it can be None to use the standard matplotlib backend or a - string identifying the backend - new_instance: bool - If True/set and the `output` parameter is not set, a new application is - created - rc_gui_file: str - The path to a yaml configuration file that can be used to update the - :attr:`~psyplot_gui.config.rcsetup.rcParams` - include_plugins: list of str - The plugin widget to include. Can be either None to load all that are - not explicitly excluded by `exclude_plugins` or a list of - plugins to include. List items can be either module names, plugin - names or the module name and widget via ``':'`` - exclude_plugins: list of str - The plugin widgets to exclude. Can be either ``'all'`` to exclude - all plugins or a list like in `include_plugins`. - offline: bool - If True/set, psyplot will be started in offline mode without - intersphinx and remote access for the help explorer - pwd: str - The path to the working directory to use. Note if you do not provide - any `fnames` or `project`, but set the `pwd`, it will switch the - `pwd` of the current GUI. - script: str - The path to a python script that shall be run in the GUI. If the GUI - is already running, the commands will be executed in this GUI. - command: str - Python commands that shall be run in the GUI. If the GUI is already - running, the commands will be executed in this GUI - use_all: bool - If True, use all variables. Note that this is the default if the - `output` is specified and not `name` - exec_: bool - If True, the main loop is entered. - callback: str - A unique identifier for the method that should be used if psyplot is - already running. Set this parameter to None to avoid sending - opengl_implementation: {'software', 'desktop', 'gles', 'automatic'} - OpenGL implementation to pass to Qt. Possible options are - 'software', 'desktop', 'gles' and 'automatic' (which let's PyQt - decide). - webengineview: bool - If True (default), use an HTML help widget. This might not be available - for all builds of PyQt5 under all circumstances. If not set, the - rcParams key ``'help_explorer.use_webengineview'`` is used. - - Returns - ------- - None or :class:`psyplot_gui.main.MainWindow` - ``None`` if `exec_` is True, otherwise the created - :class:`~psyplot_gui.main.MainWindow` instance - """ - if pwd is not None: - os.chdir(pwd) - if script is not None: - script = osp.abspath(script) - - if project is not None and (name != [] or dims is not None): - warn('The `name` and `dims` parameter are ignored if the `project`' - ' parameter is set!') - - # load rcParams from file - if rc_gui_file is not None: - rcParams.load_from_file(rc_gui_file) - - # set plugins - rcParams['plugins.include'] = include_plugins - rcParams['plugins.exclude'] = exclude_plugins - if webengineview is not None: - rcParams['help_explorer.use_webengineview'] = webengineview - - if offline: - rcParams['help_explorer.online'] = False - rcParams['help_explorer.use_intersphinx'] = False - - if dims is not None and not isinstance(dims, dict): - dims = dict(chain(*map(six.iteritems, dims))) - - if output is not None: - return make_plot( - fnames=fnames, name=name, dims=dims, plot_method=plot_method, - output=output, project=project, engine=engine, - formatoptions=formatoptions, tight=tight, rc_file=rc_file, - encoding=encoding, enable_post=enable_post, - seaborn_style=seaborn_style, output_project=output_project, - concat_dim=concat_dim, chname=chname, preset=preset) - if use_all: - name = 'all' - else: - name = safe_list(name) - - if formatoptions is not None: - if not isinstance(formatoptions, dict): - # list of dicts - for fmt in formatoptions[1:]: - formatoptions[0].update(fmt) - formatoptions = formatoptions[0] - if preset is not None: - import psyplot.project as psy - preset_data = psy.Project._load_preset(preset) - else: - preset_data = {} - preset_data.update(formatoptions) - preset = tempfile.NamedTemporaryFile(prefix='psy_', suffix='.yml').name - with open(preset, 'w') as f: - yaml.dump(preset_data, f) - - # make preset path absolute - if preset is not None and not isinstance(preset, dict) and \ - osp.exists(preset): - preset = osp.abspath(preset) - - # Lock file creation - if not new_instance: - lock_file = osp.join(get_configdir(), 'psyplot.lock') - lock = fasteners.InterProcessLock(lock_file) - - # Try to lock psyplot.lock. If it's *possible* to do it, then - # there is no previous instance running and we can start a - # new one. If *not*, then there is an instance already - # running, which is locking that file - lock_created = lock.acquire(False) - else: - lock_created = False - - chname = dict(chname) - - if lock_created: - # Start a new instance - atexit.register(lock.release) - elif not new_instance: - if callback is None: - if fnames or project: - callback = 'new_plot' - elif pwd is not None: - callback = 'change_cwd' - fnames = [pwd] - elif script is not None: - callback = 'run_script' - fnames = [script] - elif command is not None: - callback = 'command' - engine = command - if callback: - send_files_to_psyplot( - callback, fnames, project, engine, plot_method, name, dims, - encoding, enable_post, seaborn_style, concat_dim, chname, - preset) - return - elif new_instance: - rcParams['main.listen_to_port'] = False - if backend is not False: - rcParams['backend'] = backend - from psyplot_gui.main import MainWindow - fnames = _get_abs_names(fnames) - if project is not None: - project = _get_abs_names([project])[0] - if exec_: - from psyplot_gui.compat.qtcompat import QApplication - app = QApplication(sys.argv) - - _set_opengl_implementation(opengl_implementation) - - if isinstance(new_instance, MainWindow): - mainwindow = new_instance - else: - mainwindow = MainWindow.run(fnames, project, engine, plot_method, name, - dims, encoding, enable_post, seaborn_style, - concat_dim, chname, preset) - if script is not None: - mainwindow.console.run_script_in_shell(script) - if command is not None: - mainwindow.console.run_command_in_shell(command) - if exec_: - sys.excepthook = mainwindow.excepthook - sys.exit(app.exec_()) - else: - return mainwindow - - -def send_files_to_psyplot(callback, fnames, project, *args): - """ - Simple socket client used to send the args passed to the psyplot - executable to an already running instance. - - This function has to most parts been taken from spyder - """ - port = rcParams['main.open_files_port'] - - # Wait ~50 secs for the server to be up - # Taken from http://stackoverflow.com/a/4766598/438386 - for _x in range(200): - fnames = _get_abs_names(fnames) - if project is not None: - project = _get_abs_names([project])[0] - try: - client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, - socket.IPPROTO_TCP) - client.connect(("127.0.0.1", port)) - client.send(pickle.dumps([callback, fnames, project] + list(args))) - client.close() - except socket.error: - time.sleep(0.25) - continue - break - - -def _get_abs_names(fnames): - """Return the absolute paths of the given filenames""" - if fnames is None: - return - for i, fname in enumerate(fnames): - if fname: - fnames[i] = ','.join(map(osp.abspath, fname.split(','))) - return fnames - - -def get_parser(create=True): - """Return a parser to make that can be used to make plots or open files - from the command line - - Returns - ------- - psyplot.parser.FuncArgParser - The :class:`argparse.ArgumentParser` instance - - See Also - -------- - psyplot.main.get_parser - psyplot.parser.FuncArgParser - psyplot.main.main""" - from psyplot.__main__ import get_parser - parser = get_parser(create=False) - - parser.setup_args(start_app) - - gui_grp = parser.add_argument_group( - 'Gui options', - 'Options specific to the graphical user interface') - - parser.update_arg( - 'backend', short='b', const=None, nargs='?', metavar='backend', - help=""" - The backend to use. By default, the ``'gui.backend'`` key in the - :attr:`~psyplot_gui.config.rcsetup.rcParams` dictionary is used. If - used without options, the default matplotlib backend is used.""", - group=gui_grp) - - parser.update_arg('new_instance', short='ni', group=gui_grp) - - parser.update_arg('rc_gui_file', short='rc-gui', group=gui_grp) - parser.pop_key('rc_gui_file', 'metavar') - parser.update_arg('include_plugins', short='inc', group=gui_grp, - default=rcParams['plugins.include']) - parser.append2help('include_plugins', '. Default: %(default)s') - parser.update_arg('exclude_plugins', short='exc', group=gui_grp, - default=rcParams['plugins.exclude']) - parser.append2help('exclude_plugins', '. Default: %(default)s') - - parser.update_arg('offline', group=gui_grp) - parser.update_arg('pwd', group=gui_grp) - parser.update_arg('script', short='s', group=gui_grp) - parser.update_arg('command', short='c', group=gui_grp) - - parser.update_arg('opengl_implementation', group=gui_grp, short='opengl', - choices=['software', 'desktop', 'gles', 'automatic']) - - # add an action to display the GUI plugins - info_grp = parser.unfinished_arguments['list_plugins'].get('group') - parser.update_arg( - 'list_gui_plugins', short='lgp', long='list-gui-plugins', - action=ListGuiPluginsAction, if_existent=False, - help=("Print the names of the GUI plugins and exit. Note that the " - "displayed plugins are not affected by the `include-plugins` " - "and `exclude-plugins` options")) - if info_grp is not None: - parser.unfinished_arguments['list_gui_plugins']['group'] = info_grp - - parser.pop_key('offline', 'short') - - parser.append2help('output_project', - '. This option has only an effect if the `output` ' - ' option is set.') - - parser.update_arg('use_all', short='a') - - parser.pop_arg('exec_') - parser.pop_arg('callback') - - parser.pop_key('webengineview', 'short') - parser.update_arg('webengineview', default=None, action='store_true', - group=gui_grp) - - parser.unfinished_arguments['no-webengineview'] = dict( - long='no-webengineview', default=None, action='store_false', - dest='webengineview', - help="Do not use HTML rendering.", - group=gui_grp) - - if psyplot.__version__ < '1.0': - parser.set_main(start_app) - - parser.epilog += """ - -If you omit the ``'-o'`` option, the file is opened in the graphical user -interface and if you run:: - - $ psyplot -pwd . - -It will switch the directory of the already running GUI (if existent) to the -current working directory in your terminal. Additionally,:: - - $ psyplot -s myscript.py - -will run the file ``'myscript.py'`` in the GUI and:: - - $ psyplot -c 'print("Hello World!")' - -will execute ``print("Hello World")`` in the GUI. The output, of the `-s` and -`-c` options, will, however, be shown in the terminal.""" - - if create: - parser.create_arguments() - - return parser - - -#: A boolean variable to check if the GUI is tested. This is set automatically -#: true on CI services -UNIT_TESTING = os.getenv('CI') - - -#: Disable the default for the ListGuiPluginsAction on RTD, because it looks -#: better in the docs -_on_rtd = os.environ.get('READTHEDOCS', None) == 'True' - - -class ListGuiPluginsAction(argparse.Action): - - def __init__(self, option_strings, dest=argparse.SUPPRESS, nargs=None, - default=argparse.SUPPRESS, **kwargs): - if nargs is not None: - raise ValueError("nargs not allowed") - if not _on_rtd: - kwargs['default'] = default - super(ListGuiPluginsAction, self).__init__( - option_strings, nargs=0, dest=dest, - **kwargs) - - def __call__(self, parser, namespace, values, option_string=None): - import yaml - if not rcParams._plugins: - list(rcParams._load_plugin_entrypoints()) - print(yaml.dump(rcParams._plugins, default_flow_style=False)) - sys.exit(0) - - -def _set_opengl_implementation(option): - """ - Set the OpenGL implementation - - This function has been taken from spyder - (see https://github.com/spyder-ide/spyder/pull/7859) - - See issue https://github.com/spyder-ide/spyder/issues/7447 for the details. - """ - try: - from PyQt5.QtQuick import QQuickWindow, QSGRendererInterface - except Exception: - QQuickWindow = QSGRendererInterface = None - from PyQt5.QtCore import QCoreApplication, Qt - if option is None: - option = rcParams['main.opengl'] - if option == 'software': - QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL) - if QQuickWindow is not None: - QQuickWindow.setSceneGraphBackend(QSGRendererInterface.Software) - elif option == 'desktop': - QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL) - if QQuickWindow is not None: - QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL) - elif option == 'gles': - QCoreApplication.setAttribute(Qt.AA_UseOpenGLES) - if QQuickWindow is not None: - QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL) diff --git a/psyplot_gui/_version.py b/psyplot_gui/_version.py deleted file mode 100644 index 2f8671c..0000000 --- a/psyplot_gui/_version.py +++ /dev/null @@ -1,520 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "psyplot-gui-" - cfg.versionfile_source = "psyplot_gui/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/psyplot_gui/backend.py b/psyplot_gui/backend.py deleted file mode 100644 index e1f4ee2..0000000 --- a/psyplot_gui/backend.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Matplotlib backend to include matplotlib figures as dockwidgets in the -psyplot gui - -This backend is based upon matplotlibs qt4agg and qt5agg backends.""" -from psyplot_gui.compat.qtcompat import ( - QDockWidget, Qt, QWidget, QVBoxLayout, with_qt5) -from psyplot_gui.common import DockMixin -from matplotlib.backend_bases import FigureManagerBase -from matplotlib.figure import Figure -if with_qt5: - from matplotlib.backends.backend_qt5agg import ( - show, FigureManagerQT, FigureCanvasQTAgg) -else: - from matplotlib.backends.backend_qt4agg import ( - show, FigureManagerQT, FigureCanvasQTAgg) - - -class FiguresDock(QDockWidget): - """Reimplemented QDockWidget to remove the dock widget when closed - """ - - def close(self, *args, **kwargs): - """ - Reimplemented to remove the dock widget from the mainwindow when closed - """ - from psyplot_gui.main import mainwindow - try: - mainwindow.figures.remove(self) - except Exception: - pass - try: - mainwindow.removeDockWidget(self) - except Exception: - pass - return super(FiguresDock, self).close(*args, **kwargs) - - -class FigureWidget(DockMixin, QWidget): - """A simple container for figures in the psyplot backend""" - - dock_cls = FiguresDock - - -def new_figure_manager(num, *args, **kwargs): - """ - Create a new figure manager instance - """ - FigureClass = kwargs.pop('FigureClass', Figure) - thisFig = FigureClass(*args, **kwargs) - return new_figure_manager_given_figure(num, thisFig) - - -def new_figure_manager_given_figure(num, figure): - """ - Create a new figure manager instance for the given figure. - """ - canvas = PsyplotCanvas(figure) - return PsyplotCanvasManager(canvas, num) - - -class PsyplotCanvasManager(FigureManagerQT): - """The canvas manager for the psyplot backend interacting with the - mainwindow of the psyplot gui""" - - toolbar = None - - def __init__(self, canvas, num): - from psyplot_gui.main import mainwindow - self.main = mainwindow - if mainwindow is None: - return super(PsyplotCanvasManager, self).__init__(canvas, num) - parent_widget = FigureWidget() - parent_widget.vbox = vbox = QVBoxLayout() - self.window = dock = parent_widget.to_dock( - mainwindow, title="Figure %d" % num, position=Qt.TopDockWidgetArea, - docktype=None) - if mainwindow.figures: - mainwindow.tabifyDockWidget(mainwindow.figures[-1], dock) - mainwindow.figures.append(dock) - FigureManagerBase.__init__(self, canvas, num) - self.canvas = canvas - - self.window.setWindowTitle("Figure %d" % num) - - self.toolbar = self._get_toolbar(canvas, parent_widget) - - # add text label to status bar - self.statusbar_label = mainwindow.figures_label - - if self.toolbar is not None: - vbox.addWidget(self.toolbar) - self.toolbar.message.connect(self.statusbar_label.setText) - - vbox.addWidget(canvas) - parent_widget.setLayout(vbox) - self.parent_widget = parent_widget - - # Give the keyboard focus to the figure instead of the - # manager; StrongFocus accepts both tab and click to focus and - # will enable the canvas to process event w/o clicking. - # ClickFocus only takes the focus is the window has been - # clicked - # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or - # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum - self.canvas.setFocusPolicy(Qt.StrongFocus) - self.canvas.setFocus() - self.window._destroying = False - - self.main.show() - - def notify_axes_change(fig): - # This will be called whenever the current axes is changed - if self.toolbar is not None: - self.toolbar.update() - self.canvas.figure.add_axobserver(notify_axes_change) - - def statusBar(self, *args, **kwargs): - if self.main is None: - return super(PsyplotCanvasManager, self).statusBar(*args, **kwargs) - return self.main.statusBar(*args, **kwargs) - - def resize(self, width, height): - self.window.resize(width, height + self.toolbar.sizeHint().height()) - - -class PsyplotCanvas(FigureCanvasQTAgg): - """The canvas class with reimplemented resizing""" - - def resizeEvent(self, event): - """Reimplemented to make sure that the figure is only resized for - events with height and width greater 0""" - if event.size().width() > 0 and event.size().height() > 0: - super(PsyplotCanvas, self).resizeEvent(event) - - -FigureManager = PsyplotCanvasManager -FigureCanvas = PsyplotCanvas diff --git a/psyplot_gui/common.py b/psyplot_gui/common.py deleted file mode 100644 index 62221d8..0000000 --- a/psyplot_gui/common.py +++ /dev/null @@ -1,326 +0,0 @@ -"""Common functions used for the psyplot gui""" -import sys -import six -import inspect -import traceback as tb -from functools import partial -import os.path as osp -from psyplot_gui.compat.qtcompat import ( - QDockWidget, QRegExpValidator, QtCore, QErrorMessage, QDesktopWidget, - QToolButton, QInputDialog, QIcon, QAction) -import logging - -if six.PY2: - try: - import CStringIO as io - except ImportError: - import StringIO as io -else: - import io - - -def is_running_tests(): - """Check if there are any GUI tests running - - This function returns the :attr:`psyplot_gui.UNIT_TESTING` variable""" - import psyplot_gui - return psyplot_gui.UNIT_TESTING - - -def get_module_path(modname): - """Return module `modname` base path""" - - return osp.abspath(osp.dirname(sys.modules[modname].__file__)) - - -def get_icon(name): - """Get the path to an icon in the icons directory""" - return osp.join(get_module_path('psyplot_gui'), 'icons', name) - - -class DockMixin(object): - """A mixin class to define psyplot_gui plugins - - Notes - ----- - Each external plugin should set the :attr:`dock_position` and the - :attr:`title` attribute! - """ - - _set_central_action = _view_action = None - - #: The position of the plugin - dock_position = None - - #: The title of the plugin - title = None - - #: The class to use for the DockWidget - dock_cls = QDockWidget - - #: The config page for this widget. Should inherit the - #: :class:`psyplot_gui.preferences.ConfigPage` widget - config_page = None - - #: Boolean that is True if the dock widget should be hidden automatically - #: after startup - hidden = False - - #: The instance of :class:`QDockWidget` of this plugin - dock = None - - @property - def is_shown(self): - """Boolean that is True, if the dock widget is shown""" - return (self.dock is not None and - self.dock.toggleViewAction().isChecked()) - - def to_dock(self, main, title=None, position=None, docktype='pane', *args, - **kwargs): - if title is None: - title = self.title - if title is None: - raise ValueError( - "No title specified for the %s widget" % (self)) - if position is None: - position = self.dock_position - if position is None: - raise ValueError("No position specified for the %s widget (%s)" % ( - title, self)) - self.title = title - self.dock_position = position - if self.dock is None: - self.dock = self.dock_cls(title, main) - self.dock.setWidget(self) - main.dockwidgets.append(self.dock) - self.create_central_widget_action(main) - self.create_view_action(main, docktype) - self.position_dock(main, *args, **kwargs) - config_page = self.config_page - if config_page is not None: - main.config_pages.append(config_page) - return self.dock - - def position_dock(self, main, *args, **kwargs): - """Set the position of the dock widget - - This method places the plugin widget at the desired dock position - (by default, indicated with the :attr:`dock_position` attribute) - - Parameters - ---------- - main: psyplot_gui.main.Mainwindow - The main window where the dock is added""" - main.addDockWidget(self.dock_position, self.dock, *args, **kwargs) - - - def show_plugin(self): - """Show the plugin widget""" - a = self.dock.toggleViewAction() - if not a.isChecked(): - a.trigger() - - def hide_plugin(self): - """Hide the plugin widget""" - a = self.dock.toggleViewAction() - if a.isChecked(): - a.trigger() - - def show_status_message(self, msg): - """Show a status message""" - try: - self.dock.parent().plugin_label.setText(msg) - except AttributeError: - pass - - def create_central_widget_action(self, main): - """Setup the action to make this plugin the central widget""" - if self._set_central_action is None: - menu = main.central_widgets_menu - group = main.central_widgets_actions - self._set_central_action = action = QAction(self.title, main) - action.setCheckable(True) - action.triggered.connect(partial(main.set_central_widget, self)) - menu.addAction(action) - group.addAction(action) - return self._set_central_action - - def create_view_action(self, main, docktype='pane'): - if self._view_action is None: - self._view_action = action = self.dock.toggleViewAction() - if docktype == 'pane': - main.panes_menu.addAction(action) - elif docktype == 'df': - main.dataframe_menu.addAction(action) - return self._view_action - - def remove_plugin(self): - """Remove this plugin and close it""" - mainwindow = self.dock.parent() if self.dock else self.parent() - key = next((key for key, w in mainwindow.plugins.items() - if w is self), None) - if mainwindow.centralWidget() is self: - mainwindow.set_central_widget( - mainwindow.__class__.central_widget_key) - if self._view_action is not None: - mainwindow.panes_menu.removeAction(self._view_action) - mainwindow.dataframe_menu.removeAction(self._view_action) - if self._set_central_action is not None: - mainwindow.central_widgets_menu.removeAction( - self._set_central_action) - if key is not None: - del mainwindow.plugins[key] - if self.dock is not None: - mainwindow.removeDockWidget(self.dock) - self.dock.close() - self.close() - - -class LoadFromConsoleButton(QToolButton): - """A toolbutton to load an object from the console""" - - #: The signal that is emitted when an object has been loaded. The first - #: argument is the object name, the second the object itself - object_loaded = QtCore.pyqtSignal(str, object) - - @property - def instances2check_str(self): - return ', '.join('%s.%s' % (cls.__module__, cls.__name__) - for cls in self._instances2check) - - @property - def potential_object_names(self): - from ipykernel.inprocess.ipkernel import InProcessInteractiveShell - shell = InProcessInteractiveShell.instance() - return sorted(name for name, obj in shell.user_global_ns.items() - if not name.startswith('_') and self.check(obj)) - - def __init__(self, instances=None, *args, **kwargs): - """ - Parameters - ---------- - instances: class or tuple of classes - The classes that should be used for an instance check - """ - super(LoadFromConsoleButton, self).__init__(*args, **kwargs) - self.setIcon(QIcon(get_icon('console-go.png'))) - if instances is not None and inspect.isclass(instances): - instances = (instances, ) - self._instances2check = instances - self.error_msg = PyErrorMessage(self) - self.clicked.connect(partial(self.get_from_shell, None)) - - def check(self, obj): - return True if not self._instances2check else isinstance( - obj, self._instances2check) - - def get_from_shell(self, oname=None): - """Open an input dialog, receive an object and emit the - :attr:`object_loaded` signal""" - if oname is None: - oname, ok = QInputDialog.getItem( - self, 'Select variable', - 'Select a variable to import from the console', - self.potential_object_names) - if not ok: - return - if self.check(oname) and (self._instances2check or - not isinstance(oname, six.string_types)): - obj = oname - oname = 'object' - else: - found, obj = self.get_obj(oname.strip()) - if found: - if not self.check(obj): - self.error_msg.showMessage( - 'Object must be an instance of %r, not %r' % ( - self.instances2check_str, - '%s.%s' % (type(obj).__module__, - type(obj).__name__))) - return - else: - if not oname.strip(): - msg = 'The variable name must not be empty!' - else: - msg = 'Could not find object ' + oname - self.error_msg.showMessage(msg) - return - self.object_loaded.emit(oname, obj) - - def get_obj(self, oname): - """Load an object from the current shell""" - from psyplot_gui.main import mainwindow - return mainwindow.console.get_obj(oname) - - -class ListValidator(QRegExpValidator): - """A validator class to validate that a string consists of strings in a - list of strings""" - - def __init__(self, valid, sep=',', *args, **kwargs): - """ - Parameters - ---------- - valid: list of str - The possible choices - sep: str, optional - The separation pattern - ``*args,**kwargs`` - Determined by PyQt5.QtGui.QValidator - """ - patt = QtCore.QRegExp('^((%s)(;;)?)+$' % '|'.join(valid)) - super(QRegExpValidator, self).__init__(patt, *args, **kwargs) - - -class PyErrorMessage(QErrorMessage): - """Widget designed to display python errors via the :meth:`showTraceback` - method""" - - def showTraceback(self, header=None): - - if is_running_tests(): - raise - - s = io.StringIO() - tb.print_exc(file=s) - last_tb = '

' + '
'.join(s.getvalue().splitlines()) + \ - '

' - header = header + '\n' if header else '' - self.showMessage(header + last_tb) - available_width = QDesktopWidget().availableGeometry().width() / 3. - available_height = QDesktopWidget().availableGeometry().height() / 3. - width = self.sizeHint().width() - height = self.sizeHint().height() - # The message window should cover at least one third of the screen - self.resize(max(available_width, width), max(available_height, height)) - - def excepthook(self, type, value, traceback): - s = io.StringIO() - tb.print_exception(type, value, traceback, file=s) - last_tb = '

' + '
'.join(s.getvalue().splitlines()) + \ - '

' - header = value.message if six.PY2 else str(value) - self.showMessage(header + '\n' + last_tb) - available_width = QDesktopWidget().availableGeometry().width() / 3. - available_height = QDesktopWidget().availableGeometry().height() / 3. - width = self.sizeHint().width() - height = self.sizeHint().height() - # The message window should cover at least one third of the screen - self.resize(max(available_width, width), max(available_height, height)) - - -class StreamToLogger(object): - """ - Fake file-like stream object that redirects writes to a logger instance. - """ - def __init__(self, logger, log_level=logging.INFO): - self.logger = logger - self.log_level = log_level - self.linebuf = '' - - def write(self, buf): - for line in buf.rstrip().splitlines(): - self.logger.log(self.log_level, line.rstrip()) - - def flush(self): - pass diff --git a/psyplot_gui/compat/__init__.py b/psyplot_gui/compat/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/psyplot_gui/compat/qtcompat.py b/psyplot_gui/compat/qtcompat.py deleted file mode 100644 index 1d8f0a6..0000000 --- a/psyplot_gui/compat/qtcompat.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Compatibility module for the different versions of PyQt""" - -# make sure that the right pyqt version suitable for the IPython console is -# loaded -import six -import sys -from psyplot_gui.config.rcsetup import rcParams - -try: - from qtconsole.rich_jupyter_widget import RichJupyterWidget -except ImportError: - pass -try: - import PyQt5 -except ImportError: - from PyQt4.QtGui import ( - QMainWindow, QDockWidget, QToolBox, QApplication, QListWidget, - QListWidgetItem, QHBoxLayout, QVBoxLayout, QAbstractItemView, - QWidget, QPushButton, QFrame, QSplitter, QTreeWidget, QTreeWidgetItem, - QSizePolicy, QLabel, QLineEdit, QIcon, QToolButton, - QComboBox as OrigQComboBox, - QKeyEvent, QSortFilterProxyModel, QStandardItem, QStandardItemModel, - QCompleter, QStatusBar, QPlainTextEdit, QTextEdit, QToolBar, QMenu, - QAction, QTextCursor, QMessageBox, QCheckBox, QFileDialog, - QListView, QDesktopWidget, QValidator, QStyledItemDelegate, - QTableWidget, QTableWidgetItem, QRegExpValidator, QGridLayout, - QIntValidator, QErrorMessage, QInputDialog, QTabWidget, - QDoubleValidator, QGraphicsScene, QGraphicsRectItem, QGraphicsView, - QKeySequence, QStyleOptionViewItem, QDialog, QDialogButtonBox, - QStackedWidget, QScrollArea, QTableView, QHeaderView, QActionGroup) - from PyQt4 import QtCore - from PyQt4.QtCore import Qt - from PyQt4.QtWebKit import QWebView as QWebEngineView - from PyQt4.QtTest import QTest - from PyQt4 import QtGui - from PyQt4.Qt import PYQT_VERSION_STR as PYQT_VERSION - from PyQt4.Qt import QT_VERSION_STR as QT_VERSION - with_qt5 = False - QSignalSpy = None - - try: - from PyQt4.QtCore import QString, QByteArray - except ImportError: - def isstring(s): - return isinstance(s, six.string_types) - else: - def isstring(s): - return isinstance( - s, tuple(list(six.string_types) + [QString, QByteArray])) - - class QComboBox(OrigQComboBox): - - currentTextChanged = QtCore.pyqtSignal(str) - - def __init__(self, *args, **kwargs): - OrigQComboBox.__init__(self, *args, **kwargs) - self.currentIndexChanged.connect(self._emit_currentTextChanged) - - def _emit_currentTextChanged(self, i): - self.currentTextChanged.emit(self.currentText()) - - def setCurrentText(self, s): - idx = self.findText(s) - if idx == -1: - self.addItem(s) - idx = self.findText(s) - self.setCurrentIndex(idx) - -else: - from PyQt5.QtWidgets import ( - QMainWindow, QDockWidget, QToolBox, QApplication, QListWidget, - QListWidgetItem, QHBoxLayout, QVBoxLayout, QAbstractItemView, - QWidget, QPushButton, QFrame, QSplitter, QTreeWidget, QTreeWidgetItem, - QSizePolicy, QLabel, QLineEdit, QToolButton, QComboBox, QCompleter, - QStatusBar, QPlainTextEdit, QTextEdit, QToolBar, QMenu, - QAction, QMessageBox, QCheckBox, QFileDialog, QListView, - QDesktopWidget, QStyledItemDelegate, QTableWidget, QTableWidgetItem, - QGridLayout, QErrorMessage, QInputDialog, QTabWidget, - QGraphicsScene, QGraphicsRectItem, QGraphicsView, QStyleOptionViewItem, - QDialog, QDialogButtonBox, QStackedWidget, QScrollArea, - QTableView, QHeaderView, QActionGroup) - from PyQt5.QtGui import ( - QIcon, QKeyEvent, QStandardItem, QStandardItemModel, QTextCursor, - QValidator, QRegExpValidator, QIntValidator, QDoubleValidator, - QKeySequence) - from PyQt5 import QtCore - from PyQt5.QtCore import Qt, QSortFilterProxyModel - if rcParams['help_explorer.use_webengineview']: - try: - from PyQt5.QtWebEngineWidgets import QWebEngineView - except ImportError: - from PyQt5.QtWebKitWidgets import QWebView as QWebEngineView - else: - QWebEngineView = None - from PyQt5.QtTest import QTest, QSignalSpy - from PyQt5 import QtGui - from PyQt5.Qt import PYQT_VERSION_STR as PYQT_VERSION - from PyQt5.Qt import QT_VERSION_STR as QT_VERSION - with_qt5 = True - - def isstring(s): - return isinstance(s, six.string_types) - - -def asstring(s): - return six.text_type(s) - - -if sys.platform == 'darwin': - # make sure to register the open file event - OrigQApplication = QApplication - - class QApplication(OrigQApplication): - """Reimplemented QApplication with open file event""" - - def event(self, event): - from psyplot_gui.config.rcsetup import rcParams - - if (rcParams['main.listen_to_port'] and - event.type() == QtCore.QEvent.FileOpen): - from psyplot_gui.main import mainwindow - if mainwindow is not None: - opened = mainwindow.open_files([event.file()]) - if opened: - return True - return super(QApplication, self).event(event) diff --git a/psyplot_gui/config/__init__.py b/psyplot_gui/config/__init__.py deleted file mode 100755 index cd8ee78..0000000 --- a/psyplot_gui/config/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Configuration module of the psyplot package - -This module contains the module for managing rc parameters and the logging. -Default parameters are defined in the :data:`rcsetup.defaultParams` -dictionary, however you can set up your own configuration in a yaml file (see -:func:`psyplot.load_rc_from_file`)""" -import os.path as osp -from psyplot.config.logsetup import setup_logging -from psyplot.config.rcsetup import psyplot_fname - -#: :class:`str`. Path to the yaml logging configuration file -logcfg_path = setup_logging( - default_path=osp.join(osp.dirname(__file__), 'logging.yml'), - env_key='LOG_PSYPLOTGUI') - - -#: class:`str` or ``None``. Path to the yaml configuration file (if found). -#: See :func:`psyplot.config.rcsetup.psyplot_fname` for further -#: information -config_path = psyplot_fname(env_key='PSYPLOTGUIRC', - fname='psyplotguirc.yaml') diff --git a/psyplot_gui/config/logging.yml b/psyplot_gui/config/logging.yml deleted file mode 100755 index dd94e53..0000000 --- a/psyplot_gui/config/logging.yml +++ /dev/null @@ -1,75 +0,0 @@ ---- -# logging settings for the nc2map module - -version: 1 - -disable_existing_loggers: False - -formatters: - - simple: - - format: "[%(name)s] - %(levelname)s - %(message)s" - - level_message: - - format: "%(levelname)s: %(message)s" - - full: - format: "%(asctime)s - [%(name)s.%(funcName)s] - %(levelname)s - %(message)s" - - -handlers: - - console: - - class: logging.StreamHandler - - level: INFO - - formatter: simple - - stream: ext://sys.stdout - - warning_console: - - class: logging.StreamHandler - - level: INFO - - formatter: level_message - - stream: ext://sys.stdout - - - debug_file_handler: - - class: logging.handlers.RotatingFileHandler - - mode: w - - level: DEBUG - - formatter: full - - filename: ~/.debug_psyplot.log - - maxBytes: 10485760 # 10MB - - backupCount: 5 - - encoding: utf8 - - delay: True - -loggers: - - psyplot_gui: - - handlers: [console, debug_file_handler] - - propagate: False - - level: INFO - -... \ No newline at end of file diff --git a/psyplot_gui/config/logging_debug.yml b/psyplot_gui/config/logging_debug.yml deleted file mode 100755 index 5832c27..0000000 --- a/psyplot_gui/config/logging_debug.yml +++ /dev/null @@ -1,74 +0,0 @@ ---- -# debug logging settings (sets the level of the nc2map logger to DEBUG) - -version: 1 - -disable_existing_loggers: False - -formatters: - - simple: - - format: "[%(name)s] - %(levelname)s - %(message)s" - - level_message: - - format: "%(levelname)s: %(message)s" - - full: - format: "%(asctime)s - [%(name)s.%(funcName)s] - %(levelname)s - %(message)s" - - -handlers: - - console: - - class: logging.StreamHandler - - level: INFO - - formatter: simple - - stream: ext://sys.stdout - - warning_console: - - class: logging.StreamHandler - - level: INFO - - formatter: level_message - - stream: ext://sys.stdout - - - debug_file_handler: - - class: logging.handlers.RotatingFileHandler - - mode: w - - level: DEBUG - - formatter: full - - filename: ~/.debug_psyplot.log - - maxBytes: 10485760 # 10MB - - backupCount: 5 - - encoding: utf8 - - delay: True - -loggers: - - psyplot_gui: - - handlers: [console, debug_file_handler] - - propagate: False - - level: DEBUG -... \ No newline at end of file diff --git a/psyplot_gui/config/rcsetup.py b/psyplot_gui/config/rcsetup.py deleted file mode 100755 index 8f5bbbd..0000000 --- a/psyplot_gui/config/rcsetup.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Default management of the psyplot_gui package - -This module defines the necessary configuration parts for the psyplot gui""" -import six -import logging -from psyplot.config.rcsetup import ( - RcParams, psyplot_fname, validate_bool_maybe_none, validate_stringlist) -from matplotlib.rcsetup import validate_int, validate_bool - - -def try_and_error(*funcs): - """Apply multiple validation functions - - Parameters - ---------- - ``*funcs`` - Validation functions to test - - Returns - ------- - function""" - def validate(value): - exc = None - for func in funcs: - try: - return func(value) - except (ValueError, TypeError) as e: - exc = e - raise exc - return validate - - -# ----------------------------------------------------------------------------- -# ------------------------- validation functions ------------------------------ -# ----------------------------------------------------------------------------- - - -def validate_str(s): - """Validate a string - - Parameters - ---------- - s: str - - Returns - ------- - str - - Raises - ------ - ValueError""" - if not isinstance(s, six.string_types): - raise ValueError("Did not found string!") - return six.text_type(s) - - -def validate_none(b): - """Validate that None is given - - Parameters - ---------- - b: {None, 'none'} - None or string (the case is ignored) - - Returns - ------- - None - - Raises - ------ - ValueError""" - if isinstance(b, six.string_types): - b = b.lower() - if b is None or b == 'none': - return None - else: - raise ValueError('Could not convert "%s" to None' % b) - - -def validate_all(v): - """Test if ``v == 'all'``""" - if v != 'all': - raise ValueError("The value must be 'all'") - return six.text_type(v) - - -class GuiRcParams(RcParams): - """RcParams for the psyplot-gui package.""" - - HEADER = RcParams.HEADER.replace( - 'psyplotrc.yml', 'psyplotguirc.yml').replace( - 'PSYPLOTRC', 'psyplotrc.yml') - - def load_from_file(self, fname=None): - """ - Update rcParams from user-defined settings - - This function updates the instance with what is found in `fname` - - Parameters - ---------- - fname: str - Path to the yaml configuration file. Possible keys of the - dictionary are defined by :data:`config.rcsetup.defaultParams`. - If None, the :func:`config.rcsetup.psyplot_fname` function is used. - - See Also - -------- - dump_to_file, psyplot_fname""" - fname = fname or psyplot_fname(env_key='PSYPLOTGUIRC', - fname='psyplotguirc.yml') - if fname: - super(GuiRcParams, self).load_from_file(fname) - - def _load_plugin_entrypoints(self): - """Load the modules for the psyplot plugins - - Yields - ------ - pkg_resources.EntryPoint - The entry point for the psyplot plugin module""" - from pkg_resources import iter_entry_points - inc = self['plugins.include'] - exc = self['plugins.exclude'] - logger = logging.getLogger(__name__) - self._plugins = self._plugins or [] - for ep in iter_entry_points('psyplot_gui'): - plugin_name = '%s:%s:%s' % (ep.module_name, ':'.join(ep.attrs), - ep.name) - # check if the user wants to explicitly this plugin - include_user = None - if inc: - include_user = ( - ep.module_name in inc or ep.name in inc or - '%s:%s' % (ep.module_name, ':'.join(ep.attrs)) in inc) - if include_user is None and exc == 'all': - include_user = False - elif include_user is None: - # check for exclude - include_user = not ( - ep.module_name in exc or ep.name in exc or - '%s:%s' % (ep.module_name, ':'.join(ep.attrs)) in exc) - if not include_user: - logger.debug('Skipping plugin %s: Excluded by user', - plugin_name) - else: - logger.debug('Loading plugin %s', plugin_name) - self._plugins.append(str(ep)) - yield ep - - def load_plugins(self, *args, **kwargs): - """ - Load the plugins for the psyplot_gui MainWindow - - Returns - ------- - dict - A mapping from entry point name to the imported widget class - - Notes - ----- - ``*args`` and ``**kwargs`` are ignored - """ - def format_ep(ep): - return '%s:%s:%s' % (ep.module_name, ':'.join(ep.attrs), ep.name) - return { - format_ep(ep): ep.load() for ep in self._load_plugin_entrypoints()} - - -#: :class:`dict` with default values and validation functions -defaultParams = { - - # gui settings - 'backend': [ - 'psyplot', - try_and_error(validate_str, validate_none), - 'Backend to use when using the graphical user interface. The current ' - 'backend is used and no changes are made. Note that it is usually not ' - 'possible to change the backend after importing the psyplot.project ' - 'module. The default backend embeds the figures into the '], - 'help_explorer.use_webengineview': [ - True, validate_bool, - "Enable the PyQt5.QtWebEngineWidgets.QWebEngineView which might not " - "work under certain circumstances."], - 'help_explorer.use_intersphinx': [ - None, validate_bool_maybe_none, - 'Use the intersphinx extension and link to the online documentations ' - 'of matplotlib, pyplot, psyplot, numpy, etc. when converting rst ' - 'docstrings. The inventories are loaded when the first object is ' - 'documented. If None, intersphinx is only used when ' - '`help_explorer.online` is True and you are not using windows'], - 'help_explorer.render_docs_parallel': [ - True, validate_bool, - 'Boolean whether the html docs are rendered in a separate process'], - 'help_explorer.online': [ - None, validate_bool_maybe_none, - 'Switch that controls whether the online functions of the help ' - 'explorer shall be enabled. False implies that ' - 'help_explorer.use_intersphinx is set to False'], - 'console.start_channels': [ - True, validate_bool, - 'Start the different channels of the KernelClient'], - 'console.connect_to_help': [ - True, validate_bool, - 'Whether the console shall be connected to the help_explorer or not'], - 'console.auto_set_mp': [ - True, validate_bool, - "If True, then the 'mp' variable in the console is automatically set " - "when the current main project changes"], - 'console.auto_set_sp': [ - True, validate_bool, - "If True, then the 'sp' variable in the console is automatically set " - "when the current sub project changes"], - 'main.open_files_port': [ - 30124, validate_int, "The port number used when new files are opened"], - 'main.listen_to_port': [ - True, validate_bool, - "If True and the psyplot gui is already running, new files are opened " - "in that gui"], - 'main.opengl': [ - 'software', validate_str, - "The opengl implementation to use. Should be one of 'software', " - "'desktop', 'gles' or 'automatic'."], - 'content.load_tooltips': [ - True, validate_bool, - "If True, a lazy load is performed on the arrays and data sets and " - "their string representation is displayed as tool tip. This part of " - "the data into memory. It is recommended to set this to False for " - "remote data."], - 'fmt.sort_by_key': [ - True, validate_bool, - "If True, the formatoptions in the Formatoptions widget are sorted by " - "their formatoption key rather than by their name."], - 'plugins.include': [ - None, try_and_error(validate_none, validate_stringlist), - "The plugins to load. Can be either None to load all that are not " - "explicitly excluded by the 'plugins.exclude' key or a list of " - "plugins to include. List items can be either module names, plugin " - "names or the module name and widget via ':'"], - 'plugins.exclude': [ - [], try_and_error(validate_all, validate_stringlist), - "The plugins to exclude from loading. Can be either 'all' to exclude " - "all plugins or a list like in 'plugins.include'."], - } - -#: :class:`~psyplot.config.rcsetup.RcParams` instance that stores default -#: formatoptions and configuration settings. -rcParams = GuiRcParams(defaultParams=defaultParams) -rcParams.update({key: val[0] for key, val in defaultParams.items()}) -rcParams.load_from_file() diff --git a/psyplot_gui/console.py b/psyplot_gui/console.py deleted file mode 100644 index f57d0e9..0000000 --- a/psyplot_gui/console.py +++ /dev/null @@ -1,353 +0,0 @@ -""" -An example of opening up an RichJupyterWidget in a PyQT Application, this can -execute either stand-alone or by importing this file and calling -inprocess_qtconsole.show(). -Based on the earlier example in the IPython repository, this has -been updated to use qtconsole. -""" -import re -import sys - -try: - from qtconsole.inprocess import QtInProcessRichJupyterWidget -except ImportError: - from qtconsole.rich_jupyter_widget import ( - RichJupyterWidget as QtInProcessRichJupyterWidget) - -import ipykernel -from tornado import ioloop -from zmq.eventloop import ioloop as zmq_ioloop -from qtconsole.inprocess import QtInProcessKernelManager -from psyplot_gui.compat.qtcompat import ( - with_qt5, QtCore, Qt, QTextEdit, QTextCursor, QKeySequence, asstring) -from psyplot_gui.common import StreamToLogger -import psyplot -import psyplot_gui -from psyplot_gui import rcParams -from psyplot_gui.common import DockMixin -import psyplot.project as psy -from psyplot.docstring import docstrings - - -import logging - -#: HACK: Boolean that is True if the prompt should be used. This unfortunately -#: is necessary for qtconsole >= 4.3 when running the tests -_with_prompt = True - - -modules2import = [ - ('psyplot.project', 'psy'), - ('xarray', 'xr'), - ('pandas', 'pd'), - ('numpy', 'np')] - -symbols_patt = re.compile(r"[^\'\"a-zA-Z0-9_.]") - - -logger = logging.getLogger(__name__) - - -def init_asyncio_patch(): - """set default asyncio policy to be compatible with tornado - Tornado 6 (at least) is not compatible with the default - asyncio implementation on Windows - Pick the older SelectorEventLoopPolicy on Windows - if the known-incompatible default policy is in use. - do this as early as possible to make it a low priority and overrideable - ref: https://github.com/tornadoweb/tornado/issues/2608 - FIXME: if/when tornado supports the defaults in asyncio, - remove and bump tornado requirement for py38 - """ - if sys.platform.startswith("win") and sys.version_info >= (3, 8): - import asyncio - try: - from asyncio import ( - WindowsProactorEventLoopPolicy, - WindowsSelectorEventLoopPolicy, - ) - except ImportError: - pass - # not affected - else: - if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy: - # WindowsProactorEventLoopPolicy is not compatible with tornado 6 - # fallback to the pre-3.8 default of Selector - asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) - - -class IPythonControl(QTextEdit): - """A modified control to show the help of objects in the help explorer""" - - def keyPressEvent(self, event): - """Reimplement Qt Method - Basic keypress event handler""" - key = event.key() - if key == Qt.Key_Question or key == Qt.Key_ParenLeft: - self.parentWidget().show_current_help() - elif key == Qt.Key_I and (event.modifiers() & Qt.ControlModifier): - self.parentWidget().show_current_help(True, True) - # Let the parent widget handle the key press event - QTextEdit.keyPressEvent(self, event) - - -class ConsoleWidget(QtInProcessRichJupyterWidget, DockMixin): - """A console widget to access an inprocess shell""" - - custom_control = IPythonControl - - dock_position = Qt.RightDockWidgetArea - - title = 'Console' - - rc = rcParams.find_and_replace( - 'console.', pattern_base='console\.') - - intro_msg = '' - - run_script = QtCore.pyqtSignal(list) - - run_command = QtCore.pyqtSignal(list) - - _closed = True - - def __init__(self, main, *args, **kwargs): - """ - Parameters - ---------- - help_explorer: psyplot_gui.help_explorer.HelpExplorer or None - A widget that can be used to show the documentation of an object - ``*args,**kwargs`` - Any other keyword argument for the - :class:`qtconsole.rich_jupyter_widget.RichJupyterWidget` - """ - self._closed = False - - # Create an in-process kernel - # >>> print_process_id() - # will print the same process ID as the main process - init_asyncio_patch() - - kernel_manager = QtInProcessKernelManager() - # on windows, sys.stdout may be None when using pythonw.exe. Therefore - # we just us a StringIO for security - orig_stdout = sys.stdout - if sys.stdout is None: - sys.stdout = StreamToLogger(logger) - orig_stderr = sys.stderr - if sys.stderr is None: - sys.stderr = StreamToLogger(logger) - kernel_manager.start_kernel(show_banner=False) - if ipykernel.__version__ < '5.1.1': - # monkey patch to fix - # https://github.com/ipython/ipykernel/issues/370 - def _abort_queues(kernel): - pass - kernel_manager.kernel._abort_queues = _abort_queues - sys.stdout = orig_stdout - sys.stderr = orig_stderr - kernel = kernel_manager.kernel - kernel.gui = 'qt4' if not with_qt5 else 'qt' - - kernel_client = kernel_manager.client() - if rcParams['console.start_channels']: - kernel_client.start_channels() - - self.help_explorer = kwargs.pop('help_explorer', None) - - super(ConsoleWidget, self).__init__(*args, parent=main, **kwargs) - - self.intro_msg = docstrings.dedent(""" - psyplot version: %s - - gui version: %s - - The console provides you the full access to the current project and - plots. - To make your life easier, the following modules have been imported - - - %s - - Furthermore, each time you change the selection or the content in the - plot objects viewer, the `sp` (the selection) and `mp` (all arrays) - variables in the console are adjusted. To disable this behaviour, set:: - - >>> import psyplot_gui - >>> psyplot_gui.rcParams['console.auto_set_mp'] = False - >>> psyplot_gui.rcParams['console.auto_set_sp'] = False - - To inspect and object in the console and display it's documentation in - the help explorer, type 'Ctrl + I' or a '?' after the object""") % ( - psyplot.__version__, psyplot_gui.__version__, - '\n - '.join('%s as %s' % t for t in modules2import)) - - self.kernel_manager = kernel_manager - self.kernel_client = kernel_client - - self.run_command_in_shell( - '\n'.join('import %s as %s' % t for t in modules2import)) - self.exit_requested.connect(self._close_mainwindow) - self.exit_requested.connect(QtCore.QCoreApplication.instance().quit) - - # we overwrite the short cut here because the 'Ctrl+S' shortcut is - # reserved for mainwindows save action - try: - main.register_shortcut( - self.export_action, QKeySequence( - 'Ctrl+Alt+S', QKeySequence.NativeText)) - except AttributeError: - pass - - psy.Project.oncpchange.connect(self.update_mp) - psy.Project.oncpchange.connect(self.update_sp) - - self.run_script.connect(self._run_script_in_shell) - self.run_command.connect(self._run_command_in_shell) - - # HACK: we set the IOloop for the InProcessKernel here manually without - # starting it (not necessary because QApplication has a blocking - # IOLoop). However, we need this because the ZMQInteractiveShell wants - # to call - # loop = self.kernel.io_loop - # loop.call_later(0.1, loop.stop)`` - zmq_ioloop.install() - self.kernel_manager.kernel.io_loop = ioloop.IOLoop.current() - - def update_mp(self, project): - """Update the `mp` variable in the shell is - ``rcParams['console.auto_set_mp']`` with a main project""" - if self.rc['auto_set_mp'] and project is not None and project.is_main: - self.run_command_in_shell('mp = psy.gcp(True)') - - def update_sp(self, project): - """Update the `sp` variable in the shell is - ``rcParams['console.auto_set_sp']`` with a sub project""" - if self.rc['auto_set_sp'] and (project is None or not project.is_main): - self.run_command_in_shell('sp = psy.gcp()') - - def show_current_help(self, to_end=False, force=False): - """Show the help of the object at the cursor position if - ``rcParams['console.connect_to_help']`` is set""" - if not force and not self.rc['connect_to_help']: - return - obj_text = self.get_current_object(to_end) - if obj_text is not None and self.help_explorer is not None: - found, obj = self.get_obj(obj_text) - if found: - self.help_explorer.show_help(obj, obj_text) - self._control.setFocus() - - def get_obj(self, obj_text): - """ - Get the object from the shell specified by `obj_text` - - Parameters - ---------- - obj_text: str - The name of the variable as it is stored in the shell - - Returns - ------- - bool - True, if the object could be found - object or None - The requested object or None if it could not be found""" - info = self.kernel_manager.kernel.shell._object_find( - obj_text) - if info.found: - return True, info.obj - else: - return False, None - - def get_current_object(self, to_end=False): - """Get the name of the object at cursor position""" - c = self._control - if not _with_prompt: - try: # qtconsole >4.3 uses the _prompt_cursor attribute - cursor = self._prompt_cursor - except AttributeError: - cursor = c.textCursor() - else: - cursor = c.textCursor() - curr = cursor.position() - start = curr - cursor.positionInBlock() - txt = c.toPlainText()[start:curr] - eol = '' - if to_end: - cursor.movePosition(QTextCursor.EndOfBlock) - end = cursor.position() - if end > curr: - eol = c.toPlainText()[curr:end] - m = symbols_patt.search(eol) - if m: - eol = eol[:m.start()] - - if not txt: - return txt - txt = asstring(txt) - txt = txt.rsplit('\n', 1)[-1] - txt_end = "" - for startchar, endchar in ["[]", "()"]: - if txt.endswith(endchar): - pos = txt.rfind(startchar) - if pos: - txt_end = txt[pos:] - txt = txt[:pos] - tokens = symbols_patt.split(txt) - token = None - try: - while token is None or symbols_patt.match(token): - token = tokens.pop() - if token.endswith('.'): - token = token[:-1] - if token.startswith('.'): - # Invalid object name - return None - token += txt_end - if token: - return token + eol - except IndexError: - return None - - def _run_script_in_shell(self, args): - self.run_script_in_shell(args[0][0]) - - def run_script_in_shell(self, script): - """Run a script in the shell""" - self.kernel_manager.kernel.shell.run_line_magic('run', script) - - def _run_command_in_shell(self, args): - # 0: filenames - # 1: project - # 2: command - self.run_command_in_shell(args[2]) - - def run_command_in_shell(self, code, *args, **kwargs): - """Run a script in the shell""" - ret = self.kernel_manager.kernel.shell.run_code(code, *args, **kwargs) - import IPython - if IPython.__version__ < '7.0': # run_code is an asyncio.coroutine - return ret - else: - import asyncio - gathered = asyncio.gather(ret) - loop = asyncio.get_event_loop() - ret = loop.run_until_complete(gathered) - return ret[0] - - def _close_mainwindow(self): - from psyplot_gui.main import mainwindow - if mainwindow is not None: - mainwindow.close() - else: - self.close() - - def close(self): - if self.kernel_client.channels_running: - self.kernel_client.stop_channels() - self._closed = True - return super(ConsoleWidget, self).close() - - def eventFilter(self, *args, **kwargs): - if self._closed: - return False - return super().eventFilter(*args, **kwargs) diff --git a/psyplot_gui/content_widget.py b/psyplot_gui/content_widget.py deleted file mode 100644 index fb5ab98..0000000 --- a/psyplot_gui/content_widget.py +++ /dev/null @@ -1,723 +0,0 @@ -# -*- coding: utf-8 -*- -"""Module containing the project content widget to display the selection - -This module redefines the :class:`psyplot.project.Project` class with -additional features for an interactive usage with graphical qt user interface. -There is no need to import this module because the -:class:`GuiProject` class defined here replaces the project class in the -:mod:`psyplot.project` module.""" -import sys -import six -import os.path as osp -import re -import sip -import weakref -from itertools import chain -from psyplot_gui import rcParams -from psyplot_gui.compat.qtcompat import ( - QToolBox, QListWidget, QListWidgetItem, QAbstractItemView, - QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QTreeWidget, - QTreeWidgetItem, QtCore, QMenu, QAction, Qt, QLabel, QScrollArea) -from psyplot.config.rcsetup import safe_list -from psyplot.compat.pycompat import OrderedDict, map, range -from psyplot.project import scp, gcp, Project -from psyplot.data import ArrayList, InteractiveList -from psyplot.utils import _TempBool -from psyplot_gui.common import DockMixin -from xml.sax.saxutils import escape - - -html_escape_table = { - '"': """, - "'": "'" - } - - -def escape_html(s): - return escape(s, html_escape_table) - - -class ArrayItem(QListWidgetItem): - """A listwidget item that takes it's informations from a given array""" - - #: The :class:`psyplot.data.InteractiveList` or - #: :class:`psyplot.data.InteractiveArray` instance - arr = None - - def __init__(self, ref, *args, **kwargs): - """ - Parameters - ---------- - ref: weakref - The weak reference to the array to display - ``*args,**kwargs`` - Are determined by the parent class - """ - arr = ref() - super(ArrayItem, self).__init__(arr._short_info(), **kwargs) - self.arr = ref - # make sure that the item is updated when the array changes - arr.onupdate.connect(self.set_text_from_array) - self.set_text_from_array() - - def set_text_from_array(self): - """Set the text and tooltop from the - :meth:`psyplot.data.InteractiveArray._short_info` and __str__ methods - """ - if not sip.isdeleted(self): - self.setText(self.arr()._short_info()) - if rcParams['content.load_tooltips']: - if isinstance(self.arr(), InteractiveList): - self.setToolTip(str(self.arr())) - else: - self.setToolTip(str(self.arr().arr)) - else: - self.disconnect_from_array() - - def disconnect_from_array(self): - arr = self.arr() - if arr is not None: - arr.onupdate.disconnect(self.set_text_from_array) - del self.arr - - -class PlotterList(QListWidget): - """QListWidget showing multiple ArrayItems of one Plotter class""" - - #: str. The name of the attribute of the :class:`psyplot.project.Project` - #: class - project_attribute = None - - #: boolean. True if the current project does not contain any arrays in the - #: attribute identified by the :attr:`project_attribute` - is_empty = True - - _no_project_update = _TempBool() - - updated_from_project = QtCore.pyqtSignal(QListWidget) - - # Determine whether the plotter could be loaded - can_import_plotter = True - - @property - def arrays(self): - """List of The InteractiveBase instances in this list""" - return ArrayList([ - getattr(item.arr(), 'arr', item.arr()) - for item in self.array_items]) - - @property - def array_items(self): - """Iterable of :class:`ArrayItem` items in this list""" - return filter(lambda i: i is not None, - map(self.item, range(self.count()))) - - def __init__(self, plotter_type=None, *args, **kwargs): - """ - Parameters - ---------- - plotter_type: str or None - If str, it mus be an attribute name of the - :class:`psyplot.project.Project` class. Otherwise the full project - is used - ``*args,**kwargs`` - Are determined by the parent class - - Notes - ----- - When initialized, the content of the list is determined by - ``gcp(True)`` and ``gcp()``""" - super(PlotterList, self).__init__(*args, **kwargs) - self.project_attribute = plotter_type - self.setSelectionMode(QAbstractItemView.MultiSelection) - self.itemSelectionChanged.connect(self.update_cp) - self.update_from_project(gcp(True)) - self.update_from_project(gcp()) - - def update_from_project(self, project): - """Update the content from the given Project - - Parameters - ---------- - project: psyplot.project.Project - If the project is a main project, new items will be added. - Otherwise only the current selection changes""" - if self._no_project_update: - return - if not self.can_import_plotter: - # remove the current items - self.disconnect_items() - return - attr = self.project_attribute - # stop if the module of the plotter has not yet been imported - if attr and Project._registered_plotters[attr][0] not in sys.modules: - return - try: - arrays = project if not attr else getattr(project, attr) - mp = gcp(True) if project is None else project.main - main_arrays = mp if not attr else getattr(mp, attr) - except ImportError: # plotter could not be loaded - self.is_empty = True - self.can_import_plotter = False - return - self.is_empty = not bool(main_arrays) - with self._no_project_update: - if project is None: - for item in self.array_items: - item.setSelected(False) - elif project.is_main: - old_arrays = self.arrays - # remove outdated items - i = 0 - for arr in old_arrays: - if arr not in arrays: - item = self.takeItem(i) - item.disconnect_from_array() - else: - i += 1 - # add new items - for arr in arrays: - if arr not in old_arrays: - item = ArrayItem(weakref.ref(arr.psy), parent=self) - self.addItem(item) - # resort to match the project - for arr in reversed(main_arrays): - for i, item in enumerate(self.array_items): - if item.arr() is arr.psy: - self.insertItem(0, self.takeItem(i)) - cp = gcp() - for item in self.array_items: - item.setSelected( - getattr(item.arr(), 'arr', item.arr()) in cp) - self.updated_from_project.emit(self) - - def update_cp(self, *args, **kwargs): - """Update the current project from what is selected in this list""" - if not self._no_project_update: - mp = gcp(True) - sp = gcp() - selected = [item.arr().arr_name for item in self.selectedItems()] - arrays = self.arrays - other_selected = [ - arr.psy.arr_name for arr in sp if arr not in arrays] - with self._no_project_update: - scp(mp(arr_name=selected + other_selected)) - - def disconnect_items(self): - """Disconnect the items in this list from the arrays""" - for item in list(self.array_items): - item.disconnect_from_array() - self.takeItem(self.indexFromItem(item).row()) - self.is_empty = True - - -class ProjectContent(QToolBox): - """Display the content in the current project - - This toolbox contains several :class:`PlotterList` that show the content - of the current main and subproject""" - - #: :class:`OrderedDict` containing the :class:`PlotterList` instances - #: of the different selection attributes - lists = OrderedDict() - - @property - def current_names(self): - return [self.itemText(i) for i in range(self.count())] - - def __init__(self, *args, **kwargs): - super(ProjectContent, self).__init__(*args, **kwargs) - self.lists = OrderedDict() - for attr in chain(['All'], sorted(Project._registered_plotters)): - item = self.add_plotterlist(attr, force=(attr == 'All')) - self.lists[attr] = item - self.currentChanged.connect(self.update_current_list) - Project.oncpchange.connect(self.update_lists) - - def enable_list(self, list_widget): - """Enable a given list widget based upon whether it is empty or not""" - i = self.indexOf(list_widget) - if i != -1: - self.setItemEnabled(i, not list_widget.is_empty) - - def add_plotterlist(self, identifier, force=False): - """Create a :class:`PlotterList` from an identifier from the - :class:`psyplot.project.Project` class""" - attr = identifier if identifier != 'All' else None - item = PlotterList(attr) - if not item.can_import_plotter: - return item - if force or not item.is_empty: - item.setParent(self) - item.updated_from_project.connect(self.enable_list) - self.addItem(item, identifier) - i = self.indexOf(item) - self.setItemEnabled(i, not item.is_empty) - return item - - def update_current_list(self): - """Update the current list from the current main and sub project""" - self.currentWidget().update_from_project(gcp(True)) - self.currentWidget().update_from_project(gcp()) - - def update_lists(self, p): - # check new lists - current_items = self.current_names - for name, l in self.lists.items(): - if not p.is_main: - l.update_from_project(p.main) - l.update_from_project(p) - if l.is_empty: - l.disconnect_items() - if name != 'All' and l.is_empty: - i = self.indexOf(l) - self.removeItem(i) - elif not l.is_empty and name not in current_items: - self.addItem(l, name) - - -class SelectAllButton(QPushButton): - """A button to select all data objects in the current main project""" - - def __init__(self, *args, **kwargs): - super(SelectAllButton, self).__init__(*args, **kwargs) - self.setToolTip( - 'Click to select all data arrays in the entire project') - self.clicked.connect(self.select_all) - Project.oncpchange.connect(self.enable_from_project) - - def select_all(self): - """Select all arrays""" - scp(gcp(True)[:]) - - def enable_from_project(self, project): - """Enable the button if the given project is not empty""" - self.setEnabled(bool(project.main if project is not None else gcp(1))) - - -class SelectNoneButton(QPushButton): - """A button to select no data objects in the current main project""" - - def __init__(self, *args, **kwargs): - super(SelectNoneButton, self).__init__(*args, **kwargs) - self.setToolTip('Click to deselect all data arrays') - self.clicked.connect(self.select_none) - Project.oncpchange.connect(self.enable_from_project) - - def select_none(self): - """Clear current subproject""" - scp(gcp(True)[:0]) - - def enable_from_project(self, project): - """Enable the button if the given project is not empty""" - self.setEnabled(bool(project)) - - -class ProjectContentWidget(QWidget, DockMixin): - """A combination of selection buttons and the ProjectContent""" - - def __init__(self, *args, **kwargs): - super(ProjectContentWidget, self).__init__(*args, **kwargs) - vbox = QVBoxLayout() - # create buttons for unselecting and selecting all arrays - self.unselect_button = SelectNoneButton('Unselect all', parent=self) - self.select_all_button = SelectAllButton('Select all', parent=self) - button_hbox = QHBoxLayout() - button_hbox.addWidget(self.unselect_button) - button_hbox.addWidget(self.select_all_button) - mp = gcp(True) - self.unselect_button.setEnabled(bool(mp)) - self.select_all_button.setEnabled(bool(mp)) - # create widget showing the content of the current project - self.content_widget = ProjectContent(parent=self) - vbox.addLayout(button_hbox) - vbox.addWidget(self.content_widget) - self.setLayout(vbox) - - -class DatasetTreeItem(QTreeWidgetItem): - """A QTreeWidgetItem showing informations on one dataset in the main - project""" - - def __init__(self, ds, columns=[], *args, **kwargs): - super(DatasetTreeItem, self).__init__(*args, **kwargs) - self.variables = variables = QTreeWidgetItem(0) - self.columns = columns - variables.setText(0, 'variables (%i)' % len(ds)) - self.coords = coords = QTreeWidgetItem(0) - coords.setText(0, 'coords (%i)' % len(ds.coords)) - self.attrs = attrs = QTreeWidgetItem(0) - attrs.setText(0, 'Global Attributes (%i)' % len(ds.attrs)) - self.addChildren([variables, coords]) - self.addChild(variables) - self.addChild(attrs) - self.add_variables(ds) - self.add_attrs(ds.attrs) - - def add_variables(self, ds=None): - """Add children of variables and coords to this TreeWidgetItem""" - if ds is None: - ds = self.ds() - self.variables.takeChildren() - self.coords.takeChildren() - else: - self.ds = weakref.ref(ds) - columns = self.columns - variables = self.variables - coords = self.coords - for vname, variable in six.iteritems(ds.variables): - item = QTreeWidgetItem(0) - item.setText(0, str(vname)) - for i, attr in enumerate(columns, 1): - if attr == 'dims': - item.setText(i, ', '.join(variable.dims)) - else: - item.setText(i, str(variable.attrs.get(attr, getattr( - variable, attr, '')))) - if vname in ds.coords: - coords.addChild(item) - else: - variables.addChild(item) - if rcParams['content.load_tooltips']: - item.setToolTip( - 0, '
' + escape_html(str(variable)) + '
') - - # Add shape - shape_item = QTreeWidgetItem(0) - shape_item.setText(0, 'shape') - shape_item.setText(1, str(variable.shape)) - item.addChild(shape_item) - - - # Add dimensions - dims_item = QTreeWidgetItem(0) - dims_item.setText(0, 'dims') - dims_item.setText(1, ', '.join(variable.dims)) - item.addChild(dims_item) - - # add open plots - plots_item = QTreeWidgetItem(0) - plots_item.setText(0, 'Plots') - self.refresh_plots_item(plots_item, vname) - item.addChild(plots_item) - - # add variable attribute - attrs_item = QTreeWidgetItem(0) - attrs_item.setText(0, 'Attributes') - self.add_attrs(variable.attrs, attrs_item) - item.addChild(attrs_item) - - # add variable encoding - encoding_item = QTreeWidgetItem(0) - encoding_item.setText(0, 'Encoded attributes') - self.add_attrs(variable.encoding, encoding_item) - item.addChild(encoding_item) - - def get_plots_item(self, item): - for child in map(item.child, range(item.childCount())): - if child.text(0) == 'Plots': - return child - - def refresh_plots_item(self, item, vname, mp=None, sp=None): - expand = item.isExpanded() - item.takeChildren() - try: - num = self.ds().psy.num - except AttributeError: - return - if mp is None: - mp = gcp(True) - if sp is None: - sp = gcp() - for i in range(len(mp)): - sub = mp[i:i+1] - array_info = sub.array_info(ds_description={'arr', 'num'}) - arrs = sub._get_ds_descriptions(array_info).get(num, {}) - if arrs and any(vname in arr.psy.base_variables - for arr in arrs['arr']): - child = QTreeWidgetItem(0) - prefix = '*' if sub[0] in sp else '' - text = sub[0].psy._short_info() - child.setText(0, prefix + text) - child.setToolTip(0, text) - item.addChild(child) - if expand and item.childCount(): - item.setExpanded(True) - - - def add_attrs(self, attrs=None, item=None): - if attrs is None: - attrs = self.ds().attrs - self.attrs.takeChildren() - if item is None: - item = self.attrs - for key, val in attrs.items(): - child = QTreeWidgetItem(0) - child.setText(0, key) - child.setText(1, str(val)) - child.setToolTip(1, '{}: {}'.format(key, str(val))) - item.addChild(child) - - -class DatasetTree(QTreeWidget, DockMixin): - """A QTreeWidget showing informations on all datasets in the main project - """ - - tooltips = { - 'Refresh': 'Refresh the selected dataset', - 'Refresh all': 'Refresh all datasets', - 'Add to project': ('Add this variable or a plot of it to the current ' - 'project')} - - def __init__(self, *args, **kwargs): - super(DatasetTree, self).__init__(*args, **kwargs) - self.create_dataset_tree() - self.itemExpanded.connect(self.load_variable_desc) - self.setContextMenuPolicy(Qt.CustomContextMenu) - self.customContextMenuRequested.connect(self.open_menu) - Project.oncpchange.connect(self.add_datasets_from_cp) - self.hideColumn(1) - - @staticmethod - def is_variable(item): - return re.match(r'variables \(\d+\)', item.parent().text(0)) - - @staticmethod - def is_coord(item): - return re.match(r'coords\(\d+\)', item.parent().text(0)) - - def load_variable_desc(self, item): - parent = item.parent() - if parent is self or parent is None or not (self.is_variable(item) or - self.is_coord(item)): - return - if self.isColumnHidden(1): - self.showColumn(1) - self.resizeColumnToContents(0) - - top = item - while top.parent() and top.parent() is not self: - top = top.parent() - ds = top.ds() - if ds is None: - return - desc = escape_html(str(ds.variables[item.text(0)])) - item.setToolTip(0, '
' + desc + '
') - - def create_dataset_tree(self): - """Set up the columns and insert the :class:`DatasetTreeItem` - instances from the current project""" - self.set_columns() - self.add_datasets_from_cp(gcp()) - - def set_columns(self, columns=['Value']): - """Set up the columns in the DatasetTree. - - Parameters - ---------- - columns: list of str - A list of netCDF attributes that shall be shown in columns""" - self.setColumnCount(len(columns) + 1) - if columns: - self.setHeaderHidden(False) - self.setHeaderLabels(['Dataset'] + list(columns)) - else: - self.setHeaderHidden(True) - self.attr_columns = columns - - def expanded_items(self): - "Create a mapping from dataset numbers to variables that are expanded." - ret = {} - for item in map(self.topLevelItem, range(self.topLevelItemCount())): - if item.isExpanded() and item.ds() is not None: - ds = item.ds() - ret[ds.psy.num] = d = {} - for child in map(item.child, range(item.childCount())): - if child.childCount() and child.isExpanded(): - d[child.text(0)] = variables = [] - for vchild in map( - child.child, range(child.childCount())): - if vchild.childCount() and vchild.isExpanded(): - variables.append(vchild.text(0)) - return ret - - def add_datasets_from_cp(self, project=None): - """Clear the tree and add the datasets based upon the given `project` - - Parameters - ---------- - project: psyplot.project.Project - The project containing the data array. If the project is not a main - project, it's main project is used. - """ - if project is None: - project = gcp(True) - sp_arrs = ArrayList().arrays - elif project.is_main: - sp_arrs = gcp().arrays - else: - sp_arrs = project.arrays - project = project.main - - expanded_items = self.expanded_items() - # remove items from the tree - self.clear() - for i, ds_desc in six.iteritems(project._get_ds_descriptions( - project.array_info(ds_description='all'))): - top_item = DatasetTreeItem(ds_desc['ds'], self.attr_columns, 0) - if ds_desc['fname'] is not None and not all( - s is None for s in ds_desc['fname']): - ds_desc['fname'] = ', '.join(map(osp.basename, - safe_list(ds_desc['fname']))) - else: - ds_desc['fname'] = None - top_item.setText(0, '%s%i: %s' % ( - '*' if any(any(arr is arr2 for arr2 in sp_arrs) - for arr in ds_desc['arr']) else '', - i, ds_desc['fname'])) - for arr in ds_desc['arr']: - arr.psy.onbasechange.connect(self.add_datasets_from_cp) - self.addTopLevelItem(top_item) - self.expand_items(expanded_items) - - def expand_items(self, expanded_items): - """Expand tree items - - Parameters - ---------- - expanded_items: dict - A mapping as returned by the :meth:`expanded_items` method""" - for top in map(self.topLevelItem, range(self.topLevelItemCount())): - ds = top.ds() - if ds.psy.num in expanded_items: - self.expandItem(top) - d = expanded_items[ds.psy.num] - for child in map(top.child, range(top.childCount())): - if child.text(0) in d: - self.expandItem(child) - for vchild in map(child.child, - range(child.childCount())): - if vchild.text(0) in d[child.text(0)]: - self.expandItem(vchild) - - def open_menu(self, pos): - menu = QMenu() - item = self.itemAt(pos) - parent, item_type, vname = self._get_toplevel_item(item) - # ---- Refresh the selected item action - refresh_action = QAction('Refresh', self) - refresh_action.setToolTip(self.tooltips['Refresh']) - refresh_action.triggered.connect(lambda: self.refresh_items(parent)) - - # ---- Refresh all items action - refresh_all_action = QAction('Refresh all', self) - refresh_all_action.setToolTip(self.tooltips['Refresh all']) - refresh_all_action.triggered.connect(lambda: self.refresh_items()) - - # ---- add refresh actions - menu.addActions([refresh_action, refresh_all_action]) - - # ---- add plot option - if item_type == 'variable': - add2p_action = QAction(f'Add new plot of {vname}', self) - add2p_action.setToolTip(self.tooltips['Add to project']) - add2p_action.triggered.connect(lambda: self.make_plot( - parent.ds(), item.text(0), True)) - menu.addSeparator() - menu.addAction(add2p_action) - - # ---- show menu - menu.exec_(self.mapToGlobal(pos)) - return menu - - def refresh_items(self, item=None): - if item is not None: - item.add_variables() - else: - for item in map(self.topLevelItem, - range(self.topLevelItemCount())): - item.add_variables() - - def make_plot(self, ds, name, exec_=None): - from psyplot_gui.main import mainwindow - mainwindow.new_plots() - mainwindow.plot_creator.switch2ds(ds) - mainwindow.plot_creator.insert_array(safe_list(name)) - if exec_: - mainwindow.plot_creator.exec_() - - def _get_toplevel_item(self, item): - if item is None: - parent = None - else: - parent = item.parent() - item_type = None - vname = None - while parent is not None: - if self.is_variable(item): - vname = item.text(0) - item_type = 'variable' - elif self.is_coord(item): - vname = item.text(0) - item_type = 'coord' - item = item.parent() - parent = item.parent() - return item, item_type, vname - - -class FiguresTreeItem(QTreeWidgetItem): - """An item displaying the information on a data object in one figure""" - - def __init__(self, ref, *args, **kwargs): - """ - Parameters - ---------- - ref: weakref - The weak reference to the array containing the data""" - super(FiguresTreeItem, self).__init__(*args, **kwargs) - self.arr = ref - self.set_text_from_array() - ref().psy.onupdate.connect(self.set_text_from_array) - - def set_text_from_array(self): - """Set the text and tooltop from the - :meth:`psyplot.data.InteractiveArray._short_info` and __str__ methods - """ - self.setText(0, self.arr().psy._short_info()) - if rcParams['content.load_tooltips']: - self.setToolTip(0, str(self.arr())) - - def disconnect_from_array(self): - """Disconect this item from the corresponding array""" - arr = self.arr() - if arr is not None: - arr.psy.onupdate.disconnect(self.set_text_from_array) - del self.arr - - -class FiguresTree(QTreeWidget, DockMixin): - """A tree widget sorting the arrays by their figure - - This widget uses the current sub and main project to show the open figures - """ - - def __init__(self, *args, **kwargs): - super(FiguresTree, self).__init__(*args, **kwargs) - self.setHeaderLabel('Figure') - Project.oncpchange.connect(self.add_figures_from_cp) - self.add_figures_from_cp(gcp(True)) - - def add_figures_from_cp(self, project): - """Add the items in this tree based upon the figures in the given - project""" - if project is None or not project.is_main: - return - for item in map(self.takeTopLevelItem, [0] * self.topLevelItemCount()): - for child in item.takeChildren(): - child.disconnect_from_array() - for fig, arrays in six.iteritems(project.figs): - item = QTreeWidgetItem(0) - item.setText(0, fig.canvas.get_window_title()) - item.addChildren( - [FiguresTreeItem(weakref.ref(arr), 0) for arr in arrays]) - self.addTopLevelItem(item) diff --git a/psyplot_gui/dataframeeditor.py b/psyplot_gui/dataframeeditor.py deleted file mode 100644 index f3b31e8..0000000 --- a/psyplot_gui/dataframeeditor.py +++ /dev/null @@ -1,950 +0,0 @@ -"""A widget to display and edit DataFrames""" -import os -import os.path as osp -import six -from functools import partial -import numpy as np -from psyplot.docstring import docstrings -from psyplot_gui.compat.qtcompat import ( - QWidget, QHBoxLayout, QVBoxLayout, QtCore, QLineEdit, - QPushButton, Qt, QToolButton, QIcon, QMenu, QLabel, QtGui, QApplication, - QCheckBox, QFileDialog, with_qt5, QTableView, QHeaderView, - QDockWidget) -from psyplot_gui.common import (DockMixin, get_icon, LoadFromConsoleButton, - PyErrorMessage) -import pandas as pd - -if six.PY2: - try: - import CStringIO as io - except ImportError: - import StringIO as io -else: - import io - - -LARGE_SIZE = int(5e5) -LARGE_NROWS = int(1e5) -LARGE_COLS = 60 - -REAL_NUMBER_TYPES = (float, int, np.int64, np.int32) -COMPLEX_NUMBER_TYPES = (complex, np.complex64, np.complex128) - -_bool_false = ['false', '0'] - - -def bool_false_check(value): - """ - Used to convert bool intrance to false since any string in bool('') - will return True - """ - if value.lower() in _bool_false: - value = '' - return value - - -class DataFrameModel(QtCore.QAbstractTableModel): - """ DataFrame Table Model""" - - ROWS_TO_LOAD = 500 - COLS_TO_LOAD = 40 - - _format = '%0.6g' - - @docstrings.get_sections(base='DataFrameModel') - @docstrings.dedent - def __init__(self, df, parent=None, index_editable=True, - dtypes_changeable=True): - """ - Parameters - ---------- - df: pandas.DataFrame - The data frame that will be shown by this :class:`DataFrameModel` - instance - parent: DataFrameEditor - The editor for the table - index_editable: bool - True if the index should be modifiable by the user - dtypes_changeable: bool - True, if the data types should be modifiable by the user - """ - QtCore.QAbstractTableModel.__init__(self) - self._parent = parent - self.df = df - self.df_index = self.df.index.tolist() - self.df_header = self.df.columns.tolist() - self.total_rows = self.df.shape[0] - self.total_cols = self.df.shape[1] - size = self.total_rows * self.total_cols - self.index_editable = index_editable - self.dtypes_changeable = dtypes_changeable - - # Use paging when the total size, number of rows or number of - # columns is too large - if size > LARGE_SIZE: - self.rows_loaded = self.ROWS_TO_LOAD - self.cols_loaded = self.COLS_TO_LOAD - else: - if self.total_rows > LARGE_NROWS: - self.rows_loaded = self.ROWS_TO_LOAD - else: - self.rows_loaded = self.total_rows - if self.total_cols > LARGE_COLS: - self.cols_loaded = self.COLS_TO_LOAD - else: - self.cols_loaded = self.total_cols - - def get_format(self): - """Return current format""" - # Avoid accessing the private attribute _format from outside - return self._format - - def set_format(self, format): - """Change display format""" - self._format = format - self.reset() - - def bgcolor(self, state): - """Toggle backgroundcolor""" - self.bgcolor_enabled = state > 0 - self.reset() - - def headerData(self, section, orientation, role=Qt.DisplayRole): - """Set header data""" - if role != Qt.DisplayRole: - return None - - if orientation == Qt.Horizontal: - if section == 0: - return six.text_type('Index') - elif isinstance(self.df_header[section-1], six.string_types): - header = self.df_header[section-1] - return six.text_type(header) - else: - return six.text_type(self.df_header[section-1]) - else: - return None - - def get_value(self, row, column): - """Returns the value of the DataFrame""" - # To increase the performance iat is used but that requires error - # handling, so fallback uses iloc - try: - value = self.df.iat[row, column] - except AttributeError: - value = self.df.iloc[row, column] - return value - - def data(self, index, role=Qt.DisplayRole): - """Cell content""" - if not index.isValid(): - return None - if role == Qt.DisplayRole or role == Qt.EditRole: - column = index.column() - row = index.row() - if column == 0: - return six.text_type(self.df_index[row]) - else: - value = self.get_value(row, column-1) - if isinstance(value, float): - try: - return self._format % value - except (ValueError, TypeError): - # may happen if format = '%d' and value = NaN; - # see issue 4139 - return DataFrameModel._format % value - else: - return six.text_type(value) - - def sort(self, column, order=Qt.AscendingOrder, return_check=False, - report=True): - """Overriding sort method""" - try: - ascending = order == Qt.AscendingOrder - if column > 0: - try: - self.df.sort_values(by=self.df.columns[column-1], - ascending=ascending, inplace=True, - kind='mergesort') - except AttributeError: - # for pandas version < 0.17 - self.df.sort(columns=self.df.columns[column-1], - ascending=ascending, inplace=True, - kind='mergesort') - self.update_df_index() - else: - self.df.sort_index(inplace=True, ascending=ascending) - self.update_df_index() - except TypeError as e: - if report: - self._parent.error_msg.showTraceback( - "Failed to sort column!") - return False if return_check else None - self.reset() - return True if return_check else None - - def flags(self, index): - """Set flags""" - if index.column() == 0 and not self.index_editable: - return Qt.ItemIsEnabled | Qt.ItemIsSelectable - return Qt.ItemFlags(QtCore.QAbstractTableModel.flags(self, index) | - Qt.ItemIsEditable) - - def setData(self, index, value, role=Qt.EditRole, change_type=None): - """Cell content change""" - column = index.column() - row = index.row() - - if change_type is not None: - if not self.dtypes_changeable: - return False - try: - value = current_value = self.data(index, role=Qt.DisplayRole) - if change_type is bool: - value = bool_false_check(value) - value = np.asarray(change_type(value)) # to make sure it works - icol = column - 1 - self.df.iloc[:, icol] = self.df.iloc[:, icol].astype( - change_type) - except ValueError: - self.df.iloc[row, icol] = self.df.iloc[row, icol].astype(object) - else: - current_value = self.get_value(row, column-1) if column else \ - self.df.index[row] - if isinstance(current_value, bool): - value = bool_false_check(value) - supported_types = (bool,) + REAL_NUMBER_TYPES + \ - COMPLEX_NUMBER_TYPES - if (isinstance(current_value, supported_types) or - isinstance(current_value, six.string_types)): - if column: - try: - self.df.iloc[row, column-1] = current_value.__class__( - value) - except ValueError as e: - self._parent.error_msg.showTraceback( - "Failed to set value with %r!" % value) - return False - elif self.index_editable: - index = self.df.index.values.copy() - try: - index[row] = value - except ValueError as e: - self._parent.error_msg.showTraceback( - "Failed to set value with %r!" % value) - return False - self.df.index = pd.Index(index, name=self.df.index.name) - self.update_df_index() - else: - return False - else: - self._parent.error_msg.showTraceback( - "The type of the cell is not a supported type" - "") - return False - self._parent.cell_edited.emit(row, column, current_value, value) - return True - - def rowCount(self, index=QtCore.QModelIndex()): - """DataFrame row number""" - if self.total_rows <= self.rows_loaded: - return self.total_rows - else: - return self.rows_loaded - - def can_fetch_more(self, rows=False, columns=False): - if rows: - if self.total_rows > self.rows_loaded: - return True - else: - return False - if columns: - if self.total_cols > self.cols_loaded: - return True - else: - return False - - def fetch_more(self, rows=False, columns=False): - if self.can_fetch_more(rows=rows): - reminder = self.total_rows - self.rows_loaded - items_to_fetch = min(reminder, self.ROWS_TO_LOAD) - self.beginInsertRows(QtCore.QModelIndex(), self.rows_loaded, - self.rows_loaded + items_to_fetch - 1) - self.rows_loaded += items_to_fetch - self.endInsertRows() - if self.can_fetch_more(columns=columns): - reminder = self.total_cols - self.cols_loaded - items_to_fetch = min(reminder, self.COLS_TO_LOAD) - self.beginInsertColumns(QtCore.QModelIndex(), self.cols_loaded, - self.cols_loaded + items_to_fetch - 1) - self.cols_loaded += items_to_fetch - self.endInsertColumns() - - def columnCount(self, index=QtCore.QModelIndex()): - """DataFrame column number""" - # This is done to implement series - if len(self.df.shape) == 1: - return 2 - elif self.total_cols <= self.cols_loaded: - return self.total_cols + 1 - else: - return self.cols_loaded + 1 - - def update_df_index(self): - """"Update the DataFrame index""" - self.df_index = self.df.index.tolist() - - def reset(self): - self.beginResetModel() - self.endResetModel() - - def insertRow(self, irow): - """Insert one row into the :attr:`df` - - Parameters - ---------- - irow: int - The row index. If iRow is equal to the length of the - :attr:`df`, the new row will be appended.""" - # reimplemented to fall back to the :meth:`insertRows` method - self.insertRows(irow) - - def insertRows(self, irow, nrows=1): - """Insert a row into the :attr:`df` - - Parameters - ---------- - irow: int - The row index. If `irow` is equal to the length of the - :attr:`df`, the rows will be appended. - nrows: int - The number of rows to insert""" - df = self.df - if not irow: - if not len(df): - idx = 0 - else: - idx = df.index.values[0] - else: - try: - idx = df.index.values[irow-1:irow+1].mean() - except TypeError: - idx = df.index.values[min(irow, len(df) - 1)] - else: - idx = df.index.values[min(irow, len(df) - 1)].__class__(idx) - # reset the index to sort it correctly - idx_name = df.index.name - dtype = df.index.dtype - df.reset_index(inplace=True) - new_idx_name = df.columns[0] - current_len = len(df) - for i in range(nrows): - df.loc[current_len + i, new_idx_name] = idx - df[new_idx_name] = df[new_idx_name].astype(dtype) - if irow < current_len: - changed = df.index.values.astype(float) - changed[current_len:] = irow - 0.5 - df.index = changed - df.sort_index(inplace=True) - df.set_index(new_idx_name, inplace=True, drop=True) - df.index.name = idx_name - self.update_df_index() - self.beginInsertRows(QtCore.QModelIndex(), self.rows_loaded, - self.rows_loaded + nrows - 1) - self.total_rows += nrows - self.rows_loaded += nrows - self.endInsertRows() - self._parent.rows_inserted.emit(irow, nrows) - - -class FrozenTableView(QTableView): - """This class implements a table with its first column frozen - For more information please see: - http://doc.qt.io/qt-5/qtwidgets-itemviews-frozencolumn-example.html""" - def __init__(self, parent): - """Constructor.""" - QTableView.__init__(self, parent) - self.parent = parent - self.setModel(parent.model()) - self.setFocusPolicy(Qt.NoFocus) - self.verticalHeader().hide() - if with_qt5: - self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed) - else: - self.horizontalHeader().setResizeMode(QHeaderView.Fixed) - - parent.viewport().stackUnder(self) - - self.setSelectionModel(parent.selectionModel()) - for col in range(1, parent.model().columnCount()): - self.setColumnHidden(col, True) - - self.setColumnWidth(0, parent.columnWidth(0)) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) - self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) - self.show() - self.setVerticalScrollMode(QTableView.ScrollPerPixel) - - self.verticalScrollBar().valueChanged.connect( - parent.verticalScrollBar().setValue) - parent.verticalScrollBar().valueChanged.connect( - self.verticalScrollBar().setValue) - - def update_geometry(self): - """Update the frozen column size when an update occurs in its parent - table""" - self.setGeometry(self.parent.verticalHeader().width() + - self.parent.frameWidth(), - self.parent.frameWidth(), - self.parent.columnWidth(0), - self.parent.viewport().height() + - self.parent.horizontalHeader().height()) - - def contextMenuEvent(self, event): - """Show the context Menu - - Reimplemented to show the use the contextMenuEvent of the parent""" - self.parent.contextMenuEvent(event) - - -class DataFrameView(QTableView): - """Data Frame view class""" - - @property - def filled(self): - """True if the table is filled with content""" - return bool(self.model().rows_loaded) - - @docstrings.dedent - def __init__(self, df, parent, *args, **kwargs): - """ - Parameters - ---------- - %(DataFrameModel.parameters)s - """ - QTableView.__init__(self, parent) - model = DataFrameModel(df, parent, *args, **kwargs) - self.setModel(model) - self.menu = self.setup_menu() - - self.frozen_table_view = FrozenTableView(self) - self.frozen_table_view.update_geometry() - - self.setHorizontalScrollMode(1) - self.setVerticalScrollMode(1) - - self.horizontalHeader().sectionResized.connect( - self.update_section_width) - self.verticalHeader().sectionResized.connect( - self.update_section_height) - - self.sort_old = [None] - self.header_class = self.horizontalHeader() - self.header_class.sectionClicked.connect(self.sortByColumn) - self.frozen_table_view.horizontalHeader().sectionClicked.connect( - self.sortByColumn) - self.horizontalScrollBar().valueChanged.connect( - lambda val: self.load_more_data(val, columns=True)) - self.verticalScrollBar().valueChanged.connect( - lambda val: self.load_more_data(val, rows=True)) - - def update_section_width(self, logical_index, old_size, new_size): - """Update the horizontal width of the frozen column when a - change takes place in the first column of the table""" - if logical_index == 0: - self.frozen_table_view.setColumnWidth(0, new_size) - self.frozen_table_view.update_geometry() - - def update_section_height(self, logical_index, old_size, new_size): - """Update the vertical width of the frozen column when a - change takes place on any of the rows""" - self.frozen_table_view.setRowHeight(logical_index, new_size) - - def resizeEvent(self, event): - """Update the frozen column dimensions. - - Updates takes place when the enclosing window of this - table reports a dimension change - """ - QTableView.resizeEvent(self, event) - self.frozen_table_view.update_geometry() - - def moveCursor(self, cursor_action, modifiers): - """Update the table position. - - Updates the position along with the frozen column - when the cursor (selector) changes its position - """ - current = QTableView.moveCursor(self, cursor_action, modifiers) - - col_width = (self.columnWidth(0) + - self.columnWidth(1)) - topleft_x = self.visualRect(current).topLeft().x() - - overflow = self.MoveLeft and current.column() > 1 - overflow = overflow and topleft_x < col_width - - if cursor_action == overflow: - new_value = (self.horizontalScrollBar().value() + - topleft_x - col_width) - self.horizontalScrollBar().setValue(new_value) - return current - - def scrollTo(self, index, hint): - """Scroll the table. - - It is necessary to ensure that the item at index is visible. - The view will try to position the item according to the - given hint. This method does not takes effect only if - the frozen column is scrolled. - """ - if index.column() > 1: - QTableView.scrollTo(self, index, hint) - - def load_more_data(self, value, rows=False, columns=False): - if rows and value == self.verticalScrollBar().maximum(): - self.model().fetch_more(rows=rows) - if columns and value == self.horizontalScrollBar().maximum(): - self.model().fetch_more(columns=columns) - - def sortByColumn(self, index): - """ Implement a Column sort """ - frozen_header = self.frozen_table_view.horizontalHeader() - if not self.isSortingEnabled(): - self.header_class.setSortIndicatorShown(False) - frozen_header.setSortIndicatorShown(False) - return - if self.sort_old == [None]: - self.header_class.setSortIndicatorShown(True) - frozen_header.setSortIndicatorShown(index == 0) - if index == 0: - sort_order = frozen_header.sortIndicatorOrder() - else: - sort_order = self.header_class.sortIndicatorOrder() - if not self.model().sort(index, sort_order, True): - if len(self.sort_old) != 2: - self.header_class.setSortIndicatorShown(False) - frozen_header.setSortIndicatorShown(False) - else: - self.header_class.setSortIndicator(self.sort_old[0], - self.sort_old[1]) - if index == 0: - frozen_header.setSortIndicator(self.sort_old[0], - self.sort_old[1]) - return - self.sort_old = [index, self.header_class.sortIndicatorOrder()] - - def change_type(self, func): - """A function that changes types of cells""" - model = self.model() - index_list = self.selectedIndexes() - for i in index_list: - model.setData(i, '', change_type=func) - - def insert_row_above_selection(self): - """Insert rows above the selection - - The number of rows inserted depends on the number of selected rows""" - rows, cols = self._selected_rows_and_cols() - model = self.model() - if not model.rowCount(): - model.insertRows(0, 1) - elif not rows and not cols: - return - else: - min_row = min(rows) - nrows = len(set(rows)) - model.insertRows(min_row, nrows) - - def insert_row_below_selection(self): - """Insert rows below the selection - - The number of rows inserted depends on the number of selected rows""" - rows, cols = self._selected_rows_and_cols() - model = self.model() - if not model.rowCount(): - model.insertRows(0, 1) - elif not rows and not cols: - return - else: - max_row = max(rows) - nrows = len(set(rows)) - model.insertRows(max_row + 1, nrows) - - def _selected_rows_and_cols(self): - index_list = self.selectedIndexes() - if not index_list: - return [], [] - return list(zip(*[(i.row(), i.column()) for i in index_list])) - - docstrings.delete_params('DataFrameModel.parameters', 'parent') - - @docstrings.dedent - def set_df(self, df, *args, **kwargs): - """ - Set the :class:`~pandas.DataFrame` for this table - - Parameters - ---------- - %(DataFrameModel.parameters.no_parent)s - """ - model = DataFrameModel(df, self.parent(), *args, **kwargs) - self.setModel(model) - self.frozen_table_view.setModel(model) - - def reset_model(self): - self.model().reset() - - def contextMenuEvent(self, event): - """Reimplement Qt method""" - model = self.model() - for a in self.dtype_actions.values(): - a.setEnabled(model.dtypes_changeable) - nrows = max(len(set(self._selected_rows_and_cols()[0])), 1) - self.insert_row_above_action.setText('Insert %i row%s above' % ( - nrows, 's' if nrows - 1 else '')) - self.insert_row_below_action.setText('Insert %i row%s below' % ( - nrows, 's' if nrows - 1 else '')) - self.insert_row_above_action.setEnabled(model.index_editable) - self.insert_row_below_action.setEnabled(model.index_editable) - self.menu.popup(event.globalPos()) - event.accept() - - def setup_menu(self): - """Setup context menu""" - menu = QMenu(self) - menu.addAction('Copy', self.copy, QtGui.QKeySequence.Copy) - menu.addSeparator() - functions = (("To bool", bool), ("To complex", complex), - ("To int", int), ("To float", float), - ("To str", str)) - self.dtype_actions = { - name: menu.addAction(name, partial(self.change_type, func)) - for name, func in functions} - menu.addSeparator() - self.insert_row_above_action = menu.addAction( - 'Insert rows above', self.insert_row_above_selection) - self.insert_row_below_action = menu.addAction( - 'Insert rows below', self.insert_row_below_selection) - menu.addSeparator() - self.set_index_action = menu.addAction( - 'Set as index', partial(self.set_index, False)) - self.append_index_action = menu.addAction( - 'Append to as index', partial(self.set_index, True)) - return menu - - def set_index(self, append=False): - """Set the index from the selected columns""" - model = self.model() - df = model.df - args = [model.dtypes_changeable, model.index_editable] - cols = np.unique(self._selected_rows_and_cols()[1]) - if not append: - cols += len(df.index.names) - 1 - df.reset_index(inplace=True) - else: - cols -= 1 - cols = cols.tolist() - if len(cols) == 1: - df.set_index(df.columns[cols[0]], inplace=True, append=append) - else: - df.set_index(df.columns[cols].tolist(), inplace=True, - append=append) - self.set_df(df, *args) - - def copy(self): - """Copy text to clipboard""" - rows, cols = self._selected_rows_and_cols() - if not rows and not cols: - return - row_min, row_max = min(rows), max(rows) - col_min, col_max = min(cols), max(cols) - index = header = False - if col_min == 0: - col_min = 1 - index = True - df = self.model().df - if col_max == 0: # To copy indices - contents = '\n'.join(map(str, df.index.tolist()[slice(row_min, - row_max+1)])) - else: # To copy DataFrame - if (col_min == 0 or col_min == 1) and (df.shape[1] == col_max): - header = True - obj = df.iloc[slice(row_min, row_max+1), slice(col_min-1, col_max)] - output = io.StringIO() - obj.to_csv(output, sep='\t', index=index, header=header) - if not six.PY2: - contents = output.getvalue() - else: - contents = output.getvalue().decode('utf-8') - output.close() - clipboard = QApplication.clipboard() - clipboard.setText(contents) - - -class DataFrameDock(QDockWidget): - """The QDockWidget for the :class:`DataFrameEditor`""" - - def close(self): - """ - Reimplemented to remove the dock widget from the mainwindow when closed - """ - mainwindow = self.parent() - try: - mainwindow.dataframeeditors.remove(self.widget()) - except Exception: - pass - try: - mainwindow.removeDockWidget(self) - except Exception: - pass - if getattr(self.widget(), '_view_action', None) is not None: - mainwindow.dataframe_menu.removeAction(self.widget()._view_action) - return super(DataFrameDock, self).close() - - -class DataFrameEditor(DockMixin, QWidget): - """An editor for data frames""" - - dock_cls = DataFrameDock - - #: A signal that is emitted, if the table is cleared - cleared = QtCore.pyqtSignal() - - #: A signal that is emitted when a cell has been changed. The argument - #: is a tuple of two integers and one float: - #: the row index, the column index and the new value - cell_edited = QtCore.pyqtSignal(int, int, object, object) - - #: A signal that is emitted, if rows have been inserted into the dataframe. - #: The first value is the integer of the (original) position of the row, - #: the second one is the number of rows - rows_inserted = QtCore.pyqtSignal(int, int) - - @property - def hidden(self): - return not self.table.filled - - def __init__(self, *args, **kwargs): - super(DataFrameEditor, self).__init__(*args, **kwargs) - self.error_msg = PyErrorMessage(self) - - # Label for displaying the DataFrame size - self.lbl_size = QLabel() - - # A Checkbox for enabling and disabling the editability of the index - self.cb_index_editable = QCheckBox('Index editable') - - # A checkbox for enabling and disabling the change of data types - self.cb_dtypes_changeable = QCheckBox('Datatypes changeable') - - # A checkbox for enabling and disabling sorting - self.cb_enable_sort = QCheckBox('Enable sorting') - - # A button to open a dataframe from the file - self.btn_open_df = QToolButton(parent=self) - self.btn_open_df.setIcon(QIcon(get_icon('run_arrow.png'))) - self.btn_open_df.setToolTip('Open a DataFrame from your disk') - - self.btn_from_console = LoadFromConsoleButton(pd.DataFrame) - self.btn_from_console.setToolTip('Show a DataFrame from the console') - - # The table to display the DataFrame - self.table = DataFrameView(pd.DataFrame(), self) - - # format line edit - self.format_editor = QLineEdit() - self.format_editor.setText(self.table.model()._format) - - # format update button - self.btn_change_format = QPushButton('Update') - self.btn_change_format.setEnabled(False) - - # table clearing button - self.btn_clear = QPushButton('Clear') - self.btn_clear.setToolTip( - 'Clear the table and disconnect from the DataFrame') - - # refresh button - self.btn_refresh = QToolButton() - self.btn_refresh.setIcon(QIcon(get_icon('refresh.png'))) - self.btn_refresh.setToolTip('Refresh the table') - - # close button - self.btn_close = QPushButton('Close') - self.btn_close.setToolTip('Close this widget permanentely') - - # --------------------------------------------------------------------- - # ------------------------ layout -------------------------------- - # --------------------------------------------------------------------- - vbox = QVBoxLayout() - self.top_hbox = hbox = QHBoxLayout() - hbox.addWidget(self.cb_index_editable) - hbox.addWidget(self.cb_dtypes_changeable) - hbox.addWidget(self.cb_enable_sort) - hbox.addWidget(self.lbl_size) - hbox.addStretch(0) - hbox.addWidget(self.btn_open_df) - hbox.addWidget(self.btn_from_console) - vbox.addLayout(hbox) - vbox.addWidget(self.table) - self.bottom_hbox = hbox = QHBoxLayout() - hbox.addWidget(self.format_editor) - hbox.addWidget(self.btn_change_format) - hbox.addStretch(0) - hbox.addWidget(self.btn_clear) - hbox.addWidget(self.btn_close) - hbox.addWidget(self.btn_refresh) - vbox.addLayout(hbox) - self.setLayout(vbox) - - # --------------------------------------------------------------------- - # ------------------------ Connections -------------------------------- - # --------------------------------------------------------------------- - self.cb_dtypes_changeable.stateChanged.connect( - self.set_dtypes_changeable) - self.cb_index_editable.stateChanged.connect(self.set_index_editable) - self.btn_from_console.object_loaded.connect(self._open_ds_from_console) - self.rows_inserted.connect(lambda i, n: self.set_lbl_size_text()) - self.format_editor.textChanged.connect(self.toggle_fmt_button) - self.btn_change_format.clicked.connect(self.update_format) - self.btn_clear.clicked.connect(self.clear_table) - self.btn_close.clicked.connect(self.clear_table) - self.btn_close.clicked.connect(lambda: self.close()) - self.btn_refresh.clicked.connect(self.table.reset_model) - self.btn_open_df.clicked.connect(self._open_dataframe) - self.table.set_index_action.triggered.connect( - self.update_index_editable) - self.table.append_index_action.triggered.connect( - self.update_index_editable) - self.cb_enable_sort.stateChanged.connect( - self.table.setSortingEnabled) - - def update_index_editable(self): - model = self.table.model() - if len(model.df.index.names) > 1: - model.index_editable = False - self.cb_index_editable.setEnabled(False) - self.cb_index_editable.setChecked(model.index_editable) - - def set_lbl_size_text(self, nrows=None, ncols=None): - """Set the text of the :attr:`lbl_size` label to display the size""" - model = self.table.model() - nrows = nrows if nrows is not None else model.rowCount() - ncols = ncols if ncols is not None else model.columnCount() - if not nrows and not ncols: - self.lbl_size.setText('') - else: - self.lbl_size.setText('Rows: %i, Columns: %i' % (nrows, ncols)) - - def clear_table(self): - """Clear the table and emit the :attr:`cleared` signal""" - df = pd.DataFrame() - self.set_df(df, show=False) - - def _open_ds_from_console(self, oname, df): - self.set_df(df) - - @docstrings.dedent - def set_df(self, df, *args, **kwargs): - """ - Fill the table from a :class:`~pandas.DataFrame` - - Parameters - ---------- - %(DataFrameModel.parameters.no_parent)s - show: bool - If True (default), show and raise_ the editor - """ - show = kwargs.pop('show', True) - self.table.set_df(df, *args, **kwargs) - self.set_lbl_size_text(*df.shape) - model = self.table.model() - self.cb_dtypes_changeable.setChecked(model.dtypes_changeable) - - if len(model.df.index.names) > 1: - model.index_editable = False - self.cb_index_editable.setEnabled(False) - else: - self.cb_index_editable.setEnabled(True) - self.cb_index_editable.setChecked(model.index_editable) - self.cleared.emit() - if show: - self.show_plugin() - self.dock.raise_() - - def set_index_editable(self, state): - """Set the :attr:`DataFrameModel.index_editable` attribute""" - self.table.model().index_editable = state == Qt.Checked - - def set_dtypes_changeable(self, state): - """Set the :attr:`DataFrameModel.dtypes_changeable` attribute""" - self.table.model().dtypes_changeable = state == Qt.Checked - - def toggle_fmt_button(self, text): - try: - text % 1.1 - except (TypeError, ValueError): - self.btn_change_format.setEnabled(False) - else: - self.btn_change_format.setEnabled( - text.strip() != self.table.model()._format) - - def update_format(self): - """Update the format of the table""" - self.table.model().set_format(self.format_editor.text().strip()) - - def to_dock(self, main, *args, **kwargs): - connect = self.dock is None - super(DataFrameEditor, self).to_dock(main, *args, **kwargs) - if connect: - self.dock.toggleViewAction().triggered.connect(self.maybe_tabify) - - def maybe_tabify(self): - main = self.dock.parent() - if self.is_shown and main.dockWidgetArea( - main.help_explorer.dock) == main.dockWidgetArea(self.dock): - main.tabifyDockWidget(main.help_explorer.dock, self.dock) - - def _open_dataframe(self): - self.open_dataframe() - - def open_dataframe(self, fname=None, *args, **kwargs): - """Opens a file dialog and the dataset that has been inserted""" - if fname is None: - fname = QFileDialog.getOpenFileName( - self, 'Open dataset', os.getcwd(), - 'Comma separated files (*.csv);;' - 'Excel files (*.xls *.xlsx);;' - 'JSON files (*.json);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fname = fname[0] - if isinstance(fname, pd.DataFrame): - self.set_df(fname) - elif not fname: - return - else: - ext = osp.splitext(fname)[1] - open_funcs = { - '.xls': pd.read_excel, '.xlsx': pd.read_excel, - '.json': pd.read_json, - '.tab': partial(pd.read_csv, delimiter='\t'), - '.dat': partial(pd.read_csv, delim_whitespace=True), - } - open_func = open_funcs.get(ext, pd.read_csv) - try: - df = open_func(fname) - except Exception: - self.error_msg.showTraceback( - 'Could not open DataFrame %s with %s' % ( - fname, open_func)) - return - self.set_df(df) - - def close(self, *args, **kwargs): - if self.dock is not None: - self.dock.close(*args, **kwargs) # removes the dock window - del self.dock - return super(DataFrameEditor, self).close(*args, **kwargs) diff --git a/psyplot_gui/dependencies.py b/psyplot_gui/dependencies.py deleted file mode 100644 index 11345b3..0000000 --- a/psyplot_gui/dependencies.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Dependencies widget of the psyplot package - -This module defines the :class:`DependenciesWidget` that shows the versions of -of psyplot, psyplot_gui, psyplot plugins and their requirements""" -from psyplot_gui.compat.qtcompat import ( - QDialog, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QLabel, QMenu, QAction, - Qt, QApplication, QMessageBox, QPushButton, QHBoxLayout, QAbstractItemView, - QDialogButtonBox, QtCore) -from psyplot.docstring import docstrings - - -class DependenciesTree(QTreeWidget): - """A tree widget to display dependencies - - This widget uses a dictionary as created through the - :func:`psyplot.get_versions` function to display the requirements and - versions.""" - - @docstrings.get_sections(base='DependenciesTree') - def __init__(self, versions, *args, **kwargs): - """ - Parameters - ---------- - versions: dict - The dictionary that contains the version information - - See Also - -------- - psyplot.get_versions - """ - super(DependenciesTree, self).__init__(*args, **kwargs) - self.resizeColumnToContents(0) - self.setColumnCount(2) - self.setHeaderLabels(['Package', 'installed version']) - self.add_dependencies(versions) - self.expandAll() - self.resizeColumnToContents(0) - self.setContextMenuPolicy(Qt.CustomContextMenu) - self.customContextMenuRequested.connect(self.open_menu) - - @docstrings.dedent - def add_dependencies(self, versions, parent=None): - """ - Add the version informations to the tree - - This method creates an QTreeWidgetItem for each package in `versions` - and adds it to this tree. - - Parameters - ---------- - %(DependenciesTree.parameters)s - parent: QTreeWidgetItem - The parent of the newly created items for the packages in - `versions`. If None, the newly created items are inserted as - top level items into the tree - """ - for pkg, pkg_d in versions.items(): - new_item = QTreeWidgetItem(0) - new_item.setText(0, pkg) - if isinstance(pkg_d, dict): - new_item.setText(1, pkg_d['version']) - else: - new_item.setText(1, pkg_d) - if parent is None: - self.addTopLevelItem(new_item) - else: - parent.addChild(new_item) - if 'requirements' in pkg_d: - self.add_dependencies(pkg_d['requirements'], new_item) - - def open_menu(self, position): - """Open a menu to expand and collapse all items in the tree - - Parameters - ---------- - position: QPosition - The position where to open the menu""" - menu = QMenu() - expand_all_action = QAction('Expand all', self) - expand_all_action.triggered.connect(self.expandAll) - menu.addAction(expand_all_action) - collapse_all_action = QAction('Collapse all', self) - collapse_all_action.triggered.connect(self.collapseAll) - menu.addAction(collapse_all_action) - menu.exec_(self.viewport().mapToGlobal(position)) - - -class DependenciesDialog(QDialog): - """A dialog for displaying the dependencies""" - - #: description label - label = None - - #: the QVBoxLayout containing all the widgets - vbox = None - - #: The :class:`DependenciesTree` that contains the package infos - tree = None - - #: The QPushButton used for copying selected packages to the clipboard - bt_copy = None - - #: A simple info label for info messages - info_label = None - - #: A QTimer that clears the :attr:`info_label` after some time - timer = None - - @docstrings.dedent - def __init__(self, versions, *args, **kwargs): - """ - Parameters - ---------- - %(DependenciesTree.parameters)s - """ - super(DependenciesDialog, self).__init__(*args, **kwargs) - self.setWindowTitle('Dependencies') - self.versions = versions - self.vbox = layout = QVBoxLayout() - - self.label = QLabel(""" - psyplot and the plugins depend on several python libraries. The - tree widget below lists the versions of the plugins and the - requirements. You can select the items in the tree and copy them to - clipboard.""", parent=self) - - layout.addWidget(self.label) - - self.tree = DependenciesTree(versions, parent=self) - self.tree.setSelectionMode(QAbstractItemView.MultiSelection) - layout.addWidget(self.tree) - - # copy button - self.bt_copy = QPushButton('Copy selection to clipboard') - self.bt_copy.setToolTip( - 'Copy the selected packages in the above table to the clipboard.') - self.bt_copy.clicked.connect(lambda: self.copy_selected()) - - self.bbox = QDialogButtonBox(QDialogButtonBox.Ok) - self.bbox.accepted.connect(self.accept) - - hbox = QHBoxLayout() - hbox.addWidget(self.bt_copy) - hbox.addStretch(1) - hbox.addWidget(self.bbox) - layout.addLayout(hbox) - - #: A label for simple status update - self.info_label = QLabel('', self) - layout.addWidget(self.info_label) - self.timer = QtCore.QTimer(self) - self.timer.timeout.connect(self.clear_label) - - self.setLayout(layout) - - def copy_selected(self, label=None): - """Copy the selected versions and items to the clipboard""" - d = {} - items = self.tree.selectedItems() - if not items: - QMessageBox.warning(self, "No packages selected!", - "Please select packages in the tree!") - return - for item in items: - d[item.text(0)] = item.text(1) - if label is None: - label = QApplication.clipboard() - label.setText("\n".join( - '%s: %s' % t for t in d.items())) - self.info_label.setText('Packages copied to clipboard.') - self.timer.start(3000) - - def clear_label(self): - """Clear the info label""" - self.info_label.setText('') diff --git a/psyplot_gui/fmt_widget.py b/psyplot_gui/fmt_widget.py deleted file mode 100644 index 2416868..0000000 --- a/psyplot_gui/fmt_widget.py +++ /dev/null @@ -1,652 +0,0 @@ -# -*- coding: utf-8 -*- -"""Module defining a widget for updating the formatoption of the current -project""" -import six -import yaml -from functools import partial -from collections import defaultdict -from itertools import chain -import logging -from warnings import warn -from IPython.core.interactiveshell import ExecutionResult -import psyplot.project as psy -from psyplot.utils import _temp_bool_prop, unique_everseen -from psyplot_gui.compat.qtcompat import ( - QWidget, QHBoxLayout, QComboBox, QLineEdit, QVBoxLayout, QToolButton, - QIcon, QPushButton, QCheckBox, QTextEdit, QListView, QCompleter, Qt, - QStandardItemModel, QStandardItem, with_qt5) -from psyplot_gui.plot_creator import CoordComboBox -from psyplot_gui.config.rcsetup import rcParams -from psyplot.compat.pycompat import OrderedDict, map -from psyplot_gui.common import DockMixin, get_icon, PyErrorMessage -from psyplot.data import safe_list -import psyplot.plotter as psyp -from psyplot.data import isstring - -try: - from IPython.core.interactiveshell import ExecutionInfo -except ImportError: - ExecutionInfo = None - - -logger = logging.getLogger(__name__) - - -COORDSGROUP = '__coords' -ALLGROUP = '__all' - - -class DimensionsWidget(QWidget): - """A widget for updating the dimensions""" - - def __init__(self, parent, dim=None): - super(DimensionsWidget, self).__init__(parent) - self.coord_combo = CoordComboBox(self.get_ds, dim) - self.cb_use_coord = QCheckBox('show coordinates') - self.cb_close_popups = QCheckBox('close dropdowns') - self.cb_close_popups.setChecked(True) - self.toggle_close_popup() - self._single_selection = False - - self.dim = dim - hbox = QHBoxLayout() - hbox.addWidget(self.cb_close_popups) - hbox.addWidget(self.cb_use_coord) - hbox.addWidget(self.coord_combo) - self.setLayout(hbox) - self.cb_use_coord.stateChanged.connect(self.reset_combobox) - self.cb_close_popups.stateChanged.connect(self.toggle_close_popup) - self.coord_combo.leftclick.connect(self.insert_from_combo) - - def set_dim(self, dim): - self.dim = self.coord_combo.dim = dim - - def slice2list(self, sl): - if not isinstance(sl, slice): - return sl - return list(range(*sl.indices(self.coord_combo.count() - 1))) - - def reset_combobox(self): - """Clear all comboboxes""" - self.coord_combo.use_coords = self.cb_use_coord.isChecked() - self.coord_combo.clear() - self.coord_combo._is_empty = True - - def toggle_close_popup(self): - self.coord_combo.close_popups = self.cb_close_popups.isChecked() - - def insert_from_combo(self): - cb = self.coord_combo - inserts = list( - ind.row() - 1 - for ind in cb.view().selectionModel().selectedIndexes() - if ind.row() > 0) - if not inserts: - return - elif not self._single_selection: - try: - current = yaml.load(self.parent().get_text(), - Loader=yaml.Loader) - except Exception: - pass - else: - if current: - current = self.slice2list(current) - inserts = sorted(set(chain(inserts, safe_list(current)))) - else: - inserts = inserts[0] - - self.parent().set_obj(inserts) - - def get_ds(self): - import psyplot.project as psy - project = psy.gcp() - datasets = project.datasets - dim = self.dim - dims = {ds.coords[dim].shape[0]: ds for ds in datasets.values()} - if len(dims) > 1: - warn("Datasets have differing dimensions lengths for the " - "%s dimension!" % dim) - return min(dims.items())[1] - - def set_single_selection(self, yes=True): - self._single_selection = yes - if yes: - self.coord_combo.view().setSelectionMode( - QListView.SingleSelection) - else: - self.coord_combo.view().setSelectionMode( - QListView.ExtendedSelection) - - -class FormatoptionWidget(QWidget, DockMixin): - """ - Widget to update the formatoptions of the current project - - This widget, mainly made out of a combobox for the formatoption group, - a combobox for the formatoption, and a text editor, is designed - for updating the selected formatoptions for the current subproject. - - The widget is connected to the :attr:`psyplot.project.Project.oncpchange` - signal and refills the comboboxes if the current subproject changes. - - The text editor either accepts python code that will be executed by the - given `console`, or yaml code. - """ - - no_fmtos_update = _temp_bool_prop( - 'no_fmtos_update', """update the fmto combo box or not""") - - #: The combobox for the formatoption groups - group_combo = None - - #: The combobox for the formatoptions - fmt_combo = None - - #: The help_explorer to display the documentation of the formatoptions - help_explorer = None - - #: The formatoption specific widget that is loaded from the formatoption - fmt_widget = None - - #: A line edit for updating the formatoptions - line_edit = None - - #: A multiline text editor for updating the formatoptions - text_edit = None - - #: A button to switch between :attr:`line_edit` and :attr:`text_edit` - multiline_button = None - - @property - def shell(self): - """The shell to execute the update of the formatoptions in the current - project""" - return self.console.kernel_manager.kernel.shell - - def __init__(self, *args, **kwargs): - """ - Parameters - ---------- - help_explorer: psyplot_gui.help_explorer.HelpExplorer - The help explorer to show the documentation of one formatoption - console: psyplot_gui.console.ConsoleWidget - The console that can be used to update the current subproject via:: - - psy.gcp().update(**kwargs) - - where ``**kwargs`` is defined through the selected formatoption - in the :attr:`fmt_combo` combobox and the value in the - :attr:`line_edit` editor - ``*args, **kwargs`` - Any other keyword for the QWidget class - """ - help_explorer = kwargs.pop('help_explorer', None) - console = kwargs.pop('console', None) - super(FormatoptionWidget, self).__init__(*args, **kwargs) - self.help_explorer = help_explorer - self.console = console - self.error_msg = PyErrorMessage(self) - - # --------------------------------------------------------------------- - # -------------------------- Child widgets ---------------------------- - # --------------------------------------------------------------------- - self.group_combo = QComboBox(parent=self) - self.fmt_combo = QComboBox(parent=self) - self.line_edit = QLineEdit(parent=self) - self.text_edit = QTextEdit(parent=self) - self.run_button = QToolButton(parent=self) - - # completer for the fmto widget - self.fmt_combo.setEditable(True) - self.fmt_combo.setInsertPolicy(QComboBox.NoInsert) - self.fmto_completer = completer = QCompleter( - ['time', 'lat', 'lon', 'lev']) - completer.setCompletionMode( - QCompleter.PopupCompletion) - completer.activated[str].connect(self.set_fmto) - if with_qt5: - completer.setFilterMode(Qt.MatchContains) - completer.setModel(QStandardItemModel()) - self.fmt_combo.setCompleter(completer) - - self.dim_widget = DimensionsWidget(parent=self) - self.dim_widget.setVisible(False) - - self.multiline_button = QPushButton('Multiline', parent=self) - self.multiline_button.setCheckable(True) - - self.yaml_cb = QCheckBox('Yaml syntax') - self.yaml_cb.setChecked(True) - - self.keys_button = QPushButton('Keys', parent=self) - self.summaries_button = QPushButton('Summaries', parent=self) - self.docs_button = QPushButton('Docs', parent=self) - - self.grouped_cb = QCheckBox('grouped', parent=self) - self.all_groups_cb = QCheckBox('all groups', parent=self) - self.include_links_cb = QCheckBox('include links', parent=self) - - self.text_edit.setVisible(False) - - # --------------------------------------------------------------------- - # -------------------------- Descriptions ----------------------------- - # --------------------------------------------------------------------- - - self.group_combo.setToolTip('Select the formatoption group') - self.fmt_combo.setToolTip('Select the formatoption to update') - self.line_edit.setToolTip( - 'Insert the value which what you want to update the selected ' - 'formatoption and hit right button. The code is executed in the ' - 'main console.') - self.yaml_cb.setToolTip( - "Use the yaml syntax for the values inserted in the above cell. " - "Otherwise the content there is evaluated as a python expression " - "in the terminal") - self.text_edit.setToolTip(self.line_edit.toolTip()) - self.run_button.setIcon(QIcon(get_icon('run_arrow.png'))) - self.run_button.setToolTip('Update the selected formatoption') - self.multiline_button.setToolTip( - 'Allow linebreaks in the text editor line above.') - self.keys_button.setToolTip( - 'Show the formatoption keys in this group (or in all ' - 'groups) in the help explorer') - self.summaries_button.setToolTip( - 'Show the formatoption summaries in this group (or in all ' - 'groups) in the help explorer') - self.docs_button.setToolTip( - 'Show the formatoption documentations in this group (or in all ' - 'groups) in the help explorer') - self.grouped_cb.setToolTip( - 'Group the formatoptions before displaying them in the help ' - 'explorer') - self.all_groups_cb.setToolTip('Use all groups when displaying the ' - 'keys, docs or summaries') - self.include_links_cb.setToolTip( - 'Include links to remote documentations when showing the ' - 'keys, docs and summaries in the help explorer (requires ' - 'intersphinx)') - - # --------------------------------------------------------------------- - # -------------------------- Connections ------------------------------ - # --------------------------------------------------------------------- - self.group_combo.currentIndexChanged[int].connect(self.fill_fmt_combo) - self.fmt_combo.currentIndexChanged[int].connect(self.show_fmt_info) - self.fmt_combo.currentIndexChanged[int].connect(self.load_fmt_widget) - self.fmt_combo.currentIndexChanged[int].connect( - self.set_current_fmt_value) - self.run_button.clicked.connect(self.run_code) - self.line_edit.returnPressed.connect(self.run_button.click) - self.multiline_button.clicked.connect(self.toggle_line_edit) - self.keys_button.clicked.connect( - partial(self.show_all_fmt_info, 'keys')) - self.summaries_button.clicked.connect( - partial(self.show_all_fmt_info, 'summaries')) - self.docs_button.clicked.connect( - partial(self.show_all_fmt_info, 'docs')) - - # --------------------------------------------------------------------- - # ------------------------------ Layouts ------------------------------ - # --------------------------------------------------------------------- - self.combos = QHBoxLayout() - self.combos.addWidget(self.group_combo) - self.combos.addWidget(self.fmt_combo) - - self.execs = QHBoxLayout() - self.execs.addWidget(self.line_edit) - self.execs.addWidget(self.text_edit) - self.execs.addWidget(self.run_button) - - self.info_box = QHBoxLayout() - self.info_box.addWidget(self.multiline_button) - self.info_box.addWidget(self.yaml_cb) - self.info_box.addStretch(0) - for w in [self.keys_button, self.summaries_button, self.docs_button, - self.all_groups_cb, self.grouped_cb, self.include_links_cb]: - self.info_box.addWidget(w) - - self.vbox = QVBoxLayout() - self.vbox.addLayout(self.combos) - self.vbox.addWidget(self.dim_widget) - self.vbox.addLayout(self.execs) - self.vbox.addLayout(self.info_box) - - self.vbox.setSpacing(0) - - self.setLayout(self.vbox) - - # fill with content - self.fill_combos_from_project(psy.gcp()) - psy.Project.oncpchange.connect(self.fill_combos_from_project) - rcParams.connect('fmt.sort_by_key', self.refill_from_rc) - - def refill_from_rc(self, sort_by_key): - from psyplot.project import gcp - self.fill_combos_from_project(gcp()) - - def fill_combos_from_project(self, project): - """Fill :attr:`group_combo` and :attr:`fmt_combo` from a project - - Parameters - ---------- - project: psyplot.project.Project - The project to use""" - if rcParams['fmt.sort_by_key']: - def sorter(fmto): - return fmto.key - else: - sorter = self.get_name - - current_text = self.group_combo.currentText() - with self.no_fmtos_update: - self.group_combo.clear() - if project is None or project.is_main or not len(project): - self.fmt_combo.clear() - self.groups = [] - self.fmtos = [] - self.line_edit.setEnabled(False) - return - self.line_edit.setEnabled(True) - # get dimensions - it_vars = chain.from_iterable( - arr.psy.iter_base_variables for arr in project.arrays) - dims = next(it_vars).dims - sdims = set(dims) - for var in it_vars: - sdims.intersection_update(var.dims) - coords = [d for d in dims if d in sdims] - coords_name = [COORDSGROUP] if coords else [] - coords_verbose = ['Dimensions'] if coords else [] - coords = [coords] if coords else [] - - if len(project.plotters): - # get formatoptions and group them alphabetically - grouped_fmts = defaultdict(list) - for fmto in project._fmtos: - grouped_fmts[fmto.group].append(fmto) - for val in six.itervalues(grouped_fmts): - val.sort(key=sorter) - grouped_fmts = OrderedDict( - sorted(six.iteritems(grouped_fmts), - key=lambda t: psyp.groups.get(t[0], t[0]))) - fmt_groups = list(grouped_fmts.keys()) - # save original names - self.groups = coords_name + [ALLGROUP] + fmt_groups - # save verbose group names (which are used in the combo box) - self.groupnames = ( - coords_verbose + ['All formatoptions'] + list( - map(lambda s: psyp.groups.get(s, s), fmt_groups))) - # save formatoptions - fmtos = list(grouped_fmts.values()) - self.fmtos = coords + [sorted( - chain(*fmtos), key=sorter)] + fmtos - else: - self.groups = coords_name - self.groupnames = coords_verbose - self.fmtos = coords - self.group_combo.addItems(self.groupnames) - ind = self.group_combo.findText(current_text) - self.group_combo.setCurrentIndex(ind if ind >= 0 else 0) - self.fill_fmt_combo(self.group_combo.currentIndex()) - - def get_name(self, fmto): - """Get the name of a :class:`psyplot.plotter.Formatoption` instance""" - if isinstance(fmto, six.string_types): - return fmto - return '%s (%s)' % (fmto.name, fmto.key) if fmto.name else fmto.key - - @property - def fmto(self): - return self.fmtos[self.group_combo.currentIndex()][ - self.fmt_combo.currentIndex()] - - @fmto.setter - def fmto(self, value): - name = self.get_name(value) - for i, fmtos in enumerate(self.fmtos): - if i == 1: # all formatoptions - continue - if name in map(self.get_name, fmtos): - with self.no_fmtos_update: - self.group_combo.setCurrentIndex(i) - self.fill_fmt_combo(i, name) - return - - def toggle_line_edit(self): - """Switch between the :attr:`line_edit` and :attr:`text_edit` - - This method is called when the :attr:`multiline_button` is clicked - and switches between the single line :attr:``line_edit` and the - multiline :attr:`text_edit` - """ - # switch to multiline text edit - if (self.multiline_button.isChecked() and - not self.text_edit.isVisible()): - self.line_edit.setVisible(False) - self.text_edit.setVisible(True) - self.text_edit.setPlainText(self.line_edit.text()) - elif (not self.multiline_button.isChecked() and - not self.line_edit.isVisible()): - self.line_edit.setVisible(True) - self.text_edit.setVisible(False) - self.line_edit.setText(self.text_edit.toPlainText()) - - def fill_fmt_combo(self, i, current_text=None): - """Fill the :attr:`fmt_combo` combobox based on the current group name - """ - if not self.no_fmtos_update: - with self.no_fmtos_update: - if current_text is None: - current_text = self.fmt_combo.currentText() - self.fmt_combo.clear() - self.fmt_combo.addItems( - list(map(self.get_name, self.fmtos[i]))) - ind = self.fmt_combo.findText(current_text) - self.fmt_combo.setCurrentIndex(ind if ind >= 0 else 0) - # update completer model - self.setup_fmt_completion_model() - idx = self.fmt_combo.currentIndex() - self.show_fmt_info(idx) - self.load_fmt_widget(idx) - self.set_current_fmt_value(idx) - - def set_fmto(self, name): - self.fmto = name - - def setup_fmt_completion_model(self): - fmtos = list(unique_everseen(map( - self.get_name, chain.from_iterable(self.fmtos)))) - model = self.fmto_completer.model() - model.setRowCount(len(fmtos)) - for i, name in enumerate(fmtos): - model.setItem(i, QStandardItem(name)) - - def load_fmt_widget(self, i): - """Load the formatoption specific widget - - This method loads the formatoption specific widget from the - :meth:`psyplot.plotter.Formatoption.get_fmt_widget` method and - displays it above the :attr:`line_edit` - - Parameters - ---------- - i: int - The index of the current formatoption""" - self.remove_fmt_widget() - group_ind = self.group_combo.currentIndex() - if not self.no_fmtos_update: - from psyplot.project import gcp - if self.groups[group_ind] == COORDSGROUP: - dim = self.fmtos[group_ind][i] - self.fmt_widget = self.dim_widget - self.dim_widget.set_dim(dim) - self.dim_widget.set_single_selection( - dim not in gcp()[0].dims) - self.dim_widget.setVisible(True) - else: - fmto = self.fmtos[group_ind][i] - self.fmt_widget = fmto.get_fmt_widget(self, gcp()) - if self.fmt_widget is not None: - self.vbox.insertWidget(2, self.fmt_widget) - - def reset_fmt_widget(self): - idx = self.fmt_combo.currentIndex() - self.load_fmt_widget(idx) - self.set_current_fmt_value(idx) - - def remove_fmt_widget(self): - if self.fmt_widget is not None: - self.fmt_widget.hide() - if self.fmt_widget is self.dim_widget: - self.fmt_widget.reset_combobox() - else: - self.vbox.removeWidget(self.fmt_widget) - self.fmt_widget.close() - del self.fmt_widget - - def set_current_fmt_value(self, i): - """Add the value of the current formatoption to the line text""" - group_ind = self.group_combo.currentIndex() - if not self.no_fmtos_update: - if self.groups[group_ind] == COORDSGROUP: - from psyplot.project import gcp - dim = self.fmtos[group_ind][i] - self.set_obj(gcp().arrays[0].psy.idims[dim]) - else: - fmto = self.fmtos[group_ind][i] - self.set_obj(fmto.value) - - def show_fmt_info(self, i): - """Show the documentation of the formatoption in the help explorer - """ - group_ind = self.group_combo.currentIndex() - if (not self.no_fmtos_update and - self.groups[group_ind] != COORDSGROUP): - fmto = self.fmtos[self.group_combo.currentIndex()][i] - fmto.plotter.show_docs( - fmto.key, include_links=self.include_links_cb.isChecked()) - - def run_code(self): - """Run the update of the project inside the :attr:`shell`""" - if self.line_edit.isVisible(): - text = str(self.line_edit.text()) - else: - text = str(self.text_edit.toPlainText()) - if not text or not self.fmtos: - return - group_ind = self.group_combo.currentIndex() - if self.groups[group_ind] == COORDSGROUP: - key = self.fmtos[group_ind][self.fmt_combo.currentIndex()] - param = 'dims' - else: - key = self.fmtos[group_ind][self.fmt_combo.currentIndex()].key - param = 'fmt' - if self.yaml_cb.isChecked(): - import psyplot.project as psy - psy.gcp().update(**{key: yaml.load(text, Loader=yaml.Loader)}) - else: - code = "psy.gcp().update(%s={'%s': %s})" % (param, key, text) - if ExecutionInfo is not None: - info = ExecutionInfo(raw_cell=code, store_history=False, - silent=True, shell_futures=False) - e = ExecutionResult(info) - else: - e = ExecutionResult() - self.console.run_command_in_shell(code, e) - try: - e.raise_error() - except Exception: # reset the console and clear the error message - raise - finally: - self.console.reset() - - def get_text(self): - """Get the current update text""" - if self.line_edit.isVisible(): - return self.line_edit.text() - else: - return self.text_edit.toPlainText() - - def get_obj(self): - """Get the current update text""" - if self.line_edit.isVisible(): - txt = self.line_edit.text() - else: - txt = self.text_edit.toPlainText() - try: - obj = yaml.load(txt, Loader=yaml.Loader) - except Exception: - self.error_msg.showTraceback("Could not load %s" % txt) - else: - return obj - - def insert_obj(self, obj): - """Add a string to the formatoption widget""" - current = self.get_text() - use_yaml = self.yaml_cb.isChecked() - use_line_edit = self.line_edit.isVisible() - # strings are treated separately such that we consider quotation marks - # at the borders - if isstring(obj) and current: - if use_line_edit: - pos = self.line_edit.cursorPosition() - else: - pos = self.text_edit.textCursor().position() - if pos not in [0, len(current)]: - s = obj - else: - if current[0] in ['"', "'"]: - current = current[1:-1] - self.clear_text() - if pos == 0: - s = '"' + obj + current + '"' - else: - s = '"' + current + obj + '"' - current = '' - elif isstring(obj): # add quotation marks - s = '"' + obj + '"' - elif not use_yaml: - s = repr(obj) - else: - s = yaml.dump(obj, default_flow_style=True).strip() - if s.endswith('\n...'): - s = s[:-4] - if use_line_edit: - self.line_edit.insert(s) - else: - self.text_edit.insertPlainText(s) - - def clear_text(self): - if self.line_edit.isVisible(): - self.line_edit.clear() - else: - self.text_edit.clear() - - def set_obj(self, obj): - self.clear_text() - self.insert_obj(obj) - - def show_all_fmt_info(self, what): - """Show the keys, summaries or docs of the formatoptions - - Calling this function let's the help browser show the documentation - etc. of all docs or only the selected group determined by the state of - the :attr:`grouped_cb` and :attr:`all_groups_cb` checkboxes - - Parameters - ---------- - what: {'keys', 'summaries', 'docs'} - Determines what to show""" - if not self.fmtos: - return - if (self.all_groups_cb.isChecked() or - self.group_combo.currentIndex() < 2): - fmtos = list(chain.from_iterable( - fmto_group for i, fmto_group in enumerate(self.fmtos) - if self.groups[i] not in [ALLGROUP, COORDSGROUP])) - else: - fmtos = self.fmtos[self.group_combo.currentIndex()] - plotter = fmtos[0].plotter - getattr(plotter, 'show_' + what)( - [fmto.key for fmto in fmtos], grouped=self.grouped_cb.isChecked(), - include_links=self.include_links_cb.isChecked()) diff --git a/psyplot_gui/help_explorer.py b/psyplot_gui/help_explorer.py deleted file mode 100644 index 8d2c719..0000000 --- a/psyplot_gui/help_explorer.py +++ /dev/null @@ -1,1077 +0,0 @@ -# -*- coding: utf-8 -*- -"""Help explorer widget supplying a simple web browser and a plain text help -viewer""" -import sys -import os.path as osp -from collections import namedtuple -from itertools import chain -import re -import six -import types -import inspect -import shutil -from psyplot.docstring import indent, docstrings -from psyplot.compat.pycompat import OrderedDict -from psyplot.utils import _temp_bool_prop -from psyplot_gui.config.rcsetup import rcParams -from psyplot_gui.compat.qtcompat import ( - QWidget, QHBoxLayout, QFrame, QVBoxLayout, QWebEngineView, QToolButton, - QIcon, QtCore, QComboBox, Qt, QSortFilterProxyModel, isstring, asstring, - QCompleter, QStandardItemModel, QPlainTextEdit, QAction, QMenu, with_qt5, - QtGui) -from psyplot_gui.common import get_icon, DockMixin, PyErrorMessage -from IPython.core.oinspect import signature, getdoc -import logging -from psyplot_gui.common import get_module_path, StreamToLogger, \ - is_running_tests -from tempfile import mkdtemp -try: - from sphinx.application import Sphinx - from sphinx.pycode import ModuleAnalyzer - try: - from psyplot.sphinxext.extended_napoleon import ( - ExtendedNumpyDocstring as NumpyDocstring, - ExtendedGoogleDocstring as GoogleDocstring) - except ImportError: - from sphinx.ext.napoleon import NumpyDocstring, GoogleDocstring - with_sphinx = True -except ImportError: - with_sphinx = False - -if six.PY2: - from urlparse import urlparse -else: - from urllib.parse import urlparse - - -try: - import pathlib - - def file2html(fname): - return pathlib.Path(fname).as_uri() - -except ImportError: - - def file2html(fname): - return 'file://' + fname - - -def html2file(url): - p = urlparse(asstring(url)) - # skip the first '/' on windows platform - return osp.abspath(osp.join(p.netloc, - p.path[int(sys.platform == 'win32'):])) - - -_viewers = OrderedDict() - - -logger = logging.getLogger(__name__) - - -class UrlCombo(QComboBox): - """A editable ComboBox with autocompletion""" - - def __init__(self, *args, **kwargs): - super(UrlCombo, self).__init__(*args, **kwargs) - self.setInsertPolicy(self.InsertAtTop) - self.setFocusPolicy(Qt.StrongFocus) - self.setEditable(True) - self.completer = QCompleter(self) - - # always show all completions - self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) - self.pFilterModel = QSortFilterProxyModel(self) - self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) - - self.completer.setPopup(self.completer.popup()) - - self.setCompleter(self.completer) - - self.lineEdit().textEdited[str].connect( - self.pFilterModel.setFilterFixedString) - self.completer.activated.connect(self.add_text_on_top) - self.setModel(QStandardItemModel()) - - def setModel(self, model): - """Reimplemented to also set the model of the filter and completer""" - super(UrlCombo, self).setModel(model) - self.pFilterModel.setSourceModel(model) - self.completer.setModel(self.pFilterModel) - - def add_text_on_top(self, text=None, block=False): - """Add the given text as the first item""" - if text is None: - text = self.currentText() - ind = self.findText(text) - if block: - self.blockSignals(True) - if ind == -1: - self.insertItem(0, text) - elif ind != 0: - self.removeItem(ind) - self.insertItem(0, text) - self.setCurrentIndex(0) - if block: - self.blockSignals(False) - - # replace keyPressEvent to always insert the selected item at the top - def keyPressEvent(self, event): - """Handle key press events""" - if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: - self.add_text_on_top() - else: - QComboBox.keyPressEvent(self, event) - - -class UrlBrowser(QFrame): - """Very simple browser with session history and autocompletion based upon - the :class:`PyQt5.QtWebEngineWidgets.QWebEngineView` class - - Warnings - -------- - This class is known to crash under PyQt4 when new web page domains are - loaded. Hence it should be handled with care""" - - completed = _temp_bool_prop( - 'completed', "Boolean whether the html page loading is completed.", - default=True) - - url_like_re = re.compile('^\w+://') - - doc_urls = OrderedDict([ - ('startpage', 'https://startpage.com/'), - ('psyplot', 'http://psyplot.readthedocs.org/en/latest/'), - ('pyplot', 'http://matplotlib.org/api/pyplot_api.html'), - ('seaborn', 'http://stanford.edu/~mwaskom/software/seaborn/api.html'), - ('cartopy', 'http://scitools.org.uk/cartopy/docs/latest/index.html'), - ('xarray', 'http://xarray.pydata.org/en/stable/'), - ('pandas', 'http://pandas.pydata.org/pandas-docs/stable/'), - ('numpy', 'https://docs.scipy.org/doc/numpy/reference/routines.html'), - ]) - - #: The initial url showed in the webview. If None, nothing will be - #: displayed - default_url = None - - #: adress line - tb_url = None - - #: button to go to previous url - bt_back = None - - #: button to go to next url - bt_ahead = None - - #: refresh the current url - bt_refresh = None - - #: button to go lock to the current url - bt_lock = None - - #: button to disable browsing in www - bt_url_lock = None - - #: The upper part of the browser containing all the buttons - button_box = None - - #: The upper most layout aranging the button box and the html widget - vbox = None - - #: default value for :attr:`bt_lock`. Is set during browser - #: initialization - bt_lock_default = None - - #: default value for :attr:`bt_url_lock`. Is set during browser - #: initialization - bt_url_lock_default = None - - def __init__(self, *args, **kwargs): - super(UrlBrowser, self).__init__(*args, **kwargs) - - # --------------------------------------------------------------------- - # ---------------------------- upper buttons -------------------------- - # --------------------------------------------------------------------- - # adress line - self.tb_url = UrlCombo(self) - # button to go to previous url - self.bt_back = QToolButton(self) - # button to go to next url - self.bt_ahead = QToolButton(self) - # refresh the current url - self.bt_refresh = QToolButton(self) - # button to go lock to the current url - self.bt_lock = QToolButton(self) - # button to disable browsing in www - self.bt_url_lock = QToolButton(self) - - # ---------------------------- buttons settings ----------------------- - self.bt_back.setIcon(QIcon(get_icon('previous.png'))) - self.bt_back.setToolTip('Go back one page') - self.bt_ahead.setIcon(QIcon(get_icon('next.png'))) - self.bt_back.setToolTip('Go forward one page') - - self.bt_refresh.setIcon(QIcon(get_icon('refresh.png'))) - self.bt_refresh.setToolTip('Refresh the current page') - - self.bt_lock.setCheckable(True) - self.bt_url_lock.setCheckable(True) - - if not with_qt5 and rcParams['help_explorer.online'] is None: - # We now that the browser can crash with Qt4, therefore we disable - # the browing in the internet - self.bt_url_lock.click() - rcParams['help_explorer.online'] = False - elif rcParams['help_explorer.online'] is False: - self.bt_url_lock.click() - elif rcParams['help_explorer.online'] is None: - rcParams['help_explorer.online'] = True - rcParams.connect('help_explorer.online', self.update_url_lock_from_rc) - - self.bt_url_lock.clicked.connect(self.toogle_url_lock) - self.bt_lock.clicked.connect(self.toogle_lock) - - # tooltip and icons of lock and url_lock are set in toogle_lock and - # toogle_url_lock - self.toogle_lock() - self.toogle_url_lock() - - # --------------------------------------------------------------------- - # --------- initialization and connection of the web view ------------- - # --------------------------------------------------------------------- - - #: The actual widget showing the html content - self.html = QWebEngineView(parent=self) - self.html.loadStarted.connect(self.completed) - self.html.loadFinished.connect(self.completed) - - self.tb_url.currentIndexChanged[str].connect(self.browse) - self.bt_back.clicked.connect(self.html.back) - self.bt_ahead.clicked.connect(self.html.forward) - self.bt_refresh.clicked.connect(self.html.reload) - self.html.urlChanged.connect(self.url_changed) - - # --------------------------------------------------------------------- - # ---------------------------- layouts -------------------------------- - # --------------------------------------------------------------------- - - # The upper part of the browser containing all the buttons - self.button_box = button_box = QHBoxLayout() - - button_box.addWidget(self.bt_back) - button_box.addWidget(self.bt_ahead) - button_box.addWidget(self.tb_url) - button_box.addWidget(self.bt_refresh) - button_box.addWidget(self.bt_lock) - button_box.addWidget(self.bt_url_lock) - - # The upper most layout aranging the button box and the html widget - self.vbox = vbox = QVBoxLayout() - self.vbox.setContentsMargins(0, 0, 0, 0) - vbox.addLayout(button_box) - - vbox.addWidget(self.html) - - self.setLayout(vbox) - - if self.default_url is not None: - self.tb_url.addItem(self.default_url) - - self.bt_lock_default = bool(self.bt_lock.isChecked()) - self.bt_url_lock_default = bool(self.bt_url_lock.isChecked()) - - def browse(self, url): - """Make a web browse on the given url and show the page on the Webview - widget. """ - if self.bt_lock.isChecked(): - return - if not self.url_like_re.match(url): - url = 'https://' + url - if self.bt_url_lock.isChecked() and url.startswith('http'): - return - if not self.completed: - logger.debug('Stopping current load...') - self.html.stop() - self.completed = True - logger.debug('Loading %s', url) - # we use :meth:`PyQt5.QtWebEngineWidgets.QWebEngineView.setUrl` instead - # of :meth:`PyQt5.QtWebEngineWidgets.QWebEngineView.load` because that - # changes the url directly and is more useful for unittests - self.html.setUrl(QtCore.QUrl(url)) - - def url_changed(self, url): - """Triggered when the url is changed to update the adress line""" - try: - url = url.toString() - except AttributeError: - pass - logger.debug('url changed to %s', url) - try: - self.tb_url.setCurrentText(url) - except AttributeError: # Qt4 - self.tb_url.setEditText(url) - self.tb_url.add_text_on_top(url, block=True) - - def update_url_lock_from_rc(self, online): - if (online and self.bt_url_lock.isChecked() or - not online and not self.bt_url_lock.isChecked()): - self.bt_url_lock.click() - - def toogle_url_lock(self): - """Disable (or enable) the loading of web pages in www""" - bt = self.bt_url_lock - offline = bt.isChecked() - bt.setIcon(QIcon(get_icon( - 'world_red.png' if offline else 'world.png'))) - online_message = "Go online" - if not with_qt5: - online_message += ("\nWARNING: This mode is unstable under Qt4 " - "and might result in a complete program crash!") - bt.setToolTip(online_message if offline else "Offline mode") - if rcParams['help_explorer.online'] is offline: - rcParams['help_explorer.online'] = not offline - - def toogle_lock(self): - """Disable (or enable) the changing of the current webpage""" - bt = self.bt_lock - bt.setIcon(QIcon(get_icon( - 'lock.png' if bt.isChecked() else 'lock_open.png'))) - bt.setToolTip("Unlock" if bt.isChecked() else "Lock to current page") - - -class HelpMixin(object): - """Base class for providing help on an object""" - - #: Object containing the necessary fields to describe an object given to - #: the help widget. The descriptor is set up by the :meth:`describe_object` - #: method. - object_descriptor = namedtuple('ObjectDescriptor', ['obj', 'name']) - - #: :class:`bool` determining whether the documentation of an object can be - #: shown or not - can_document_object = True - #: :class:`bool` determining whether this class can show restructured text - can_show_rst = True - - @docstrings.get_sections(base='HelpMixin.show_help') - @docstrings.dedent - def show_help(self, obj, oname='', files=None): - """ - Show the rst documentation for the given object - - Parameters - ---------- - obj: object - The object to get the documentation for - oname: str - The name to use for the object in the documentation - files: list of str - A path to additional files that shall be used to process the - docs""" - descriptor = self.describe_object(obj, oname) - doc = self.get_doc(descriptor) - return self.show_rst(doc, descriptor=descriptor, files=files) - - def header(self, descriptor, sig): - """Format the header and include object name and signature `sig` - - Returns - ------- - str - The header for the documentation""" - bars = '=' * len(descriptor.name + sig) - return bars + '\n' + descriptor.name + sig + '\n' + bars + '\n' - - def describe_object(self, obj, oname=''): - """Return an instance of the :attr:`object_descriptor` class - - Returns - ------- - :attr:`object_descriptor` - The descriptor containing the information on the object""" - return self.object_descriptor(obj, oname) - - def get_doc(self, descriptor): - """Get the documentation of the object in the given `descriptor` - - Parameters - ---------- - descriptor: instance of :attr:`object_descriptor` - The descriptor containig the information on the specific object - - Returns - ------- - str - The header and documentation of the object in the descriptor - - Notes - ----- - This method uses the :func:`IPython.core.oinspect.getdoc` function to - get the documentation and the :func:`IPython.core.oinspect.signature` - function to get the signature. Those function (different from the - inspect module) do not fail when the object is not saved""" - obj = descriptor.obj - oname = descriptor.name - sig = '' - obj_sig = obj - if callable(obj): - if inspect.isclass(obj): - oname = oname or obj.__name__ - obj_sig = getattr(obj, '__init__', obj) - elif six.PY2 and type(obj) is types.InstanceType: - obj_sig = getattr(obj, '__call__', obj) - - try: - sig = str(signature(obj_sig)) - sig = re.sub('^\(\s*self,\s*', '(', sig) - except: - logger.debug('Failed to get signature from %s!' % (obj, ), - exc_info=True) - oname = oname or type(oname).__name__ - head = self.header(descriptor, sig) - lines = [] - ds = getdoc(obj) - if ds: - lines.append('') - lines.append(ds) - if inspect.isclass(obj) and hasattr(obj, '__init__'): - init_ds = getdoc(obj.__init__) - if init_ds is not None: - lines.append('\n' + init_ds) - elif hasattr(obj, '__call__'): - call_ds = getdoc(obj.__call__) - if call_ds and call_ds != getdoc(object.__call__): - lines.append('\n' + call_ds) - doc = self.process_docstring(lines, descriptor) - return head + '\n' + doc - - def process_docstring(self, lines, descriptor): - """Make final modification on the rst lines - - Returns - ------- - str - The docstring""" - return '\n'.join(lines) - - @docstrings.get_sections(base='HelpMixin.show_rst') - @docstrings.dedent - def show_rst(self, text, oname='', descriptor=None, files=None): - """ - Abstract method which needs to be implemented by th widget to show - restructured text - - Parameters - ---------- - text: str - The text to show - oname: str - The object name - descriptor: instance of :attr:`object_descriptor` - The object descriptor holding the informations - files: list of str - A path to additional files that shall be used to display the docs - - Returns - ------- - bool - True if the text is displayed - """ - return False - - @docstrings.get_sections(base='HelpMixin.show_intro') - def show_intro(self, text=''): - """ - Show an intro message - - Parameters - ---------- - s: str - A string in reStructured Text format to show""" - title = 'Welcome to psyplot!' - title += '\n' + '-' * len(title) + '\n\n' - self.show_rst(title + text, 'intro') - - -class TextHelp(QFrame, HelpMixin): - """Class to show plain text rst docstrings""" - - def __init__(self, *args, **kwargs): - super(TextHelp, self).__init__(*args, **kwargs) - self.vbox = QVBoxLayout() - self.vbox.setContentsMargins(0, 0, 0, 0) - #: The :class:`PyQt5.QtWidgets.QPlainTextEdit` instance used for - #: displaying the documentation - self.editor = QPlainTextEdit(parent=self) - self.editor.setFont(QtGui.QFont('Courier New')) - self.vbox.addWidget(self.editor) - self.setLayout(self.vbox) - - def show_rst(self, text, *args, **kwargs): - """Show the given text in the editor window - - Parameters - ---------- - text: str - The text to show - ``*args,**kwargs`` - Are ignored""" - self.editor.clear() - self.editor.insertPlainText(text) - return True - - -class UrlHelp(UrlBrowser, HelpMixin): - """Class to convert rst docstrings to html and show browsers""" - - #: Object containing the necessary fields to describe an object given to - #: the help widget. The descriptor is set up by the :meth:`describe_object` - #: method and contains an additional objtype attribute - object_descriptor = namedtuple( - 'ObjectDescriptor', ['obj', 'name', 'objtype']) - - can_document_object = with_sphinx - can_show_rst = with_sphinx - - #: menu button with different urls - bt_url_menus = None - - #: - sphinx_thread = None - - def __init__(self, *args, **kwargs): - self._temp_dir = 'sphinx_dir' not in kwargs - self.sphinx_dir = kwargs.pop('sphinx_dir', mkdtemp(prefix='psyplot_')) - self.build_dir = osp.join(self.sphinx_dir, '_build', 'html') - super(UrlHelp, self).__init__(*args, **kwargs) - - self.error_msg = PyErrorMessage(self) - if with_sphinx: - self.sphinx_thread = SphinxThread(self.sphinx_dir) - self.sphinx_thread.html_ready[str].connect(self.browse) - self.sphinx_thread.html_error[str].connect( - self.error_msg.showTraceback) - self.sphinx_thread.html_error[str].connect(logger.debug) - rcParams.connect('help_explorer.render_docs_parallel', - self.reset_sphinx) - rcParams.connect('help_explorer.use_intersphinx', - self.reset_sphinx) - rcParams.connect('help_explorer.online', - self.reset_sphinx) - - self.bt_connect_console = QToolButton(self) - self.bt_connect_console.setCheckable(True) - if rcParams['console.connect_to_help']: - self.bt_connect_console.setIcon(QIcon(get_icon( - 'ipython_console.png'))) - self.bt_connect_console.click() - else: - self.bt_connect_console.setIcon(QIcon(get_icon( - 'ipython_console_t.png'))) - self.bt_connect_console.clicked.connect(self.toogle_connect_console) - rcParams.connect('console.connect_to_help', - self.update_connect_console) - self.toogle_connect_console() - - # menu button with different urls - self.bt_url_menus = QToolButton(self) - self.bt_url_menus.setIcon(QIcon(get_icon('docu_button.png'))) - self.bt_url_menus.setToolTip('Browse documentations') - self.bt_url_menus.setPopupMode(QToolButton.InstantPopup) - - docu_menu = QMenu(self) - for name, url in six.iteritems(self.doc_urls): - def to_url(b, url=url): - self.browse(url) - action = QAction(name, self) - action.triggered.connect(to_url) - docu_menu.addAction(action) - self.bt_url_menus.setMenu(docu_menu) - - self.button_box.addWidget(self.bt_connect_console) - self.button_box.addWidget(self.bt_url_menus) - # toogle the lock again to set the bt_url_menus enabled state - self.toogle_url_lock() - - def update_connect_console(self, connect): - if (connect and not self.bt_connect_console.isChecked() or - not connect and self.bt_connect_console.isChecked()): - self.bt_connect_console.click() - - def toogle_connect_console(self): - """Disable (or enable) the loading of web pages in www""" - bt = self.bt_connect_console - connect = bt.isChecked() - bt.setIcon(QIcon(get_icon( - 'ipython_console.png' if connect else 'ipython_console_t.png'))) - bt.setToolTip("%sonnect the console to the help explorer" % ( - "Don't c" if connect else "C")) - if rcParams['console.connect_to_help'] is not connect: - rcParams['console.connect_to_help'] = connect - - def reset_sphinx(self, value): - """Method that is called if the configuration changes""" - if with_sphinx and hasattr(self.sphinx_thread, 'app'): - del self.sphinx_thread.app - - @docstrings.dedent - def show_help(self, obj, oname='', files=None): - """ - Render the rst docu for the given object with sphinx and show it - - Parameters - ---------- - %(HelpMixin.show_help.parameters)s - """ - if self.bt_lock.isChecked(): - return - return super(UrlHelp, self).show_help(obj, oname=oname, files=files) - - @docstrings.dedent - def show_intro(self, text=''): - """ - Show the intro text in the explorer - - Parameters - ---------- - %(HelpMixin.show_intro.parameters)s""" - if self.sphinx_thread is not None: - with open(self.sphinx_thread.index_file, 'a') as f: - f.write('\n' + text.strip() + '\n\n' + - 'Table of Contents\n' - '=================\n\n.. toctree::\n') - self.sphinx_thread.render(None, None) - - def show_rst(self, text, oname='', descriptor=None, files=None): - """Render restructured text with sphinx and show it - - Parameters - ---------- - %(HelpMixin.show_rst.parameters)s""" - if self.bt_lock.isChecked() or self.sphinx_thread is None: - return False - if not oname and descriptor: - oname = descriptor.name - for f in files or []: - shutil.copyfile(f, osp.join(self.sphinx_dir, osp.basename(f))) - self.sphinx_thread.render(text, oname) - return True - - def describe_object(self, obj, oname=''): - """Describe an object using additionaly the object type from the - :meth:`get_objtype` method - - Returns - ------- - instance of :attr:`object_descriptor` - The descriptor of the object""" - return self.object_descriptor(obj, oname, self.get_objtype(obj)) - - def browse(self, url): - """Reimplemented to add file paths to the url string""" - url = asstring(url) - html_file = osp.join(self.sphinx_dir, '_build', 'html', url + '.html') - if osp.exists(html_file): - url = file2html(html_file) - super(UrlHelp, self).browse(url) - - def toogle_url_lock(self): - """Disable (or enable) the loading of web pages in www""" - super(UrlHelp, self).toogle_url_lock() - # enable or disable documentation button - bt = self.bt_url_lock - offline = bt.isChecked() - try: - self.bt_url_menus.setEnabled(not offline) - except AttributeError: # not yet initialized - pass - - def url_changed(self, url): - """Reimplemented to remove file paths from the url string""" - try: - url = asstring(url.toString()) - except AttributeError: - pass - if url.startswith('file://'): - fname = html2file(url) - if osp.samefile(self.build_dir, osp.commonprefix([ - fname, self.build_dir])): - url = osp.splitext(osp.basename(fname))[0] - super(UrlHelp, self).url_changed(url) - - def header(self, descriptor, sig): - return '%(name)s\n%(bars)s\n\n.. py:%(type)s:: %(name)s%(sig)s\n' % { - 'name': descriptor.name, 'bars': '-' * len(descriptor.name), - 'type': descriptor.objtype, 'sig': sig} - - def get_objtype(self, obj): - """Get the object type of the given object and determine wheter the - object is considered a class, a module, a function, method or data - - Parameters - ---------- - obj: object - - Returns - ------- - str - One out of {'class', 'module', 'function', 'method', 'data'}""" - if inspect.isclass(obj): - return 'class' - if inspect.ismodule(obj): - return 'module' - if inspect.isfunction(obj) or isinstance(obj, type(all)): - return 'function' - if inspect.ismethod(obj) or isinstance(obj, type(str.upper)): - return 'method' - return 'data' - - def is_importable(self, modname): - """Determine whether members of the given module can be documented with - sphinx by using the :func:`sphinx.util.get_module_source` function - - Parameters - ---------- - modname: str - The __name__ attribute of the module to import - - Returns - ------- - bool - True if sphinx can import the module""" - try: - ModuleAnalyzer.get_module_source(modname) - return True - except Exception: - return False - - def get_doc(self, descriptor): - """Reimplemented to (potentially) use the features from - sphinx.ext.autodoc""" - obj = descriptor.obj - if inspect.ismodule(obj): - module = obj - else: - module = inspect.getmodule(obj) - if module is not None and (re.match('__.*__', module.__name__) or - not self.is_importable(module.__name__)): - module = None - isclass = inspect.isclass(obj) - # If the module is available, we try to use autodoc - if module is not None: - doc = '.. currentmodule:: ' + module.__name__ + '\n\n' - # a module --> use automodule - if inspect.ismodule(obj): - doc += self.header(descriptor, '') - doc += '.. automodule:: ' + obj.__name__ - # an importable class --> use autoclass - elif isclass and getattr(module, obj.__name__, None) is not None: - doc += self.header(descriptor, '') - doc += '.. autoclass:: ' + obj.__name__ - # an instance and the class can be imported - # --> use super get_doc and autoclass for the tyoe - elif descriptor.objtype == 'data' and getattr( - module, type(obj).__name__, None) is not None: - doc += '\n\n'.join([ - super(UrlHelp, self).get_doc(descriptor), - "Class docstring\n===============", - '.. autoclass:: ' + type(obj).__name__]) - # an instance --> use super get_doc for instance and the type - elif descriptor.objtype == 'data': - cls_doc = super(UrlHelp, self).get_doc(self.describe_object( - type(obj), type(obj).__name__)) - doc += '\n\n'.join([ - super(UrlHelp, self).get_doc(descriptor), - "Class docstring\n===============", - cls_doc]) - # a function or method --> use super get_doc - else: - doc += super(UrlHelp, self).get_doc(descriptor) - # otherwise the object has been defined in this session - else: - # an instance --> use super get_doc for instance and the type - if descriptor.objtype == 'data': - cls_doc = super(UrlHelp, self).get_doc(self.describe_object( - type(obj), type(obj).__name__)) - doc = '\n\n'.join([ - super(UrlHelp, self).get_doc(descriptor), - "Class docstring\n===============", - cls_doc]) - # a function or method --> use super get_doc - else: - doc = super(UrlHelp, self).get_doc(descriptor) - return doc.rstrip() + '\n' - - def process_docstring(self, lines, descriptor): - """Process the lines with the napoleon sphinx extension""" - lines = list(chain(*(l.splitlines() for l in lines))) - lines = NumpyDocstring( - lines, what=descriptor.objtype, name=descriptor.name, - obj=descriptor.obj).lines() - lines = GoogleDocstring( - lines, what=descriptor.objtype, name=descriptor.name, - obj=descriptor.obj).lines() - return indent(super(UrlHelp, self).process_docstring( - lines, descriptor)) - - def close(self, *args, **kwargs): - if kwargs.pop('force', False) or ( - not is_running_tests() and self.sphinx_thread is not None): - try: - del self.sphinx_thread.app - except AttributeError: - pass - shutil.rmtree(self.build_dir, ignore_errors=True) - if self._temp_dir: - shutil.rmtree(self.sphinx_dir, ignore_errors=True) - del self.sphinx_thread - return super(UrlHelp, self).close(*args, **kwargs) - elif is_running_tests(): - self.bt_url_lock.setChecked(self.bt_url_lock_default) - self.bt_lock.setChecked(self.bt_lock_default) - else: - return super(UrlHelp, self).close(*args, **kwargs) - - -class SphinxThread(QtCore.QThread): - """A thread to render sphinx documentation in a separate process""" - - #: A signal to be emitted when the rendering finished. The url is the - #: file location - html_ready = QtCore.pyqtSignal(str) - html_error = QtCore.pyqtSignal(str) - - def __init__(self, outdir, html_text_no_doc=''): - super(SphinxThread, self).__init__() - self.doc = None - self.name = None - self.html_text_no_doc = html_text_no_doc - self.outdir = outdir - self.index_file = osp.join(self.outdir, 'psyplot.rst') - self.confdir = osp.join(get_module_path(__name__), 'sphinx_supp') - shutil.copyfile(osp.join(self.confdir, 'psyplot.rst'), - osp.join(self.outdir, 'psyplot.rst')) - self.build_dir = osp.join(self.outdir, '_build', 'html') - - def render(self, doc, name): - """Render the given rst string and save the file as ``name + '.rst'`` - - Parameters - ---------- - doc: str - The rst docstring - name: str - the name to use for the file""" - if self.wait(): - self.doc = doc - self.name = name - # start rendering in separate process - if rcParams['help_explorer.render_docs_parallel']: - self.start() - else: - self.run() - - def run(self): - """Create the html file. When called the first time, it may take a - while because the :class:`sphinx.application.Sphinx` app is build, - potentially with intersphinx - - When finished, the html_ready signal is emitted""" - if not hasattr(self, 'app'): - from IPython.core.history import HistoryAccessor - # to avoid history access conflicts between different threads, - # we disable the ipython history - HistoryAccessor.enabled.default_value = False - self.app = Sphinx(self.outdir, - self.confdir, - self.build_dir, - osp.join(self.outdir, '_build', 'doctrees'), - 'html', - status=StreamToLogger(logger, logging.DEBUG), - warning=StreamToLogger(logger, logging.DEBUG)) - if self.name is not None: - docfile = osp.abspath(osp.join(self.outdir, self.name + '.rst')) - if docfile == self.index_file: - self.name += '1' - docfile = osp.abspath( - osp.join(self.outdir, self.name + '.rst')) - html_file = osp.abspath(osp.join( - self.outdir, '_build', 'html', self.name + '.html')) - if not osp.exists(docfile): - with open(self.index_file, 'a') as f: - f.write('\n ' + self.name) - with open(docfile, 'w') as f: - f.write(self.doc) - else: - html_file = osp.abspath(osp.join( - self.outdir, '_build', 'html', 'psyplot.html')) - try: - self.app.build(None, []) - except Exception: - msg = 'Error while building sphinx document %s' % ( - self.name) - self.html_error.emit('' + msg + '') - logger.debug(msg) - else: - self.html_ready.emit(file2html(html_file)) - - -class HelpExplorer(QWidget, DockMixin): - """A widget for showing the documentation. It behaves somewhat similar - to spyders object inspector plugin and can show restructured text either - as html (if sphinx is installed) or as plain text. It furthermore has a - browser to show html content - - Warnings - -------- - The :class:`HelpBrowser` class is known to crash under PyQt4 when new web - page domains are loaded. Hence you should disable the browsing to different - remote websites and even disable intersphinx""" - - #: The viewer classes used by the help explorer. :class:`HelpExplorer` - #: instances replace this attribute with the corresponding HelpMixin - #: instance - viewers = OrderedDict([('HTML help', UrlHelp), ('Plain text', TextHelp)]) - - if not rcParams['help_explorer.use_webengineview']: - del viewers['HTML help'] - - def __init__(self, *args, **kwargs): - super(HelpExplorer, self).__init__(*args, **kwargs) - self.vbox = vbox = QVBoxLayout() - self.combo = QComboBox(parent=self) - vbox.addWidget(self.combo) - if _viewers: - self.viewers = _viewers.copy() - for w in self.viewers.values(): - w.setParent(self) - else: - self.viewers = OrderedDict( - [(key, cls(parent=self)) for key, cls in six.iteritems( - self.viewers)]) - # save the UrlHelp because QWebEngineView creates child processes - # that are not properly closed by PyQt and as such use too much - # memory - if is_running_tests(): - for key, val in self.viewers.items(): - _viewers[key] = val - for key, ini in six.iteritems(self.viewers): - self.combo.addItem(key) - ini.hide() - vbox.addWidget(ini) - self.viewer = next(six.itervalues(self.viewers)) - self.viewer.show() - self.combo.currentIndexChanged[str].connect(self.set_viewer) - self.setLayout(vbox) - - def set_viewer(self, name): - """Sets the current documentation viewer - - Parameters - ---------- - name: str or object - A string must be one of the :attr:`viewers` attribute. An object - can be one of the values in the :attr:`viewers` attribute""" - if isstring(name) and asstring(name) not in self.viewers: - raise ValueError("Don't have a viewer named %s" % (name, )) - elif not isstring(name): - viewer = name - else: - name = asstring(name) - viewer = self.viewers[name] - self.viewer.hide() - self.viewer = viewer - self.viewer.show() - if (isstring(name) and - not self.combo.currentText() == name): - self.combo.setCurrentIndex(list(self.viewers).index(name)) - - @docstrings.dedent - def show_help(self, obj, oname='', files=None): - """ - Show the documentaion of the given object - - We first try to use the current viewer based upon it's - :attr:`HelpMixin.can_document_object` attribute. If this does not work, - we check the other viewers - - Parameters - ---------- - %(HelpMixin.show_help.parameters)s""" - oname = asstring(oname) - ret = None - if self.viewer.can_document_object: - try: - ret = self.viewer.show_help(obj, oname=oname, files=files) - except Exception: - logger.debug("Could not document %s with %s viewer!", - oname, self.combo.currentText(), exc_info=True) - else: - curr_i = self.combo.currentIndex() - for i, (viewername, viewer) in enumerate( - six.iteritems(self.viewers)): - if i != curr_i and viewer.can_document_object: - self.set_viewer(viewername) - self.combo.blockSignals(True) - self.combo.setCurrentIndex(i) - self.combo.blockSignals(False) - try: - ret = viewer.show_help(obj, oname=oname, files=files) - except Exception: - logger.debug("Could not document %s with %s viewer!", - oname, viewername, exc_info=True) - if ret: - self.parent().raise_() - return ret - - @docstrings.dedent - def show_rst(self, text, oname='', files=None): - """ - Show restructured text - - We first try to use the current viewer based upon it's - :attr:`HelpMixin.can_show_rst` attribute. If this does not work, - we check the other viewers - - Parameters - ---------- - %(HelpMixin.show_rst.parameters)s""" - ret = None - if self.viewer.can_show_rst: - ret = self.viewer.show_rst(text, oname=oname, files=files) - else: - for viewer in six.itervalues(self.viewers): - if viewer.can_show_rst: - self.set_viewer(viewer) - ret = viewer.show_rst(text, oname=oname, files=files) - break - if ret: - self.parent().raise_() - return ret - - @docstrings.dedent - def show_intro(self, text=''): - """ - Show an intro text - - We first try to use the current viewer based upon it's - :attr:`HelpMixin.can_show_rst` attribute. If this does not work, - we check the other viewers - - Parameters - ---------- - %(HelpMixin.show_intro.parameters)s""" - found = False - for i, viewer in enumerate(six.itervalues(self.viewers)): - viewer.show_intro(text) - if not found and viewer.can_show_rst: - if i: - self.set_viewer(viewer) - found = True - - def close(self, *args, **kwargs): - try: - self.viewers['HTML help'].close(*args, **kwargs) - except (KeyError, AttributeError): - pass - return super(HelpExplorer, self).close(*args, **kwargs) diff --git a/psyplot_gui/icons/console-go.png b/psyplot_gui/icons/console-go.png deleted file mode 100644 index 0b44bd1..0000000 Binary files a/psyplot_gui/icons/console-go.png and /dev/null differ diff --git a/psyplot_gui/icons/copy.png b/psyplot_gui/icons/copy.png deleted file mode 100644 index 6a7614a..0000000 Binary files a/psyplot_gui/icons/copy.png and /dev/null differ diff --git a/psyplot_gui/icons/docu_button.png b/psyplot_gui/icons/docu_button.png deleted file mode 100644 index 0b64ea9..0000000 Binary files a/psyplot_gui/icons/docu_button.png and /dev/null differ diff --git a/psyplot_gui/icons/info.png b/psyplot_gui/icons/info.png deleted file mode 100644 index 8671d32..0000000 Binary files a/psyplot_gui/icons/info.png and /dev/null differ diff --git a/psyplot_gui/icons/invalid.png b/psyplot_gui/icons/invalid.png deleted file mode 100644 index 26e4f95..0000000 Binary files a/psyplot_gui/icons/invalid.png and /dev/null differ diff --git a/psyplot_gui/icons/ipython_console.png b/psyplot_gui/icons/ipython_console.png deleted file mode 100644 index 1aca205..0000000 Binary files a/psyplot_gui/icons/ipython_console.png and /dev/null differ diff --git a/psyplot_gui/icons/ipython_console_t.png b/psyplot_gui/icons/ipython_console_t.png deleted file mode 100644 index cf88e6d..0000000 Binary files a/psyplot_gui/icons/ipython_console_t.png and /dev/null differ diff --git a/psyplot_gui/icons/lock.png b/psyplot_gui/icons/lock.png deleted file mode 100644 index f6ef32b..0000000 Binary files a/psyplot_gui/icons/lock.png and /dev/null differ diff --git a/psyplot_gui/icons/lock_open.png b/psyplot_gui/icons/lock_open.png deleted file mode 100644 index d0a0254..0000000 Binary files a/psyplot_gui/icons/lock_open.png and /dev/null differ diff --git a/psyplot_gui/icons/logo.png b/psyplot_gui/icons/logo.png deleted file mode 100644 index 28e5198..0000000 Binary files a/psyplot_gui/icons/logo.png and /dev/null differ diff --git a/psyplot_gui/icons/logo.svg b/psyplot_gui/icons/logo.svg deleted file mode 100644 index 491c49e..0000000 --- a/psyplot_gui/icons/logo.svg +++ /dev/null @@ -1,5722 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/psyplot_gui/icons/minus.png b/psyplot_gui/icons/minus.png deleted file mode 100644 index 1b27257..0000000 Binary files a/psyplot_gui/icons/minus.png and /dev/null differ diff --git a/psyplot_gui/icons/minusminus.png b/psyplot_gui/icons/minusminus.png deleted file mode 100644 index ee5d9f9..0000000 Binary files a/psyplot_gui/icons/minusminus.png and /dev/null differ diff --git a/psyplot_gui/icons/next.png b/psyplot_gui/icons/next.png deleted file mode 100644 index 611530c..0000000 Binary files a/psyplot_gui/icons/next.png and /dev/null differ diff --git a/psyplot_gui/icons/plus.png b/psyplot_gui/icons/plus.png deleted file mode 100644 index 2e93407..0000000 Binary files a/psyplot_gui/icons/plus.png and /dev/null differ diff --git a/psyplot_gui/icons/plusplus.png b/psyplot_gui/icons/plusplus.png deleted file mode 100644 index bea2203..0000000 Binary files a/psyplot_gui/icons/plusplus.png and /dev/null differ diff --git a/psyplot_gui/icons/previous.png b/psyplot_gui/icons/previous.png deleted file mode 100644 index f69bf9c..0000000 Binary files a/psyplot_gui/icons/previous.png and /dev/null differ diff --git a/psyplot_gui/icons/rcParams.png b/psyplot_gui/icons/rcParams.png deleted file mode 100644 index 1b17c78..0000000 Binary files a/psyplot_gui/icons/rcParams.png and /dev/null differ diff --git a/psyplot_gui/icons/refresh.png b/psyplot_gui/icons/refresh.png deleted file mode 100644 index d339514..0000000 Binary files a/psyplot_gui/icons/refresh.png and /dev/null differ diff --git a/psyplot_gui/icons/run_arrow.png b/psyplot_gui/icons/run_arrow.png deleted file mode 100644 index 4a58c37..0000000 Binary files a/psyplot_gui/icons/run_arrow.png and /dev/null differ diff --git a/psyplot_gui/icons/valid.png b/psyplot_gui/icons/valid.png deleted file mode 100644 index cd10167..0000000 Binary files a/psyplot_gui/icons/valid.png and /dev/null differ diff --git a/psyplot_gui/icons/warning.png b/psyplot_gui/icons/warning.png deleted file mode 100644 index 9801d12..0000000 Binary files a/psyplot_gui/icons/warning.png and /dev/null differ diff --git a/psyplot_gui/icons/world.png b/psyplot_gui/icons/world.png deleted file mode 100644 index 36dde37..0000000 Binary files a/psyplot_gui/icons/world.png and /dev/null differ diff --git a/psyplot_gui/icons/world_red.png b/psyplot_gui/icons/world_red.png deleted file mode 100644 index f12058e..0000000 Binary files a/psyplot_gui/icons/world_red.png and /dev/null differ diff --git a/psyplot_gui/main.py b/psyplot_gui/main.py deleted file mode 100644 index 35c3789..0000000 --- a/psyplot_gui/main.py +++ /dev/null @@ -1,1106 +0,0 @@ -"""Core module for the psyplot graphical user interface - -This module redefines the :class:`psyplot.project.Project` class with -additional features for an interactive usage with graphical qt user interface. -There is no need to import this module because the -:class:`GuiProject` class defined here replaces the project class in the -:mod:`psyplot.project` module.""" -import sys -import six -import socket -import errno -import pickle -import os -from pkg_resources import iter_entry_points -from functools import partial -from collections import defaultdict, OrderedDict -import matplotlib as mpl -from psyplot.compat.pycompat import get_default_value -from psyplot_gui import rcParams -from threading import Thread -import logging - -# change backend here before the project module is imported -backend = rcParams['backend'] -if backend is not None: - if backend == 'psyplot': - backend = 'module://psyplot_gui.backend' - mpl.use(backend) - -from psyplot_gui.console import ConsoleWidget -from psyplot_gui.compat.qtcompat import ( - QMainWindow, QApplication, Qt, QMenu, QAction, QDesktopWidget, QLabel, - QFileDialog, QKeySequence, QtCore, with_qt5, QMessageBox, QIcon, - QInputDialog, QActionGroup) -from psyplot_gui.content_widget import ( - ProjectContentWidget, DatasetTree, FiguresTree) -from psyplot_gui.plot_creator import PlotCreator -from psyplot_gui.help_explorer import HelpExplorer -from psyplot_gui.dataframeeditor import DataFrameEditor -from psyplot_gui.fmt_widget import FormatoptionWidget -from psyplot_gui.common import PyErrorMessage, get_icon, StreamToLogger -from psyplot_gui.preferences import ( - Prefences, GuiRcParamsWidget, PsyRcParamsWidget) -from psyplot_gui.dependencies import DependenciesDialog - -from psyplot.docstring import docstrings -import psyplot.plotter as psyp -import psyplot.project as psy -import psyplot -from psyplot.config.rcsetup import get_configdir -import psyplot.data as psyd -import psyplot_gui -import xarray as xr - - -#: The :class:`PyQt5.QtWidgets.QMainWindow` of the graphical user interface -mainwindow = None - - -def _set_mainwindow(obj): - global mainwindow - mainwindow = obj - - -class MainWindow(QMainWindow): - - #: A signal that is emmitted when the a signal is received through the - #: open_files_server - open_external = QtCore.pyqtSignal(list) - - #: The server to open external files - open_files_server = None - - #: Inprocess console - console = None - - #: tree widget displaying the open datasets - ds_tree = None - - #: list of figures from the psyplot backend - figures = [] - - #: tree widget displaying the open figures - figures_tree = None - - #: general formatoptions widget - fmt_widget = None - - #: help explorer - help_explorer = None - - #: the DataFrameEditor widgets, a widget to show and edit data frames - dataframeeditors = None - - #: tab widget displaying the arrays in current main and sub project - project_content = None - - #: The dockwidgets of this instance - dockwidgets = [] - - #: default widths of the dock widgets - default_widths = {} - - _is_open = False - - #: The keyboard shortcuts of the default layout - default_shortcuts = [] - - #: The current keyboard shortcuts - current_shortcuts = [] - - #: The key for the central widget for the main window in the - #: :attr:`plugins` dictionary - central_widget_key = 'console' - - @property - def logger(self): - """The logger of this instance""" - return logging.getLogger('%s.%s' % (self.__class__.__module__, - self.__class__.__name__)) - - @docstrings.get_sections(base='MainWindow') - @docstrings.dedent - def __init__(self, show=True): - """ - Parameters - ---------- - show: bool - If True, the created mainwindow is show - """ - if sys.stdout is None: - sys.stdout = StreamToLogger(self.logger) - if sys.stderr is None: - sys.stderr = StreamToLogger(self.logger) - super(MainWindow, self).__init__() - self.setWindowIcon(QIcon(get_icon('logo.png'))) - - #: list of figures from the psyplot backend - self.figures = [] - self.error_msg = PyErrorMessage(self) - self.setDockOptions( - QMainWindow.AnimatedDocks | QMainWindow.AllowNestedDocks | - QMainWindow.AllowTabbedDocks) - #: Inprocess console - self.console = ConsoleWidget(self) - self.project_actions = {} - - self.config_pages = [] - - self.open_file_options = OrderedDict([ - ('new psyplot plot from dataset', self.open_external_files), - ('new psyplot project', partial(self.open_external_files, [])), - ]) - - # --------------------------------------------------------------------- - # ----------------------------- Menus --------------------------------- - # --------------------------------------------------------------------- - - # ######################## File menu ################################## - - # --------------------------- New plot -------------------------------- - - self.file_menu = QMenu('File', parent=self) - self.new_plot_action = QAction('New plot', self) - self.new_plot_action.setStatusTip( - 'Use an existing dataset (or open a new one) to create one or ' - 'more plots') - self.register_shortcut(self.new_plot_action, QKeySequence.New) - self.new_plot_action.triggered.connect(lambda: self.new_plots(True)) - self.file_menu.addAction(self.new_plot_action) - - # --------------------------- Open project ---------------------------- - - self.open_project_menu = QMenu('Open project', self) - self.file_menu.addMenu(self.open_project_menu) - - self.open_mp_action = QAction('New main project', self) - self.register_shortcut(self.open_mp_action, QKeySequence.Open) - self.open_mp_action.setStatusTip('Open a new main project') - self.open_mp_action.triggered.connect(self.open_mp) - self.open_project_menu.addAction(self.open_mp_action) - - self.open_sp_action = QAction('Add to current', self) - - self.register_shortcut( - self.open_sp_action, QKeySequence( - 'Ctrl+Shift+O', QKeySequence.NativeText)) - self.open_sp_action.setStatusTip( - 'Load a project as a sub project and add it to the current main ' - 'project') - self.open_sp_action.triggered.connect(self.open_sp) - self.open_project_menu.addAction(self.open_sp_action) - - # ---------------------- load preset menu ----------------------------- - - self.load_preset_menu = QMenu('Load preset', parent=self) - self.file_menu.addMenu(self.load_preset_menu) - - self.load_sp_preset_action = self.load_preset_menu.addAction( - "For selection", self.load_sp_preset) - self.load_sp_preset_action.setStatusTip( - "Load a preset for the selected project") - - self.load_mp_preset_action = self.load_preset_menu.addAction( - "For full project", self.load_mp_preset) - self.load_sp_preset_action.setStatusTip( - "Load a preset for the full project") - - # ----------------------- Save project -------------------------------- - - self.save_project_menu = QMenu('Save', parent=self) - self.file_menu.addMenu(self.save_project_menu) - - self.save_mp_action = QAction('Full psyplot project', self) - self.save_mp_action.setStatusTip( - 'Save the entire project into a pickle file') - self.register_shortcut(self.save_mp_action, QKeySequence.Save) - self.save_mp_action.triggered.connect(self.save_mp) - self.save_project_menu.addAction(self.save_mp_action) - - self.save_sp_action = QAction('Selected psyplot project', self) - self.save_sp_action.setStatusTip( - 'Save the selected sub project into a pickle file') - self.save_sp_action.triggered.connect(self.save_sp) - self.save_project_menu.addAction(self.save_sp_action) - - # ------------------------ Save project as ---------------------------- - - self.save_project_as_menu = QMenu('Save as', parent=self) - self.file_menu.addMenu(self.save_project_as_menu) - - self.save_mp_as_action = QAction('Full psyplot project', self) - self.save_mp_as_action.setStatusTip( - 'Save the entire project into a pickle file') - self.register_shortcut(self.save_mp_as_action, - QKeySequence.SaveAs) - self.save_mp_as_action.triggered.connect( - partial(self.save_mp, new_fname=True)) - self.save_project_as_menu.addAction(self.save_mp_as_action) - - self.save_sp_as_action = QAction('Selected psyplot project', self) - self.save_sp_as_action.setStatusTip( - 'Save the selected sub project into a pickle file') - self.save_sp_as_action.triggered.connect( - partial(self.save_sp, new_fname=True)) - self.save_project_as_menu.addAction(self.save_sp_as_action) - - # ------------------------ Save preset -------------------------------- - - self.save_preset_menu = QMenu('Save preset', parent=self) - self.file_menu.addMenu(self.save_preset_menu) - - self.save_sp_preset_action = self.save_preset_menu.addAction( - "Selection", self.save_sp_preset) - self.save_sp_preset_action.setStatusTip( - "Save the formatoptions of the selected project as a preset") - - self.save_mp_preset_action = self.save_preset_menu.addAction( - "Full project", self.save_mp_preset) - self.save_sp_preset_action.setStatusTip( - "Save the formatoptions of the full project as a preset") - - # -------------------------- Pack project ----------------------------- - - self.pack_project_menu = QMenu('Zip project files', parent=self) - self.file_menu.addMenu(self.pack_project_menu) - - self.pack_mp_action = QAction('Full psyplot project', self) - self.pack_mp_action.setStatusTip( - 'Pack all the data of the main project into one folder') - self.pack_mp_action.triggered.connect(partial(self.save_mp, pack=True)) - self.pack_project_menu.addAction(self.pack_mp_action) - - self.pack_sp_action = QAction('Selected psyplot project', self) - self.pack_sp_action.setStatusTip( - 'Pack all the data of the current sub project into one folder') - self.pack_sp_action.triggered.connect(partial(self.save_sp, pack=True)) - self.pack_project_menu.addAction(self.pack_sp_action) - - # ------------------------ Export figures ----------------------------- - - self.export_project_menu = QMenu('Export figures', parent=self) - self.file_menu.addMenu(self.export_project_menu) - - self.export_mp_action = QAction('Full psyplot project', self) - self.export_mp_action.setStatusTip( - 'Pack all the data of the main project into one folder') - self.export_mp_action.triggered.connect(self.export_mp) - self.register_shortcut( - self.export_mp_action, QKeySequence( - 'Ctrl+E', QKeySequence.NativeText)) - self.export_project_menu.addAction(self.export_mp_action) - - self.export_sp_action = QAction('Selected psyplot project', self) - self.export_sp_action.setStatusTip( - 'Pack all the data of the current sub project into one folder') - self.register_shortcut( - self.export_sp_action, QKeySequence( - 'Ctrl+Shift+E', QKeySequence.NativeText)) - self.export_sp_action.triggered.connect(self.export_sp) - self.export_project_menu.addAction(self.export_sp_action) - - # ------------------------ Close project ------------------------------ - - self.file_menu.addSeparator() - - self.close_project_menu = QMenu('Close project', parent=self) - self.file_menu.addMenu(self.close_project_menu) - - self.close_mp_action = QAction('Full psyplot project', self) - self.register_shortcut( - self.close_mp_action, QKeySequence( - 'Ctrl+Shift+W', QKeySequence.NativeText)) - self.close_mp_action.setStatusTip( - 'Close the main project and delete all data and plots out of ' - 'memory') - self.close_mp_action.triggered.connect( - lambda: psy.close(psy.gcp(True).num)) - self.close_project_menu.addAction(self.close_mp_action) - - self.close_sp_action = QAction('Selected psyplot project', self) - self.close_sp_action.setStatusTip( - 'Close the selected arrays project and delete all data and plots ' - 'out of memory') - self.register_shortcut(self.close_sp_action, QKeySequence.Close) - self.close_sp_action.triggered.connect( - lambda: psy.gcp().close(True, True)) - self.close_project_menu.addAction(self.close_sp_action) - - # ----------------------------- Quit ---------------------------------- - - if sys.platform != 'darwin': # mac os makes this anyway - self.quit_action = QAction('Quit', self) - self.quit_action.triggered.connect(self.close) - self.quit_action.triggered.connect( - QtCore.QCoreApplication.instance().quit) - self.register_shortcut( - self.quit_action, QKeySequence.Quit) - self.file_menu.addAction(self.quit_action) - - self.menuBar().addMenu(self.file_menu) - - # ######################## Console menu ############################### - - self.console_menu = QMenu('Console', self) - self.console_menu.addActions(self.console.actions()) - self.menuBar().addMenu(self.console_menu) - - # ######################## Windows menu ############################### - - self.windows_menu = QMenu('Windows', self) - self.menuBar().addMenu(self.windows_menu) - - # ############################ Help menu ############################## - - self.help_menu = QMenu('Help', parent=self) - self.menuBar().addMenu(self.help_menu) - - # -------------------------- Preferences ------------------------------ - - self.help_action = QAction('Preferences', self) - self.help_action.triggered.connect(lambda: self.edit_preferences(True)) - self.register_shortcut(self.help_action, - QKeySequence.Preferences) - self.help_menu.addAction(self.help_action) - - # ---------------------------- About ---------------------------------- - - self.about_action = QAction('About', self) - self.about_action.triggered.connect(self.about) - self.help_menu.addAction(self.about_action) - - # ---------------------------- Dependencies --------------------------- - - self.dependencies_action = QAction('Dependencies', self) - self.dependencies_action.triggered.connect( - lambda: self.show_dependencies(True)) - self.help_menu.addAction(self.dependencies_action) - - self.dockwidgets = [] - - # --------------------------------------------------------------------- - # -------------------------- Dock windows ----------------------------- - # --------------------------------------------------------------------- - #: tab widget displaying the arrays in current main and sub project - #: tree widget displaying the open datasets - self.project_content = ProjectContentWidget(parent=self) - self.ds_tree = DatasetTree(parent=self) - #: tree widget displaying the open figures - self.figures_tree = FiguresTree(parent=self) - #: help explorer - self.help_explorer = help_explorer = HelpExplorer(parent=self) - if 'HTML help' in help_explorer.viewers and help_explorer.viewers[ - 'HTML help'].sphinx_thread is not None: - help_explorer.viewers[ - 'HTML help'].sphinx_thread.html_ready.connect( - self.focus_on_console) - #: the DataFrameEditor widgets - self.dataframeeditors = [] - #: general formatoptions widget - self.fmt_widget = FormatoptionWidget( - parent=self, help_explorer=help_explorer, - console=self.console) - - # load plugin widgets - self.plugins = plugins = OrderedDict([ - ('console', self.console), - ('project_content', self.project_content), - ('ds_tree', self.ds_tree), - ('figures_tree', self.figures_tree), - ('help_explorer', self.help_explorer), - ('fmt_widget', self.fmt_widget), - ]) - self.default_plugins = list(plugins) - for plugin_name, w_class in six.iteritems(rcParams.load_plugins()): - plugins[plugin_name] = w_class(parent=self) - - self.add_mp_to_menu() - psy.Project.oncpchange.connect(self.eventually_add_mp_to_menu) - self.windows_menu.addSeparator() - - self.window_layouts_menu = QMenu('Window layouts', self) - self.restore_layout_action = QAction('Restore default layout', self) - self.restore_layout_action.triggered.connect(self.setup_default_layout) - self.window_layouts_menu.addAction(self.restore_layout_action) - self.windows_menu.addMenu(self.window_layouts_menu) - - self.panes_menu = QMenu('Panes', self) - self.windows_menu.addMenu(self.panes_menu) - - self.dataframe_menu = QMenu('DataFrame editors', self) - self.dataframe_menu.addAction( - 'New Editor', partial(self.new_data_frame_editor, None, - 'DataFrame Editor')) - self.dataframe_menu.addSeparator() - self.windows_menu.addMenu(self.dataframe_menu) - - self.central_widgets_menu = menu = QMenu('Central widget', self) - self.windows_menu.addMenu(menu) - self.central_widgets_actions = group = QActionGroup(self) - group.setExclusive(True) - - # --------------------------------------------------------------------- - # -------------------------- connections ------------------------------ - # --------------------------------------------------------------------- - - self.console.help_explorer = help_explorer - psyp.default_print_func = partial(help_explorer.show_rst, - oname='formatoption_docs') - psy.PlotterInterface._print_func = psyp.default_print_func - self.setCentralWidget(self.console) - - # make sure that the plots are shown between the project content and - # the help explorer widget - self.setCorner(Qt.TopLeftCorner, Qt.LeftDockWidgetArea) - self.setCorner(Qt.TopRightCorner, Qt.RightDockWidgetArea) - - # make sure that the formatoption widgets are shown between the - # project content and the help explorer widget - self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea) - self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea) - - # --------------------------------------------------------------------- - # ------------------------------ closure ------------------------------ - # --------------------------------------------------------------------- - if show: - self.help_explorer.show_intro(self.console.intro_msg) - - # --------------------------------------------------------------------- - # ------------------------- open_files_server ------------------------- - # --------------------------------------------------------------------- - self.callbacks = {'new_plot': self.open_external.emit, - 'change_cwd': self._change_cwd, - 'run_script': self.console.run_script.emit, - 'command': self.console.run_command.emit, - } - - # Server to open external files on a single instance - self.open_files_server = socket.socket(socket.AF_INET, - socket.SOCK_STREAM, - socket.IPPROTO_TCP) - - if rcParams['main.listen_to_port']: - self._file_thread = Thread(target=self.start_open_files_server) - self._file_thread.setDaemon(True) - self._file_thread.start() - - self.open_external.connect(self._open_external_files) - - self.config_pages.extend([GuiRcParamsWidget, PsyRcParamsWidget]) - - # display the statusBar - statusbar = self.statusBar() - self.figures_label = QLabel() - statusbar.addWidget(self.figures_label) - self.plugin_label = QLabel() - statusbar.addWidget(self.plugin_label) - - self.default_widths = {} - - self.setup_default_layout() - - if show: - self.showMaximized() - - # save the default widths after they have been shown - for w in self.plugins.values(): - if w.dock is not None: - self.default_widths[w] = w.dock.size().width() - - # hide plugin widgets that should be hidden at startup. Although this - # has been executed by :meth:`setup_default_layout`, we have to execute - # it again after the call of showMaximized - for name, w in self.plugins.items(): - if name != self.central_widget_key: - w.to_dock(self) - if w.hidden: - w.hide_plugin() - else: - w.create_central_widget_action(self).setChecked(True) - - self._is_open = True - - def focus_on_console(self, *args, **kwargs): - """Put focus on the ipython console""" - self.console._control.setFocus() - - def new_data_frame_editor(self, df=None, title='DataFrame Editor'): - """Open a new dataframe editor - - Parameters - ---------- - df: pandas.DataFrame - The dataframe to display - title: str - The title of the dock window - - Returns - ------- - psyplot_gui.dataframeeditor.DataFrameEditor - The newly created editor""" - editor = DataFrameEditor() - self.dataframeeditors.append(editor) - editor.to_dock(self, title, - Qt.RightDockWidgetArea, docktype='df') - if df is not None: - editor.set_df(df) - editor.show_plugin() - editor.maybe_tabify() - editor.raise_() - return editor - - def setup_default_layout(self): - """Set up the default window layout""" - self.project_content.to_dock(self, 'Plot objects', - Qt.LeftDockWidgetArea) - self.ds_tree.to_dock(self, 'Datasets', Qt.LeftDockWidgetArea) - self.figures_tree.to_dock(self, 'Figures', Qt.LeftDockWidgetArea) - self.help_explorer.to_dock(self, 'Help explorer', - Qt.RightDockWidgetArea) - self.fmt_widget.to_dock(self, 'Formatoptions', Qt.BottomDockWidgetArea) - - modify_widths = bool(self.default_widths) - for w in map(self.plugins.__getitem__, self.default_plugins): - if w.dock is not None: - w.show_plugin() - - if modify_widths and with_qt5: - self.resizeDocks([w.dock], [self.default_widths[w]], - Qt.Horizontal) - - # hide plugin widgets that should be hidden at startup - for name, w in self.plugins.items(): - if name != self.central_widget_key: - w.to_dock(self) - if w.hidden: - w.hide_plugin() - - action2shortcut = defaultdict(list) - for s, a in self.default_shortcuts: - action2shortcut[a].append(s) - - for a, s in action2shortcut.items(): - self.register_shortcut(a, s) - - def set_central_widget(self, name): - """Set the central widget - - Parameters - ---------- - name: str or QWidget - The key or the plugin widget in the :attr:`plugins` dictionary""" - from PyQt5.QtCore import QTimer - self.setUpdatesEnabled(False) - current = self.centralWidget() - if isinstance(name, six.string_types): - new = self.plugins[name] - else: - new = name - name = next(key for key, val in self.plugins.items() if val is new) - if new is not current: - - self._dock_widths = dock_widths = OrderedDict() - self._dock_heights = dock_heights = OrderedDict() - for key, w in self.plugins.items(): - if w.dock is not None and w.is_shown: - s = w.dock.size() - dock_widths[w] = s.width() - if w is not new: - dock_heights[w] = s.height() - - new_pos = self.dockWidgetArea(new.dock) - - self.removeDockWidget(new.dock) - new.dock.close() - self.panes_menu.removeAction(new._view_action) - self.dataframe_menu.removeAction(new._view_action) - new.dock = new._view_action = None - self.central_widget_key = name - current.to_dock(self) - self.setCentralWidget(new) - new._set_central_action.setChecked(True) - current.show_plugin() - current.to_dock(self) - new_width = dock_widths.pop(new, None) - if current.hidden: - current.hide_plugin() - else: - current_pos = self.dockWidgetArea(current.dock) - if current_pos == new_pos and new_width: - dock_widths[current] = new_width - - self._custom_layout_timer = QTimer(self) - self._custom_layout_timer.timeout.connect(self._reset_dock_widths) - self._custom_layout_timer.setSingleShot(True) - self._custom_layout_timer.start(5000) - - def _reset_dock_widths(self): - # resize the plugins - if with_qt5: - for w, width in self._dock_widths.items(): - if w.dock is not None: - self.resizeDocks([w.dock], [width], Qt.Horizontal) - for w, height in self._dock_heights.items(): - if w.dock is not None: - self.resizeDocks([w.dock], [height], Qt.Vertical) - - self.setUpdatesEnabled(True) - - def _save_project(self, p, new_fname=False, *args, **kwargs): - if new_fname or 'project_file' not in p.attrs: - fname = QFileDialog.getSaveFileName( - self, 'Project destination', os.getcwd(), - 'Pickle files (*.pkl);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fname = fname[0] - if not fname: - return - else: - fname = p.attrs['project_file'] - try: - p.save_project(fname, *args, **kwargs) - except Exception: - self.error_msg.showTraceback('Could not save the project!') - else: - p.attrs['project_file'] = fname - if p.is_main: - self.update_project_action(p.num) - - def load_mp_preset(self): - self._load_preset(psy.gcp(True)) - - def load_sp_preset(self): - self._load_preset(psy.gcp()) - - def _load_preset(self, project, *args, **kwargs): - fname, ok = QFileDialog.getOpenFileName( - self, 'Load preset', os.path.join(get_configdir(), "presets"), - 'YAML files (*.yml *.yaml);;' - 'All files (*)' - ) - if ok: - project.load_preset(fname, *args, **kwargs) - - def open_mp(self, *args, **kwargs): - """Open a new main project""" - self._open_project(main=True) - - def open_sp(self, *args, **kwargs): - """Open a subproject and add it to the current main project""" - self._open_project(main=False) - - def _open_project(self, *args, **kwargs): - fname = QFileDialog.getOpenFileName( - self, 'Project file', os.getcwd(), - 'Pickle files (*.pkl);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fname = fname[0] - if not fname: - return - p = psy.Project.load_project(fname, *args, **kwargs) - p.attrs['project_file'] = fname - self.update_project_action(p.num) - - def save_mp(self, *args, **kwargs): - """Save the current main project.""" - self._save_project(psy.gcp(True), **kwargs) - - def save_sp(self, *args, **kwargs): - """Save the current sub project.""" - self._save_project(psy.gcp(), **kwargs) - - def save_sp_preset(self): - self._save_preset(psy.gcp()) - - def save_mp_preset(self): - self._save_preset(psy.gcp(True)) - - def _save_preset(self, project, *args, **kwargs): - fname, ok = QFileDialog.getSaveFileName( - self, 'Save preset', os.path.join(get_configdir(), 'presets'), - 'YAML file (*.yml *.yaml);;' - 'All files (*)' - ) - if ok: - project.save_preset(fname, *args, **kwargs) - - def _export_project(self, p, *args, **kwargs): - fname = QFileDialog.getSaveFileName( - self, 'Picture destination', os.getcwd(), - 'PDF files (*.pdf);;' - 'Postscript file (*.ps);;' - 'PNG image (*.png);;' - 'JPG image (*.jpg *.jpeg);;' - 'TIFF image (*.tif *.tiff);;' - 'GIF image (*.gif);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fname = fname[0] - if not fname: - return - try: - p.export(fname, *args, **kwargs) - except Exception: - self.error_msg.showTraceback( - 'Could not export the figures!') - - def export_mp(self, *args, **kwargs): - self._export_project(psy.gcp(True), **kwargs) - - def export_sp(self, *args, **kwargs): - self._export_project(psy.gcp(), **kwargs) - - def new_plots(self, exec_=None): - if hasattr(self, 'plot_creator'): - try: - self.plot_creator.close() - except RuntimeError: - pass - self.plot_creator = PlotCreator( - help_explorer=self.help_explorer, parent=self) - available_width = QDesktopWidget().availableGeometry().width() / 3. - width = self.plot_creator.sizeHint().width() - height = self.plot_creator.sizeHint().height() - # The plot creator window should cover at least one third of the screen - self.plot_creator.resize(max(available_width, width), height) - if exec_: - self.plot_creator.exec_() - - def excepthook(self, type, value, traceback): - """A method to replace the sys.excepthook""" - self.error_msg.excepthook(type, value, traceback) - - def edit_preferences(self, exec_=None): - """Edit Spyder preferences""" - if hasattr(self, 'preferences'): - try: - self.preferences.close() - except RuntimeError: - pass - self.preferences = dlg = Prefences(self) - for PrefPageClass in self.config_pages: - widget = PrefPageClass(dlg) - widget.initialize() - dlg.add_page(widget) - available_width = int( - 0.667*QDesktopWidget().availableGeometry().width() - ) - width = dlg.sizeHint().width() - height = dlg.sizeHint().height() - # The preferences window should cover at least one third of the screen - dlg.resize(max(available_width, width), height) - if exec_: - dlg.exec_() - - def about(self): - """About the tool""" - versions = { - key: d['version'] for key, d in psyplot.get_versions(False).items() - } - versions.update(psyplot_gui.get_versions()['requirements']) - versions.update(psyplot._get_versions()['requirements']) - versions['github'] = 'https://github.com/psyplot/psyplot' - versions['author'] = psyplot.__author__ - QMessageBox.about( - self, "About psyplot", - u"""psyplot: Interactive data visualization with python -
Copyright © 2017- Philipp Sommer -
Licensed under the terms of the GNU General Public License v2 - (GPLv2) -

Created by %(author)s

-

Most of the icons come from the - iconfinder.

-

For bug reports and feature requests, please go - to our Github website or contact the - author via mail.

-

This package uses (besides others) the following packages:
-

    -
  • psyplot %(psyplot)s
  • -
  • Python %(python)s
  • -
  • numpy %(numpy)s
  • -
  • xarray %(xarray)s
  • -
  • pandas %(pandas)s
  • -
  • psyplot_gui %(psyplot_gui)s
  • -
  • Qt %(qt)s
  • -
  • PyQt %(pyqt)s
  • -
  • qtconsole %(qtconsole)s
  • -

-

For a full list of requirements see the dependencies - in the Help menu.

-

This software is provided "as is", without warranty or support - of any kind.

""" - % versions) - - def show_dependencies(self, exec_=None): - """Open a dialog that shows the dependencies""" - if hasattr(self, 'dependencies'): - try: - self.dependencies.close() - except RuntimeError: - pass - self.dependencies = dlg = DependenciesDialog(psyplot.get_versions(), - parent=self) - dlg.resize(630, 420) - if exec_: - dlg.exec_() - - def reset_rcParams(self): - rcParams.update_from_defaultParams() - psy.rcParams.update_from_defaultParams() - - def add_mp_to_menu(self): - mp = psy.gcp(True) - action = QAction(os.path.basename(mp.attrs.get( - 'project_file', 'Untitled %s*' % mp.num)), self) - action.setStatusTip( - 'Make project %s the current project' % mp.num) - action.triggered.connect(lambda: psy.scp(psy.project(mp.num))) - self.project_actions[mp.num] = action - self.windows_menu.addAction(action) - - def update_project_action(self, num): - action = self.project_actions.get(num) - p = psy.project(num) - if action: - action.setText(os.path.basename(p.attrs.get( - 'project_file', 'Untitled %s*' % num))) - - def eventually_add_mp_to_menu(self, p): - for num in set(self.project_actions).difference( - psy.get_project_nums()): - self.windows_menu.removeAction(self.project_actions.pop(num)) - if p is None or not p.is_main: - return - if p.num not in self.project_actions: - self.add_mp_to_menu() - - def start_open_files_server(self): - """This method listens to the open_files_port and opens the plot - creator for new files - - This method is inspired and to most parts copied from spyder""" - self.open_files_server.setsockopt(socket.SOL_SOCKET, - socket.SO_REUSEADDR, 1) - port = rcParams['main.open_files_port'] - try: - self.open_files_server.bind(('127.0.0.1', port)) - except Exception: - return - self.open_files_server.listen(20) - while 1: # 1 is faster than True - try: - req, dummy = self.open_files_server.accept() - except socket.error as e: - # See Issue 1275 for details on why errno EINTR is - # silently ignored here. - eintr = errno.EINTR - # To avoid a traceback after closing on Windows - if e.args[0] == eintr: - continue - # handle a connection abort on close error - enotsock = (errno.WSAENOTSOCK if os.name == 'nt' - else errno.ENOTSOCK) - if e.args[0] in [errno.ECONNABORTED, enotsock]: - return - raise - args = pickle.loads(req.recv(1024)) - callback = args[0] - func = self.callbacks[callback] - self.logger.debug('Emitting %s callback %s', callback, func) - func(args[1:]) - req.sendall(b' ') - - def change_cwd(self, path): - """Change the current working directory""" - import os - os.chdir(path) - - def _change_cwd(self, args): - path = args[0][0] - self.change_cwd(path) - - docstrings.keep_params( - 'make_plot.parameters', 'fnames', 'project', 'engine', 'plot_method', - 'name', 'dims', 'encoding', 'enable_post', 'seaborn_style', - 'concat_dim', 'chname', 'preset') - - def open_files(self, fnames): - """Open a file and ask the user how""" - fnames_s = ', '.join(map(os.path.basename, fnames)) - if len(fnames_s) > 30: - fnames_s = fnames_s[:27] + '...' - item, ok = QInputDialog.getItem( - self, 'Open file...', 'Open %s as...' % fnames_s, - list(self.open_file_options), current=0, editable=False) - if ok: - return self.open_file_options[item](fnames) - - @docstrings.get_sections(base='MainWindow.open_external_files') - @docstrings.dedent - def open_external_files(self, fnames=[], project=None, engine=None, - plot_method=None, name=None, dims=None, - encoding=None, enable_post=False, - seaborn_style=None, concat_dim=get_default_value( - xr.open_mfdataset, 'concat_dim'), chname={}, - preset=None): - """ - Open external files - - Parameters - ---------- - %(make_plot.parameters.fnames|project|engine|plot_method|name|dims|encoding|enable_post|seaborn_style|concat_dim|chname|preset)s - """ - if seaborn_style is not None: - import seaborn as sns - sns.set_style(seaborn_style) - if project is not None: - fnames = [s.split(',') for s in fnames] - if not isinstance(project, dict): - project = psyd.safe_list(project)[0] - single_files = (l[0] for l in fnames if len(l) == 1) - alternative_paths = defaultdict(lambda: next(single_files, None)) - alternative_paths.update(list(l for l in fnames if len(l) == 2)) - p = psy.Project.load_project( - project, alternative_paths=alternative_paths, - engine=engine, main=not psy.gcp(), encoding=encoding, - enable_post=enable_post, chname=chname) - if preset: - p.load_preset(preset) - if isinstance(project, six.string_types): - p.attrs.setdefault('project_file', project) - return True - else: - self.new_plots(False) - self.plot_creator.open_dataset(fnames, engine=engine, - concat_dim=concat_dim) - if name == 'all': - ds = self.plot_creator.get_ds() - name = sorted(set(ds.variables) - set(ds.coords)) - self.plot_creator.insert_array( - list(filter(None, psy.safe_list(name)))) - if dims is not None: - ds = self.plot_creator.get_ds() - dims = {key: ', '.join( - map(str, val)) for key, val in six.iteritems( - dims)} - for i, vname in enumerate( - self.plot_creator.array_table.vnames): - self.plot_creator.array_table.selectRow(i) - self.plot_creator.array_table.update_selected( - ) - self.plot_creator.array_table.selectAll() - var = ds[vname[0]] - self.plot_creator.array_table.update_selected( - dims=var.psy.decoder.correct_dims(var, dims.copy())) - if preset: - self.plot_creator.set_preset(preset) - if plot_method: - self.plot_creator.pm_combo.setCurrentIndex( - self.plot_creator.pm_combo.findText(plot_method)) - self.plot_creator.exec_() - return True - - def _open_external_files(self, args): - self.open_external_files(*args) - - @classmethod - @docstrings.get_sections(base='MainWindow.run') - @docstrings.dedent - def run(cls, fnames=[], project=None, engine=None, plot_method=None, - name=None, dims=None, encoding=None, enable_post=False, - seaborn_style=None, - concat_dim=get_default_value(xr.open_mfdataset, 'concat_dim'), - chname={}, preset=None, show=True): - """ - Create a mainwindow and open the given files or project - - This class method creates a new mainwindow instance and sets the - global :attr:`mainwindow` variable. - - Parameters - ---------- - %(MainWindow.open_external_files.parameters)s - %(MainWindow.parameters)s - - Notes - ----- - - There can be only one mainwindow at the time - - This method does not create a QApplication instance! See - :meth:`run_app` - - See Also - -------- - run_app - """ - mainwindow = cls(show=show) - _set_mainwindow(mainwindow) - if fnames or project: - mainwindow.open_external_files( - fnames, project, engine, plot_method, name, dims, encoding, - enable_post, seaborn_style, concat_dim, chname, preset) - psyplot.with_gui = True - return mainwindow - - def register_shortcut(self, action, shortcut, - context=Qt.ApplicationShortcut): - """Register an action for a shortcut""" - shortcuts = psy.safe_list(shortcut) - for j, shortcut in enumerate(shortcuts): - found = False - for i, (s, a) in enumerate(self.current_shortcuts): - if s == shortcut: - new_shortcuts = [ - sc for sc in self.current_shortcuts[i][1].shortcuts() - if sc != s] - a.setShortcut(QKeySequence()) - if new_shortcuts: - a.setShortcuts(new_shortcuts) - self.current_shortcuts[i][1] = action - found = True - break - if not found: - self.default_shortcuts.append([shortcut, action]) - self.current_shortcuts.append([shortcut, action]) - action.setShortcuts(shortcuts) - action.setShortcutContext(context) - - @classmethod - @docstrings.dedent - def run_app(cls, *args, **kwargs): - """ - Create a QApplication, open the given files or project and enter the - mainloop - - Parameters - ---------- - %(MainWindow.run.parameters)s - - See Also - -------- - run - """ - app = QApplication(sys.argv) - cls.run(*args, **kwargs) - sys.exit(app.exec_()) - - def closeEvent(self, event): - """closeEvent reimplementation""" - if not self._is_open or (self._is_open and self.close()): - self._is_open = False - event.accept() - - def close(self): - _set_mainwindow(None) - if self.open_files_server is not None: - self.open_files_server.close() - del self.open_files_server - for widget in self.plugins.values(): - widget.close() - self.plugins.clear() - return super(MainWindow, self).close() diff --git a/psyplot_gui/plot_creator.py b/psyplot_gui/plot_creator.py deleted file mode 100644 index a9ac328..0000000 --- a/psyplot_gui/plot_creator.py +++ /dev/null @@ -1,2187 +0,0 @@ -"""This module contains a widget to create new plots with psyplot - -The main class is the :class:`PlotCreator` which is used to handle the -different plotting methods of the :class:`psyplot.project.ProjectPlotter` -class""" -from __future__ import division -import os -import logging -import re -import types -import xarray -from functools import partial -import numpy as np -from collections import defaultdict -from math import floor -from itertools import chain, product, cycle, repeat, starmap -import matplotlib as mpl -import six -from psyplot.utils import _temp_bool_prop -from psyplot.compat.pycompat import map, range, filter, OrderedDict -from psyplot_gui.compat.qtcompat import ( - QWidget, QComboBox, QHBoxLayout, QVBoxLayout, QFileDialog, QToolButton, - QIcon, Qt, QListView, QtCore, with_qt5, QAbstractItemView, QPushButton, - QLabel, QValidator, QStyledItemDelegate, QLineEdit, QCheckBox, isstring, - QTableWidget, QTableWidgetItem, QGridLayout, QIntValidator, QMenu, QAction, - QInputDialog, QTabWidget, QDoubleValidator, QGraphicsScene, asstring, - QGraphicsRectItem, QGraphicsView, QDialog, QDialogButtonBox, QSplitter) -from psyplot_gui.common import (get_icon, ListValidator, PyErrorMessage, - LoadFromConsoleButton) -from psyplot_gui.preferences import RcParamsTree -import psyplot.project as psy -from psyplot.config.rcsetup import get_configdir - - -logger = logging.getLogger(__name__) - - -class CoordComboBox(QComboBox): - """Combobox showing coordinate information of a dataset - - This combobox loads its data from the current dataset and allows the - popups to be left open. It also has a :attr:`leftclick` signal that is - emitted when the popup is about to be closed because the user clicked on a - value""" - - close_popups = _temp_bool_prop('close_popups', default=True) - use_coords = _temp_bool_prop('use_coords', default=False) - leftclick = QtCore.pyqtSignal(QComboBox) - - def __init__(self, ds_func, dim, parent=None): - """ - Parameters - ---------- - ds_func: function - The function that, when called without arguments, returns the - xarray.Dataset to use - dim: str - The coordinate name for this combobox - parent: PyQt5.QtWidgets.QWidget - The parent widget""" - super(CoordComboBox, self).__init__(parent) - self.dim = dim - self._is_empty = True - self.get_ds = ds_func - self._changed = False - self._right_clicked = False - - # modify the view - view = self.view() - # We allow the selection of multiple items with a left-click - view.setSelectionMode(QListView.ExtendedSelection) - # The following modifications will cause this behaviour: - # Left-click: - # Case 1: Any of the already existing plot arrays is selected - # Add the selected values in the popup to the dimension in - # the currently selected plot items - # Case 2: No plot arrays are selected or none exists - # Create new plot items from the selection in the popup - # Right-Click: - # Set the currentIndex which will be used when new plot items - # are created - # - # Therefore we first enable a CustomContextMenu - view.setContextMenuPolicy(Qt.CustomContextMenu) - - # We have to disable the default MousePressEvent in the views viewport - # because otherwise the Left-click behaviour would occur as well when - # hitting the right button - # Therefore: - # install an EventFilter such that only the customContextMenuRequested - # signal of the view is fired and not the pressed signal (which would - # hide the popup) - view.viewport().installEventFilter(self) - view.customContextMenuRequested.connect(self.right_click) - # Furthermore we implement, that the pop up shall not be closed if the - # keep open property is True. Therefore we have to track when the - # index changes - view.pressed.connect(self.handleItemPressed) - view.doubleClicked.connect(self.hide_anyway) - - def eventFilter(self, obj, event): - """Reimplemented to filter right-click events on the view()""" - ret = ((event.type() == QtCore.QEvent.MouseButtonPress) and - event.button() == Qt.RightButton) - return ret - - def handleItemPressed(self, index): - """Function to be called when an item is pressed to make sure that - we know whether anything changed before closing the popup""" - item = self.model().itemFromIndex(index) - if item.checkState() == Qt.Checked: - item.setCheckState(Qt.Unchecked) - else: - item.setCheckState(Qt.Checked) - self.setCurrentIndex(0) - self._changed = True - - def right_click(self, point): - """Function that is called when an item is right_clicked""" - ind = self.view().indexAt(point).row() - self.setCurrentIndex(ind) - self._right_clicked = True - self._changed = True - - def hide_anyway(self, index=None): - """Function to hide the popup despite of the :attr:`_changed` attribute - """ - self._changed = True - self.hidePopup() - - def hidePopup(self): - """Reimplemented to only close the popup when the :attr:`close_popup` - attribute is True or it is clicked outside the window""" - if not self._right_clicked: - self.leftclick.emit(self) - if not self._changed or self.close_popups: - super(CoordComboBox, self).hidePopup() - self._changed = False - self._right_clicked = False - - def mousePressEvent(self, *args, **kwargs): - """Reimplemented to fill the box with content from the dataset""" - self.load_coord() - super(CoordComboBox, self).mousePressEvent(*args, **kwargs) - - def mouseDoubleClickEvent(self, *args, **kwargs): - """Reimplemented to fill the box with content from the dataset""" - self.load_coord() - super(CoordComboBox, self).mouseDoubleClickEvent(*args, **kwargs) - - def load_coord(self): - """Load the coordinate data from the dataset and fill the combobox with - it (if it is empty)""" - if self._is_empty: - ds = self.get_ds() - self.addItem('') - if self.use_coords: - self.addItems(ds[self.dim].astype(str).values) - else: - self.addItems(list(map(str, range(len(ds[self.dim]))))) - self._is_empty = False - - -class ArrayNameValidator(QValidator): - """Class to make sure that only those arrays names are inserted that are - not currently in the main project or the tree""" - - def __init__(self, text, table, *args, **kwargs): - super(ArrayNameValidator, self).__init__(*args, **kwargs) - self.table = table - self.current_text = text - self.current_names = list(table.current_names) - - def fixup(self, s): - s = asstring(s) - if not s: - return self.table.next_available_name() - return self.table.next_available_name(s + '_{0}') - - def validate(self, s, pos): - s = asstring(s) - if not s: - return QValidator.Intermediate, s, pos - elif s == self.current_text: - pass - elif s in chain(psy.gcp(True).arr_names, self.current_names): - return QValidator.Intermediate, s, pos - return QValidator.Acceptable, s, pos - - -class ArrayNameItemDelegate(QStyledItemDelegate): - """Delegate using the :class:`ArrayNameValidator` for validation""" - - def createEditor(self, widget, option, index): - if not index.isValid(): - return - editor = QLineEdit(widget) - item = self.parent().item(index.row(), index.column()) - validator = ArrayNameValidator(item.text() if item else '', - self.parent(), editor) - editor.setValidator(validator) - return editor - - -class VariableItemDelegate(QStyledItemDelegate): - """Delegate alowing only the variables in the parents dataset. - - The parent must hold a `get_ds` method that returns a dataset when called - """ - - def createEditor(self, widget, option, index): - if not index.isValid(): - return - editor = QLineEdit(widget) - ds = self.parent().get_ds() - validator = ListValidator(ds.variables.keys(), self.parent().sep, - editor) - editor.setValidator(validator) - return editor - - -class VariablesTable(QTableWidget): - """Table to display the variables of a dataset""" - - #: The variables in the dataset - variables = [] - - @property - def selected_variables(self): - """The currently selected variables""" - return [ - self.variables[i] for i in map( - list(map(asstring, self.variables)).index, - sorted(set(item.text() for item in self.selectedItems() - if item.column() == 0)))] - - def __init__(self, get_func, columns=['long_name', 'dims', 'shape'], - *args, **kwargs): - """ - Parameters - ---------- - get_func: function - The function that, when called without arguments, returns the - xarray.Dataset to use - columns: list of str - The attribute that will be used as columns for the variables""" - super(VariablesTable, self).__init__(*args, **kwargs) - self.variables = [] - self.get_ds = get_func - self.set_columns(columns) - self.setEditTriggers(QAbstractItemView.NoEditTriggers) - self.verticalHeader().setVisible(False) - - def set_columns(self, columns=None): - if columns is None: - columns = self.column_labels - else: - self.column_labels = columns - self.setColumnCount(len(columns) + 1) - self.setHorizontalHeaderLabels(['variable'] + columns) - - def fill_from_ds(self, ds=None): - """Clear the table and insert items from the given `dataset`""" - self.clear() - self.set_columns() - if ds is None: - ds = self.get_ds() - if ds is None: - return - coords = list(ds.coords) - self.variables = vnames = [v for v in ds.variables if v not in coords] - self.setRowCount(len(vnames)) - for i, vname in enumerate(vnames): - variable = ds.variables[vname] - self.setItem(i, 0, QTableWidgetItem(asstring(vname))) - for j, attr in enumerate(self.column_labels, 1): - if attr == 'dims': - self.setItem(i, j, QTableWidgetItem( - ', '.join(variable.dims))) - else: - self.setItem(i, j, QTableWidgetItem( - str(variable.attrs.get(attr, getattr( - variable, attr, ''))))) - - -class CoordsTable(QTableWidget): - """A table showing the coordinates of in a dataset via instances of - :class:`CoordComboBox`""" - - def __init__(self, get_func, *args, **kwargs): - """ - Parameters - ---------- - get_func: function - The function that, when called without arguments, returns the - xarray.Dataset to use - ``*args, **kwargs`` - Determined by the :class:`PyQt5.QtWidgets.QTableWidget` class""" - super(CoordsTable, self).__init__(*args, **kwargs) - self.get_ds = get_func - self.setEditTriggers(QAbstractItemView.NoEditTriggers) - self.setRowCount(1) - self.verticalHeader().setVisible(False) - self.horizontalHeader().setStretchLastSection(True) - self.verticalHeader().setStretchLastSection(True) - - @property - def combo_boxes(self): - """A list of :class:`CoordComboBox` in this table""" - return list(filter( - lambda w: w is not None, - (self.cellWidget(0, i) for i in range(self.columnCount())))) - - def fill_from_ds(self, ds=None): - """Clear the table and create new comboboxes""" - for cb in self.combo_boxes: - cb.blockSignals(True) - self.clear() - if ds is None: - ds = self.get_ds() - if ds is None: - return - coords = list(ds.coords) - vnames = [v for v in ds.variables if v not in coords] - self.dims = dims = list(set( - chain(*(ds.variables[vname].dims for vname in vnames)))) - try: - dims.sort() - except TypeError: - pass - self.setColumnCount(len(dims)) - for i, dim in enumerate(dims): - header_item = QTableWidgetItem(dim) - self.setHorizontalHeaderItem(i, header_item) - self.setCellWidget(0, i, CoordComboBox(self.get_ds, dim)) - - def sizeHint(self): - """Reimplemented to adjust the heigth based upon the header and the - first row""" - return QtCore.QSize( - super(CoordsTable, self).sizeHint().width(), - self.horizontalHeader().height() + self.rowHeight(0)) - - -class DragDropTable(QTableWidget): - """Table that allows to exchange rows via drag and drop - - This class was mainly taken from - http://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget - """ - - def __init__(self, *args, **kwargs): - super(DragDropTable, self).__init__(*args, **kwargs) - - self.setDragEnabled(True) - self.setAcceptDrops(True) - self.viewport().setAcceptDrops(True) - self.setDragDropOverwriteMode(False) - self.setDropIndicatorShown(True) - - self.setSelectionMode(QAbstractItemView.ExtendedSelection) - self.setSelectionBehavior(QAbstractItemView.SelectRows) - self.setDragDropMode(QAbstractItemView.InternalMove) - - def dropEvent(self, event): - if event.source() == self and ( - event.dropAction() == Qt.MoveAction or - self.dragDropMode() == QAbstractItemView.InternalMove): - self.dropOn(event) - - else: - super(DragDropTable, self).dropEvent(event) - - def moveRows(self, row, remove=False): - """Move all selected rows to the given `row`""" - selRows = sorted({ind.row() for ind in self.selectedIndexes()}) - top = selRows[0] - - dropRow = row - if dropRow == -1: - dropRow = self.rowCount() - offset = dropRow - top - - for i, row in enumerate(selRows): - r = row + offset - if r > self.rowCount() or r < 0: - r = 0 - self.insertRow(r) - - selRows = sorted({ind.row() for ind in self.selectedIndexes()}) - - top = selRows[0] - offset = dropRow - top - for i, row in enumerate(selRows): - r = row + offset - if r > self.rowCount() or r < 0: - r = 0 - - for j in range(self.columnCount()): - source = QTableWidgetItem(self.item(row, j)) - self.setItem(r, j, source) - - if remove: - for row in reversed(selRows): - self.removeRow(row) - - def droppingOnItself(self, event, index): - dropAction = event.dropAction() - - if self.dragDropMode() == QAbstractItemView.InternalMove: - dropAction = Qt.MoveAction - - if (event.source() == self and - event.possibleActions() & Qt.MoveAction and - dropAction == Qt.MoveAction): - selectedIndexes = self.selectedIndexes() - child = index - while child.isValid() and child != self.rootIndex(): - if child in selectedIndexes: - return True - child = child.parent() - - return False - - def dropOn(self, event): - if event.isAccepted(): - return False, None, None, None - - index = QtCore.QModelIndex() - row = -1 - - if self.viewport().rect().contains(event.pos()): - index = self.indexAt(event.pos()) - if not index.isValid() or not self.visualRect(index).contains( - event.pos()): - index = self.rootIndex() - - if self.model().supportedDropActions() & event.dropAction(): - if index != self.rootIndex(): - dropIndicatorPosition = self.position( - event.pos(), self.visualRect(index), index) - - if dropIndicatorPosition == QAbstractItemView.AboveItem: - row = index.row() - # index = index.parent() - elif dropIndicatorPosition == QAbstractItemView.BelowItem: - row = index.row() + 1 - # index = index.parent() - else: - row = index.row() - - if not self.droppingOnItself(event, index): - self.moveRows(row, remove=event.source() is None) - event.accept() - - def position(self, pos, rect, index): - r = QAbstractItemView.OnViewport - margin = 2 - if pos.y() - rect.top() < margin: - r = QAbstractItemView.AboveItem - elif rect.bottom() - pos.y() < margin: - r = QAbstractItemView.BelowItem - elif rect.contains(pos, True): - r = QAbstractItemView.OnItem - - if r == QAbstractItemView.OnItem and not ( - self.model().flags(index) & Qt.ItemIsDropEnabled): - if pos.y() < rect.center().y(): - r = QAbstractItemView.AboveItem - else: - r = QAbstractItemView.BelowItem - return r - - -class ArrayTable(DragDropTable): - """Table that shows the arrays that will be used for plotting - - It contains the following columns: - - 1. The variable column which holds the variable names of the arrays. - multiple variables may be separated by ';;' - 2. The array name. The :attr:`psyplot.data.InteractiveBase.arr_name` - attribute. Depending on the plot methods - :attr:`~psyplot.project._PlotterInterface._prefer_list`, multiple - array names are allowed or not. If this attribute is True, - arrays with the same array name will be concatenated into one - :class:`psyplot.data.InteractiveList` - 3. The axes column. Use the right-click context menu to select a - subplot - 4. The check column. Checks for variable names, array names, axes and - dimensions via the :meth:`psyplot.project._PlotterInterface.check_data` - method - 5. Columns containing the dimension informations""" - - #: Pattern to interprete subplots - subplot_patt = re.compile(r'\((?P\d+),\s*' # figure - r'(?P\d+),\s*' # rows - r'(?P\d+),\s*' # columns - r'(?P\d+),\s*' # position - r'(?P\d+)\s*\)' # end subplot - ) - - #: pattern to interprete arbitrary axes - axes_patt = re.compile(r'\((?P\d+),\s*' # figure - r'(?P0*\.\d+),\s*' # lower left x - r'(?P0*\.\d+),\s*' # lower left y - r'(?P0*\.\d+),\s*' # upper right x - r'(?P0*\.\d+)\s*\)' # upper right y - ) - - #: The separator for variable names - sep = ';;' - - #: Tool tip for the variable column - VARIABLE_TT = ("The variables of the array from the dataset. Multiple" - "variables for one array may be separated by '%s'" % ( - sep)) - - #: Base tool tip for a dimension column - DIMS_TT = ("The values for dimension %s." - " You can use integers either explicit, e.g." - "
    " - "
  • 1, 2, 3, ...,
  • " - "
" - "or slices like start:end:step, e.g." - "
    " - "
  • '1:6:2'
  • " - "
" - "where the latter is equivalent to '1, 3, 5'") - - def dropEvent(self, event): - """Reimplemented to call the :meth:`check_arrays` after the call""" - # apparently the row deletion occurs after the call of this method. - # therefore our call of `check_arrays` leads to the (wrong) result - # of a duplicated entry. We therefore filter them out here and make - # sure that those arrays are not considered when checking for - # duplicates - messages = dict( - zip(self.current_names, [msg for b, msg in self.check_arrays()])) - super(ArrayTable, self).dropEvent(event) - ignores = [arr_name for arr_name, msg in messages.items() - if not msg.startswith('Found duplicated entry of')] - self.check_arrays(ignore_duplicates=ignores) - - @property - def prefer_list(self): - """Return the _prefer_list attribute of the plot_method""" - return self.plot_method and self.plot_method._prefer_list - - @property - def current_names(self): - """The names that are currently in use""" - if self.prefer_list: - return [] - arr_col = self.arr_col - return [asstring(item.text()) for item in filter(None, map( - lambda i: self.item(i, arr_col), range(self.rowCount())))] - - @property - def vnames(self): - """The list of variable names per array""" - var_col = self.var_col - return [self.item(i, var_col).text().split(';;') - for i in range(self.rowCount())] - - @property - def arr_names_dict(self): - """The final dictionary containing the array names necessary for the - `arr_names` parameter in the - :meth:`psyplot.data.ArrayList.from_dataset` method """ - ret = OrderedDict() - arr_col = self.arr_col - for irow in range(self.rowCount()): - arr_name = asstring(self.item(irow, arr_col).text()) - if self.plot_method and self.plot_method._prefer_list: - d = ret.setdefault(arr_name, defaultdict(list)) - d['name'].append(self._get_variables(irow)) - for key, val in self._get_dims(irow).items(): - d[key].append(val) - else: - ret[arr_name] = d = {'name': self._get_variables(irow)} - d.update(self._get_dims(irow)) - - return ret - - @property - def axes(self): - """A list of axes settings corresponding to the arrays in the - :attr:`arr_names_dict`""" - ret = [] - d = set() - arr_col = self.arr_col - axes_col = self.axes_col - # get the projection - pm = self.plot_method - kwargs = {} - if pm is not None: - projection = self.plot_method.plotter_cls._get_sample_projection() - if projection is not None: - kwargs['projection'] = projection - for irow in range(self.rowCount()): - arr_name = self.item(irow, arr_col).text() - if arr_name in d: - continue - d.add(arr_name) - axes_type, args = self.axes_info(self.item(irow, axes_col)) - if axes_type == 'subplot': - ret.append(SubplotCreator.create_subplot(*args, **kwargs)) - elif axes_type == 'axes': - ret.append(AxesCreator.create_axes(*args, **kwargs)) - else: - ret.append(None) - return ret - - @property - def var_col(self): - """The index of the variable column""" - return self.desc_cols.index(self.VARIABLE_LABEL) - - @property - def arr_col(self): - """The index of the array name column""" - return self.desc_cols.index(self.ARRAY_LABEL) - - @property - def axes_col(self): - """The index of the axes column""" - return self.desc_cols.index(self.AXES_LABEL) - - @property - def check_col(self): - """The index of the check column""" - return self.desc_cols.index(self.CHECK_LABEL) - - def __init__(self, get_func, columns=[], *args, **kwargs): - """ - Parameters - ---------- - get_func: function - The function that, when called without arguments, returns the - xarray.Dataset to use - columns: list of str - The coordinates in the dataset""" - super(ArrayTable, self).__init__(*args, **kwargs) - self.get_ds = get_func - self.VARIABLE_LABEL = 'variable' - self.ARRAY_LABEL = 'array name' - self.AXES_LABEL = 'axes' - self.CHECK_LABEL = 'check' - self.desc_cols = [self.VARIABLE_LABEL, self.ARRAY_LABEL, - self.AXES_LABEL, self.CHECK_LABEL] - self.plot_method = None - self.setSelectionBehavior(QAbstractItemView.SelectRows) - self.setContextMenuPolicy(Qt.CustomContextMenu) - self.customContextMenuRequested.connect(self.showAxesCreator) - self.set_columns(columns) - self.setItemDelegateForColumn(self.var_col, VariableItemDelegate(self)) - self.setItemDelegateForColumn( - self.arr_col, ArrayNameItemDelegate(self)) - self.itemChanged.connect(self.check_item) - self.itemChanged.connect(self.update_other_items) - - def set_columns(self, columns): - """Set the columns of the table - - Parameters - ---------- - columns: list of str - The coordinates in the dataset""" - if columns is None: - columns = self.column_labels - else: - self.column_labels = columns - self.setColumnCount(len(columns) + len(self.desc_cols)) - self.setHorizontalHeaderLabels(self.desc_cols + columns) - for i, col in enumerate(columns, len(self.desc_cols)): - self.horizontalHeaderItem(i).setToolTip(self.DIMS_TT % col) - self.horizontalHeaderItem(self.var_col).setToolTip(self.VARIABLE_TT) - - def setup_from_ds(self, ds=None, plot_method=None): - """Fill the table based upon the given dataset. - - Parameters - ---------- - ds: xarray.Dataset or None - If None, the dataset from the :attr:`get_ds` function is used - plot_method: psyplot.project._PlotterInterface or None - The plot method of the :class:`psyplot.project.ProjectPlotter` - class or None if no plot shall be made""" - self.clear() - self.setRowCount(0) - if ds is None: - ds = self.get_ds() - if plot_method is not None: - self.set_pm(plot_method) - if ds is None: - self.set_columns([]) - return - coords = list(ds.coords) - vnames = [v for v in ds.variables if v not in coords] - self.dims = dims = list( - set(chain(*(ds.variables[vname].dims for vname in vnames)))) - try: - dims.sort() - except TypeError: - pass - self.set_columns(dims) - - def next_available_name(self, *args, **kwargs): - """Gives the next possible name to use""" - counter = iter(range(1000)) - current_names = self.current_names - mp = psy.gcp(True) - while True: - name = mp.next_available_name(*args, counter=counter, **kwargs) - if name not in current_names: - return name - - def insert_array(self, name, check=True, **kwargs): - """Appends the settings for an array the the list in a new row""" - dims = set(self.get_ds().variables[name].dims) - irow = self.rowCount() - self.setRowCount(irow + 1) - self.setItem(irow, 0, QTableWidgetItem(asstring(name))) - self.setItem(irow, 1, QTableWidgetItem(self.next_available_name())) - self.setItem(irow, 2, QTableWidgetItem('')) - for dim in dims.intersection(kwargs): - icol = len(self.desc_cols) + self.dims.index(dim) - self.setItem(irow, icol, QTableWidgetItem(kwargs[dim])) - if check: - self.check_array(irow) - - def remove_arrays(self, selected=True): - """Remove array rows from the list - - Parameters - ---------- - selected: bool - If True, only the selected rows are removed""" - if selected: - irows = sorted({ind.row() for ind in self.selectedIndexes()}) - else: - irows = list(range(self.rowCount())) - for irow in irows[::-1]: - self.removeRow(irow) - - def update_selected(self, check=True, dims={}): - """Updates the dimensions of the selectiond arrays with the given - `dims` - - Parameters - ---------- - check: bool - whether the array shall be checked afterwards - dims: dict - a mapping from coordinate names to string values that shall be - appended to the current text""" - ds = self.get_ds() - irows = {item.row() for item in self.selectedItems()} - var_col = self.desc_cols.index(self.VARIABLE_LABEL) - for irow in irows: - vname = asstring( - self.item(irow, var_col).text()).split(self.sep)[0].strip() - var_dims = set(ds.variables[vname].dims) - for dim in var_dims.intersection(dims): - icol = len(self.desc_cols) + self.dims.index(dim) - item = self.item(irow, icol) - curr_text = asstring(item.text()) - if curr_text: - curr_text += ', ' - item.setText(curr_text + dims[dim]) - if check: - for irow in irows: - self.check_array(irow) - - def add_subplots(self, rows, cols, maxn=None): - """Add multiple subplots to the selected arrays""" - import matplotlib.pyplot as plt - irows = sorted({ind.row() for ind in self.selectedIndexes()}) - irows = irows or list(range(self.rowCount())) - maxn = maxn or rows * cols - figs = chain(*( - [i] * maxn for i in range(1, 1000) if i not in plt.get_fignums())) - nums = cycle(range(1, maxn + 1)) - seen = set() - axes_col = self.desc_cols.index(self.AXES_LABEL) - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - for irow in irows: - arr_item = self.item(irow, arr_col) - if arr_item is None or arr_item.text() in seen: - continue - seen.add(arr_item.text()) - num = next(nums) - text = '(%i, %i, %i, %i, %i)' % ( - next(figs), rows, cols, num, num) - item = QTableWidgetItem(text) - self.setItem(irow, axes_col, item) - - def add_single_subplot(self, rows, cols, row, col): - """Add one subplot to the selected arrays on multiple figures""" - import matplotlib.pyplot as plt - irows = sorted({ind.row() for ind in self.selectedIndexes()}) - irows = irows or list(range(self.rowCount())) - figs = (num for num in range(1, 1000) if num not in plt.get_fignums()) - num = (row - 1) * rows + col - seen = set() - axes_col = self.desc_cols.index(self.AXES_LABEL) - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - for irow in irows: - arr_item = self.item(irow, arr_col) - if arr_item is None or arr_item.text() in seen: - continue - seen.add(arr_item.text()) - text = '(%i, %i, %i, %i, %i)' % ( - next(figs), rows, cols, num, num) - item = QTableWidgetItem(text) - self.setItem(irow, axes_col, item) - - def showAxesCreator(self, pos): - """Context menu for right-click on a row""" - irows = sorted({ind.row() for ind in self.selectedIndexes()}) - if not irows: - return - menu = QMenu(self) - menu.addAction(self.axes_creator_action(irows)) - menu.exec_(self.mapToGlobal(pos)) - - def axes_creator_action(self, rows): - """Action to open a :class:`AxesCreatorCollection` for the selected - rows""" - axes_col = self.desc_cols.index(self.AXES_LABEL) - items = [self.item(row, axes_col) for row in rows] - action = QAction('Select subplot', self) - types_and_args = list( - filter(lambda t: t[0], map(self.axes_info, items))) - types = [t[0] for t in types_and_args] - if types and all(t == types[0] for t in types): - if types[0] == 'subplot': - creator_kws = ['fig', 'rows', 'cols', 'num1', 'num2'] - elif types[0] == 'axes': - creator_kws = ['fig', 'x0', 'y0', 'x1', 'y1'] - else: - creator_kws = [] - func_name = types[0] - args = [t[1] for t in types_and_args] - - #: the initialization keywords of the :class:`SubplotCreator` class - kwargs = {} - - if len(items) > 0: - kwargs['fig'] = '' - - for kw, vals in zip(creator_kws, zip(*args)): - if all(val == vals[0] for val in vals): - kwargs[kw] = vals[0] - else: - func_name = None - kwargs = {} - - action.triggered.connect( - self._open_axes_creator(items, func_name, kwargs)) - return action - - def _change_axes(self, items, iterator): - seen = set() - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - for item, text in zip(items, iterator): - arr_name = self.item(item.row(), arr_col).text() - if arr_name in seen: - continue - seen.add(arr_name) - item.setText(text) - - def _open_axes_creator(self, items, func_name, kwargs): - - def func(): - if hasattr(self, '_axes_creator'): - self._axes_creator.close() - self._axes_creator = obj = AxesCreatorCollection( - func_name, kwargs, parent=self) - obj.okpressed.connect(partial(self._change_axes, items)) - obj.exec_() - return func - - def axes_info(self, s): - """Interpretes an axes information""" - s = asstring(s) if isstring(s) else asstring(s.text()) - m = self.subplot_patt.match(s) - if m: - return 'subplot', list(map(int, m.groups())) - m = self.axes_patt.match(s) - if m: - return 'axes', [int(m.groupdict()['fig'])] + list(map( - float, m.groups()[1:])) - return None, None - - def set_pm(self, s): - """Set the plot method""" - s = asstring(s) - self.plot_method = getattr(psy.plot, s, None) - self.check_arrays() - - def check_item(self, item): - """Check the array corresponding to the given item""" - if item.column() == self.desc_cols.index(self.CHECK_LABEL): - return - for irow in range(self.rowCount()): - other_item = self.item( - irow, self.desc_cols.index(self.ARRAY_LABEL)) - if other_item is not None: - self.check_array(irow) - - def update_other_items(self, item): - """Updates the axes information of the other items corresponding - that have the same array name as the array corresponding to the given - `item`""" - axes_col = self.desc_cols.index(self.AXES_LABEL) - if not self.prefer_list or item.column() != axes_col: - return - this_row = item.row() - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - arr_item = self.item(this_row, arr_col) - if arr_item is None: - return - arr_name = arr_item.text() - self.blockSignals(True) - for row in range(self.rowCount()): - if row != this_row: - arr_item2 = self.item(row, arr_col) - if arr_item2 is not None and arr_item2.text() == arr_name: - self.item(row, axes_col).setText(item.text()) - self.blockSignals(False) - - def get_all_rows(self, row): - """Return all the rows that have the same array name as the given `row` - """ - def check_item(row): - item = self.item(row, arr_col) - return item is not None and item.text() == arr_name - - if self.plot_method is None or not self.plot_method._prefer_list: - return [row] - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - arr_name = self.item(row, arr_col).text() - return [r for r in range(self.rowCount()) if check_item(r)] - - def check_array(self, row, ignore_duplicates=[]): - """check whether the array variables are valid, the array name is - valid, the axes info is valid and the dimensions""" - def set_check(row, valid, msg): - check_item = QTableWidgetItem() - check_item.setFlags(check_item.flags() ^ Qt.ItemIsEditable) - if valid: - check_item.setIcon(QIcon(get_icon('valid.png'))) - elif valid is None: - check_item.setIcon(QIcon(get_icon('warning.png'))) - check_item.setToolTip(msg) - else: - check_item.setIcon(QIcon(get_icon('invalid.png'))) - check_item.setToolTip(msg) - self.setItem(row, check_col, check_item) - self.resizeColumnToContents(check_col) - - check_col = self.desc_cols.index(self.CHECK_LABEL) - valid = True - msg = '' - - # --------------------------------------------------------------------- - # ----------------- check if a variable is provided ------------------- - # --------------------------------------------------------------------- - - var_item = self.item(row, self.desc_cols.index(self.VARIABLE_LABEL)) - if var_item is not None and not asstring(var_item.text()).strip(): - valid = False - msg = 'At least one variable name must be provided!' - - # --------------------------------------------------------------------- - # ----------------- check for duplicates of array names --------------- - # --------------------------------------------------------------------- - - arr_col = self.desc_cols.index(self.ARRAY_LABEL) - arr_item = self.item(row, arr_col) - if valid and arr_item is not None: - arr_name = arr_item.text() - if arr_name not in ignore_duplicates: - if not arr_name: - msg = 'An array name must be provided' - valid = False - elif (len([name for name in self.current_names - if name == arr_name]) > 1): - valid = False - msg = "Found duplicated entry of '%s'" % arr_name - - # --------------------------------------------------------------------- - # ------- check the plotmethod if necessary and set the icon ---------- - # --------------------------------------------------------------------- - - if valid and self.plot_method is not None: - rows = self.get_all_rows(row) - checks, messages = self.plot_method.check_data( - self.get_ds(), - name=list(map(self._get_variables, rows)), - dims=list(map(self._get_dims, rows))) - for row2, valid, msg in zip(rows, checks, messages): - set_check(row2, valid, msg) - valid = checks[rows.index(row)] - msg = messages[rows.index(row)] - else: - set_check(row, valid, msg) - - return valid, msg - - def check_arrays(self, **kwargs): - """Convenience function to check all arrays using the - :meth:`check_array` method""" - return list(map(partial(self.check_array, **kwargs), - range(self.rowCount()))) - - def _str2slice(self, s): - s = s.strip() - if not s: - return [] - s = s.split(':') - if len(s) > 1: - return range(*map(int, s[:3])) - return [int(s[0])] - - def _get_dims(self, row): - start = len(self.desc_cols) - ret = {} - for dim, item in zip(self.dims, - map(lambda col: self.item(row, col), - range(start, self.columnCount()))): - if item: - text = asstring(item.text()) - if text: - slices = list( - chain(*map(self._str2slice, text.split(',')))) - if len(slices) == 1: - slices = slices[0] - ret[dim] = slices - return ret - - def _get_variables(self, row): - var_col = self.desc_cols.index(self.VARIABLE_LABEL) - ret = [s.strip() for s in asstring( - self.item(row, var_col).text()).split(self.sep)] - ds = self.get_ds() - for i, name in enumerate(ret): - ret[i] = next(v for v in ds if asstring(v) == name) - if len(ret) == 1: - return ret[0] - return ret - - -class SubplotCreator(QWidget): - """Select a subplot to which will be created (if not already existing) when - making the plot""" - - def __init__(self, fig=None, rows=1, cols=1, num1=1, num2=None, *args, - **kwargs): - """ - Parameters - ---------- - fig: int or None - The number of the figure - rows: int - The number of rows for the gridspec - cols: int - The number of columns for the gridspec - num1: int - The number of the upper left corner starting from 1 - num2: int or None - The number of the lower right corner starting from 1. If None, - `num1` is used""" - super(SubplotCreator, self).__init__(*args, **kwargs) - - self.fig_label = QLabel('Figure number:', self) - if fig is None: - import matplotlib.pyplot as plt - fig = next( - num for num in range(1, 1000) if num not in plt.get_fignums()) - self.fig_edit = QLineEdit(str(fig), self) - self.fig_edit.setValidator(QIntValidator()) - - self.rows_label = QLabel('No. of rows:', self) - self.rows_edit = QLineEdit(str(rows), self) - self.rows_edit.setValidator(QIntValidator(1, 9999, parent=self)) - - self.cols_label = QLabel('No. of columns:', self) - self.cols_edit = QLineEdit(str(cols), self) - self.cols_edit.setValidator(QIntValidator(1, 9999, parent=self)) - - self.num1_label = QLabel('Subplot number:', self) - self.num1_edit = QLineEdit(str(num1), self) - self.num1_edit.setValidator(QIntValidator( - 1, max(1, (rows or 1)*(cols or 1)), self.num1_edit)) - - self.num2_label = QLabel('End of the plot', self) - self.num2_edit = QLineEdit(str(num2 or num1)) - self.num2_edit.setValidator(QIntValidator( - num1, max(1, (rows or 1)*(cols or 1)), self.num2_edit)) - - self.table = table = QTableWidget(self) - table.setSelectionMode(QAbstractItemView.ContiguousSelection) - table.resizeRowsToContents() - table.resizeColumnsToContents() - table.setEditTriggers(QAbstractItemView.NoEditTriggers) - self.setup_table() - self.cols_edit.textChanged.connect(lambda s: self.setup_table()) - self.rows_edit.textChanged.connect(lambda s: self.setup_table()) - self.num1_edit.textChanged.connect(self.set_selected_from_num1) - self.num1_edit.textChanged.connect(self.set_num2_validator) - self.num2_edit.textChanged.connect(self.set_selected_from_num2) - table.itemSelectionChanged.connect(self.update_num_edit) - - layout = QGridLayout() - layout.addWidget(self.fig_label, 0, 0) - layout.addWidget(self.fig_edit, 0, 1) - layout.addWidget(self.rows_label, 1, 0) - layout.addWidget(self.rows_edit, 1, 1) - layout.addWidget(self.cols_label, 2, 0) - layout.addWidget(self.cols_edit, 2, 1) - layout.addWidget(self.num1_label, 3, 0) - layout.addWidget(self.num1_edit, 3, 1) - layout.addWidget(self.num2_label, 4, 0) - layout.addWidget(self.num2_edit, 4, 1) - - layout.addWidget(self.table, 1, 2, 4, 4) - - self.setLayout(layout) - - @staticmethod - def create_subplot(fig=None, rows=1, cols=1, num1=1, num2=None, **kwargs): - """Create a subplot for the given figure - - Parameters - ---------- - fig: :class:`matplotlib.figure.Figure` or int - If integer, the :func:`matplotlib.pyplot.figure` function is used - rows: int - Number of rows for the gridspec - cols: int - Number of columns for the gridspec - num1: int - The subplot number of the upper left corner in the grid (starting - from 1!) - num2: None or int - The subplot number of the lower left corner in the grid (starting - from 1!). If None, `num1` will be used - ``**kwargs`` - Any other keyword argument for the - :meth:`matplotlib.figure.Figure.add_subplot` method - - Returns - ------- - mpl.axes.Subplot - The new created subplot""" - if not isinstance(fig, mpl.figure.Figure): - import matplotlib.pyplot as plt - fig = plt.figure(fig or next( - num for num in range(1, 1000) if num not in plt.get_fignums())) - if num1 == num2: - num2 = None - elif num2 is not None: - num2 = num2 - 1 - num1 = num1 - 1 - # first check if an axes with this specification already exists and if - # yes, return it - for ax in fig.axes: - ss = ax.get_subplotspec() - if ss.num1 == num1 and ( - ss.num2 == num2 or (ss.num2 is None and num1 == num2) or - (num2 is None and ss.num2 == num1)): - gs = ss.get_gridspec() - if gs.get_geometry() == (rows, cols): - return ax - # if it does not exist, create a new one - gs = mpl.gridspec.GridSpec(rows, cols) - ss = mpl.gridspec.SubplotSpec(gs, num1, num2) - return fig.add_subplot(ss, **kwargs) - - def setup_table(self): - """Set up the table based upon the number of rows and columns in the - rows and cols line edit""" - rows = int(self.rows_edit.text() or 0) - cols = int(self.cols_edit.text() or 0) - if not rows or not cols: - return - self.table.clear() - self.table.setRowCount(rows) - self.table.setColumnCount(cols) - selected = int(self.num1_edit.text() or 0) - if selected: - selected = (int(floor(selected / (cols + 1))), - ((selected % cols) - 1) % cols) - else: - selected = (0, 0) - for i, (row, col) in enumerate(product(range(rows), range(cols)), 1): - item = QTableWidgetItem(str(i)) - self.table.setItem(row, col, item) - self.table.resizeColumnsToContents() - self.table.resizeRowsToContents() - self.num1_edit.validator().setTop(max(1, rows*cols)) - self.set_num2_validator(self.num1_edit.text()) - self.set_selected_from_num1(self.num1_edit.text()) - - def set_num2_validator(self, s): - """Set the validator range for the num2 line edit""" - num1 = int(s or 1) - rows = int(self.rows_edit.text() or 0) - cols = int(self.cols_edit.text() or 0) - num2 = int(self.num2_edit.text() or num1) - self.num2_edit.setText(str(max(num1, num2))) - self.num2_edit.validator().setRange( - num1, max(1, (rows or 1)*(cols or 1))) - - def set_selected_from_num1(self, s): - """Update the selection of the table after changes of - :attr:`num1_edit`""" - self.table.clearSelection() - if not s: - return - num1 = int(s) - num2 = int(self.num2_edit.text() or num1) - self.set_selected(num1, num2) - - def set_selected_from_num2(self, s): - """Update the selection of the table after changes of :attr:`num2_edit` - """ - self.table.clearSelection() - if not s: - return - num2 = int(s) - num1 = int(self.num1_edit.text() or 0) - if not num1: - return - self.set_selected(num1, num2) - - def set_selected(self, num1, num2): - """Update the selection in the table based upon `num1` and `num2`""" - self.table.clearSelection() - rows = int(self.rows_edit.text() or 0) - cols = int(self.cols_edit.text() or 0) - if not rows or not cols: - return - sel_rows = range(int(floor(num1 / (cols + 1))), - int(floor(num2 / (cols + 1))) + 1) - sel_cols = range(((num1 % cols) - 1) % cols, - (((num2 % cols) - 1) % cols) + 1) - for item in starmap(self.table.item, product(sel_rows, sel_cols)): - if item: - self.table.blockSignals(True) - item.setSelected(True) - self.table.blockSignals(False) - - def update_num_edit(self): - """Update the :attr:`num1_edit` and :attr:`num2_edit` after the - selection of the table changed""" - items = self.table.selectedItems() - if not items: - return - sel_rows = [item.row() for item in items] - sel_cols = [item.column() for item in items] - cols = int(self.cols_edit.text() or 0) - self.num1_edit.blockSignals(True) - self.num1_edit.setText(str(min(sel_rows) * cols + min(sel_cols) + 1)) - self.num1_edit.blockSignals(False) - self.num2_edit.blockSignals(True) - self.num2_edit.setText(str(max(sel_rows) * cols + max(sel_cols) + 1)) - self.num2_edit.blockSignals(False) - - def get_iter(self): - """Get the iterator over the axes""" - fig_text = self.fig_edit.text() - if fig_text: - figs = repeat(fig_text) - else: - import matplotlib.pyplot as plt - figs = map(str, (num for num in range(1, 1000) - if num not in plt.get_fignums())) - num1 = self.num1_edit.text() or '1' - num2 = self.num2_edit.text() or num1 - return ('(%s, %s, %s, %s, %s)' % ( - fig, self.rows_edit.text() or '1', - self.cols_edit.text() or '1', num1, num2) - for fig in figs) - - -class AxesViewer(QGraphicsView): - """Widget to show a rectangle""" - - sizeChanged = QtCore.pyqtSignal(QtCore.QSize) - - def __init__(self, *args, **kwargs): - super(AxesViewer, self).__init__(*args, **kwargs) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) - self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) - - def resizeEvent(self, *args, **kwargs): - super(AxesViewer, self).resizeEvent(*args, **kwargs) - self.setSceneRect( - 0, 0, self.frameSize().width(), self.frameSize().height()) - self.sizeChanged.emit(self.size()) - - -class AxesCreator(QWidget): - """Widget to setup an axes in a arbitrary location""" - - def __init__(self, fig=None, x0=0.125, y0=0.1, x1=0.9, y1=0.9, - *args, **kwargs): - """ - Parameters - ---------- - fig: int or None - The figure number. If None, a new figure number will be used - x0: float - the x-coordinate of the lower left corner (between 0 and 1) - y0: float - the y-coordinate of the lower left corner (between 0 and 1) - x1: float - the x-coordinate of the upper right corner (between 0 and 1) - y1: float - the y-coordinate of the upper right corner (between 0 and 1) - """ - super(AxesCreator, self).__init__(*args, **kwargs) - self.fig_label = QLabel('Figure number:', self) - if fig is None: - import matplotlib.pyplot as plt - fig = next( - num for num in range(1, 1000) if num not in plt.get_fignums()) - self.fig_edit = QLineEdit(str(fig), self) - self.fig_edit.setValidator(QIntValidator()) - - self.x0_label = QLabel('Lower left x: ', self) - self.x0_edit = QLineEdit(str(x0), self) - self.x0_edit.setValidator(QDoubleValidator(0.0, 1.0, 5, - parent=self)) - - self.y0_label = QLabel('Lower left y: ', self) - self.y0_edit = QLineEdit(str(y0), self) - self.y0_edit.setValidator(QDoubleValidator(0.0, 1.0, 5, - parent=self)) - - self.x1_label = QLabel('Upper right x: ', self) - self.x1_edit = QLineEdit(str(x1), self) - self.x1_edit.setValidator(QDoubleValidator(0.0, 1.0, 5, - parent=self)) - - self.y1_label = QLabel('Upper right y: ', self) - self.y1_edit = QLineEdit(str(y1), self) - self.y1_edit.setValidator(QDoubleValidator(0.5, 1.0, 5, - parent=self)) - - self.graphics_scene = QGraphicsScene(self) - self.graphics_view = AxesViewer(self.graphics_scene) - - size = self.graphics_view.size() - width = size.width() * float(x1 - x0) - height = size.height() * float(y1 - y0) - x0_resized = size.width() * float(x0) - y0_resized = size.height() * float(y0) - - self.box_widget = QGraphicsRectItem( - x0_resized, y0_resized, width, height) - self.graphics_scene.addItem(self.box_widget) - self.graphics_view.sizeChanged.connect(self.resize_rectangle) - - layout = QGridLayout() - layout.addWidget(self.fig_label, 0, 0) - layout.addWidget(self.fig_edit, 0, 1) - layout.addWidget(self.x0_label, 1, 0) - layout.addWidget(self.x0_edit, 1, 1) - layout.addWidget(self.y0_label, 2, 0) - layout.addWidget(self.y0_edit, 2, 1) - layout.addWidget(self.x1_label, 3, 0) - layout.addWidget(self.x1_edit, 3, 1) - layout.addWidget(self.y1_label, 4, 0) - layout.addWidget(self.y1_edit, 4, 1) - - layout.addWidget(self.graphics_view, 1, 2, 4, 4) - - for w in [self.x0_edit, self.y0_edit, self.x1_edit, self.y1_edit]: - w.textChanged.connect(lambda s: self.resize_rectangle( - self.graphics_view.size())) - - self.setLayout(layout) - - def resize_rectangle(self, size): - """resize the rectangle after changes of the widget size""" - coords = [self.x0_edit.text(), self.y0_edit.text(), - self.x1_edit.text(), self.y1_edit.text()] - if any(not c for c in coords): - return - x0, y0, x1, y1 = map(float, coords) - width = size.width() * float(x1 - x0) - height = size.height() * float(y1 - y0) - x0_resized = size.width() * float(x0) - y1_resized = size.height() * float(1.0 - y1) - self.box_widget.setRect(x0_resized, y1_resized, width, height) - - @staticmethod - def create_axes(fig, x0, y0, x1, y1, **kwargs): - """ - Create an axes for the given `fig` - - Parameters - ---------- - fig: int or None - The figure number. If None, a new figure number will be used - x0: float - the x-coordinate of the lower left corner (between 0 and 1) - y0: float - the y-coordinate of the lower left corner (between 0 and 1) - x1: float - the x-coordinate of the upper right corner (between 0 and 1) - y1: float - the y-coordinate of the upper right corner (between 0 and 1) - ``**kwargs`` - Any other keyword argument for the - :meth:`matplotlib.figure.Figure.add_axes` method - """ - if not isinstance(fig, mpl.figure.Figure): - import matplotlib.pyplot as plt - fig = plt.figure(fig or next( - num for num in range(1, 1000) if num not in plt.get_fignums())) - x1 = max([x0, x1]) - y1 = max([y0, y1]) - bbox = mpl.transforms.Bbox.from_extents(x0, y0, x1, y1) - points = np.round(bbox.get_points(), 5) - for ax in fig.axes: - if (np.round(ax.get_position().get_points(), 5) == points).all(): - return ax - return fig.add_axes(bbox, **kwargs) - - def get_iter(self): - """Get the iterator over the axes""" - fig_text = self.fig_edit.text() - if fig_text: - figs = repeat(fig_text) - else: - import matplotlib.pyplot as plt - figs = map(str, (num for num in range(1, 1000) - if num not in plt.get_fignums())) - left = self.x0_edit.text() or '0.125' - bottom = self.y0_edit.text() or '0.1' - width = self.x1_edit.text() or '0.9' - height = self.y1_edit.text() or '0.9' - return ('(%s, %s, %s, %s, %s)' % (fig, left, bottom, width, height) - for fig in figs) - - -class AxesSelector(QWidget): - """Widget to select an already created axes - - Click the button, select your axes and click the button again""" - - def __init__(self, *args, **kwargs): - super(AxesSelector, self).__init__(*args, **kwargs) - self.bt_choose = QPushButton('Click to select axes', self) - self.bt_choose.setCheckable(True) - self.msg_label = QLabel('', self) - - self.result_label = QLabel('', self) - - self.layout = QVBoxLayout() - self.layout.addWidget(self.bt_choose) - self.layout.addWidget(self.msg_label) - self.layout.addWidget(self.result_label) - - self.setLayout(self.layout) - - self.bt_choose.clicked.connect(self.change_pickers) - - def change_pickers(self, b): - """Change the pickers of the axes instances - - If the push button is clicked, we replace the existing pickers of the - axes in order to select the plots. Otherwise we restore them""" - if self.bt_choose.isChecked(): - self.bt_choose.setText('Click when finished') - self.msg_label.setText('Select an existing axes') - self.result_label.setText('') - self.allow_axes_select() - else: - self.bt_choose.setText('Select an axes') - self.msg_label.setText('') - self.restore_pickers() - - def unclick(self): - """Restore the original pickers""" - if self.bt_choose.isChecked(): - self.bt_choose.click() - - def allow_axes_select(self): - """Replace make all axes pickable""" - import matplotlib.pyplot as plt - self.fig_events = d = {} - self.pickers = pickers = defaultdict(dict) - for num in plt.get_fignums(): - fig = plt.figure(num) - d[num] = fig.canvas.mpl_connect('pick_event', self.get_picked_ax) - for ax in fig.axes: - pickers[num][ax] = ax.get_picker() - ax.set_picker(True) - - def restore_pickers(self): - """Restore the original pickers of the existing axes instances""" - import matplotlib.pyplot as plt - for num, cid in self.fig_events.items(): - plt.figure(num).canvas.mpl_disconnect(cid) - for artist, picker in self.pickers[num].items(): - artist.set_picker(picker) - self.fig_events.clear() - self.pickers.clear() - - def get_picked_ax(self, event): - """Function to be called when an axes is picked""" - try: - ax = event.artist.axes - except AttributeError: - ax = event.artist.get_axes() - text = self.result_label.text() - if text: - text += ';;' - self.result_label.setText( - text + self.inspect_axes(ax)) - - def inspect_axes(self, ax): - """Inspect the given axes and get the right string for making a plot - with it""" - from matplotlib.axes import SubplotBase - if isinstance(ax, SubplotBase): - ss = ax.get_subplotspec() - gs = ss.get_gridspec() - rows, cols = gs.get_geometry() - return '(%i, %i, %i, %i, %i)' % ( - ax.get_figure().number, rows, cols, ss.num1 + 1, - (ss.num2 or ss.num1) + 1) - else: - box = ax.get_position() - points = np.round(box.get_points().ravel(), 5).tolist() - return '(%i, %1.5f, %1.5f, %1.5f, %1.5f)' % tuple( - [ax.get_figure().number] + points) - - def setVisible(self, b): - """Reimplemented to restore the pickers if the widget is made invisible - """ - super(AxesSelector, self).setVisible(b) - if not self.isVisible(): - self.unclick() - - def close(self): - """Reimplemented to restore the pickers if the widget is closed - """ - self.unclick() - return super(AxesSelector, self).close() - - def get_iter(self): - """Get the iterator over the axes""" - return (txt for txt in cycle(self.result_label.text().split(';;'))) - - -class AxesCreatorCollection(QDialog): - """Wrapper for a QToolBox that holds the different possibilities to select - an axes - - When the user finished, the :attr:`okpressed` symbol is emitted with an - infinite iterator of strings. Possible widgets for the toolbox are - determined by the :attr:`widgets` attribute""" - - #: signal that is emitted when the 'Ok' pushbutton is pressed and the user - #: finished the selection - okpressed = QtCore.pyqtSignal(types.GeneratorType) - - #: key, title and class fot the widget that is used to create an - #: axes - widgets = [('subplot', 'Subplot in a grid', SubplotCreator), - ('axes', 'Arbitray position', AxesCreator), - ('choose', 'Existing subplot', AxesSelector)] - - def __init__(self, key=None, func_kwargs={}, *args, **kwargs): - """ - Parameters - ---------- - key: str or None - if string, it must be one of the keys in the :attr:`widgets` - attribute - func_kwargs: dict - a dictionary that is passed to the class constructor determined by - the `key` parameter if `key` is not None - ``*args,**kwargs`` - Determined by the QWidget class""" - super(AxesCreatorCollection, self).__init__(*args, **kwargs) - self.bt_cancel = QPushButton('Cancel', self) - self.bt_ok = QPushButton('Ok', self) - - self.tb = QTabWidget(self) - self.tb.setTabPosition(QTabWidget.West) - current = 0 - for i, (func_name, title, cls) in enumerate(self.widgets): - if func_name == key: - current = i - w = cls(**func_kwargs) - else: - w = cls() - self.tb.addTab(w, title) - - self.tb.setCurrentIndex(current) - - self.bt_ok.clicked.connect(self.create_subplot) - self.bt_ok.clicked.connect(self.close) - self.bt_cancel.clicked.connect(self.close) - - layout = QVBoxLayout() - layout.addWidget(self.tb) - - hbox = QHBoxLayout() - hbox.addStretch(0) - hbox.addWidget(self.bt_cancel) - hbox.addWidget(self.bt_ok) - layout.addLayout(hbox) - - self.setLayout(layout) - - def create_subplot(self): - """Method that is called whenn the ok button is pressed. - - It emits the :attr:`okpressed` signal with the iterator of the current - widget in the toolbox""" - it = self.tb.currentWidget().get_iter() - self.okpressed.emit(it) - - def close(self): - """reimplemented to make sure that all widgets are closed when this one - is closed""" - for w in map(self.tb.widget, range(len(self.widgets))): - w.close() - return super(AxesCreatorCollection, self).close() - - -class PlotCreator(QDialog): - """ - Widget to extract data from a dataset and eventually create a plot""" - - #: Tooltip for not making a plot - NO_PM_TT = 'Choose a plot method (or choose none to only extract the data)' - - _preset = None - - def __init__(self, *args, **kwargs): - self.help_explorer = kwargs.pop('help_explorer', None) - super(PlotCreator, self).__init__(*args, **kwargs) - self.setAttribute(Qt.WA_DeleteOnClose) - self.setWindowTitle('Create plots') - self.error_msg = PyErrorMessage(self) - mp = psy.gcp(True) - - self.splitter = splitter = QSplitter(Qt.Vertical, parent=self) - self.w = w = QWidget(self) - self.fmt_tree_widget = QWidget(self) - - # --------------------------------------------------------------------- - # -------------------------- children --------------------------------- - # --------------------------------------------------------------------- - - self.ds_combo = QComboBox(parent=w) - self.ds_combo.setToolTip('The data source to use the data from') - self.fill_ds_combo(mp) - self.bt_open_file = QToolButton(parent=w) - self.bt_open_file.setIcon(QIcon(get_icon('run_arrow.png'))) - self.bt_open_file.setToolTip('Open a new dataset from the hard disk') - self.bt_get_ds = LoadFromConsoleButton(xarray.Dataset, parent=w) - self.bt_get_ds.setToolTip( - 'Use a dataset already defined in the console') - - self.pm_label = QLabel('Plot method: ', w) - self.pm_combo = QComboBox(w) - self.fill_plot_method_combo() - self.bt_load_preset = QPushButton("Preset") - self.bt_load_preset.setEnabled(False) - self.pm_info = QToolButton(w) - self.pm_info.setIcon(QIcon(get_icon('info.png'))) - self.pm_info.setToolTip('Show information in the help explorer') - - self.variables_table = VariablesTable(self.get_ds, parent=w) - self.variables_table.fill_from_ds() - - self.coords_table = CoordsTable(self.get_ds, parent=w) - self.coords_table.fill_from_ds() - - self.array_table = ArrayTable(self.get_ds, parent=w) - self.array_table.setup_from_ds(plot_method=self.pm_combo.currentText()) - - self.cbox_load = QCheckBox('load') - self.cbox_load.setToolTip( - 'Load the selected data arrays into memory when clicking on ' - 'Ok. Note that this might cause problems for large ' - 'arrays!') - - self.cbox_close_popups = QCheckBox('close dropdowns', w) - self.cbox_close_popups.setChecked(True) - self.cbox_close_popups.setToolTip( - 'Close drop down menues after selecting indices to plot') - self.cbox_use_coords = QCheckBox('show coordinates', w) - self.cbox_use_coords.setChecked(False) - self.cbox_use_coords.setToolTip( - 'Show the real coordinates instead of the indices in the drop ' - 'down menues') - self.bt_remove_all = QToolButton(w) - self.bt_remove_all.setIcon(QIcon(get_icon('minusminus.png'))) - self.bt_remove_all.setToolTip('Remove all arrays') - self.bt_remove = QToolButton(w) - self.bt_remove.setIcon(QIcon(get_icon('minus.png'))) - self.bt_remove.setToolTip('Remove selected arrays') - self.bt_add = QToolButton(w) - self.bt_add.setIcon(QIcon(get_icon('plus.png'))) - self.bt_add.setToolTip('Add arrays for the selected variables') - self.bt_add_all = QToolButton(w) - self.bt_add_all.setIcon(QIcon(get_icon('plusplus.png'))) - self.bt_add_all.setToolTip( - 'Add arrays for all variables in the dataset') - - self.rows_axis_label = QLabel('No. of rows', w) - self.rows_axis_edit = QLineEdit(w) - self.rows_axis_edit.setText('1') - self.cols_axis_label = QLabel('No. sof columns', w) - self.cols_axis_edit = QLineEdit(w) - self.cols_axis_edit.setText('1') - self.max_axis_label = QLabel('No. of axes per figure', w) - self.max_axis_edit = QLineEdit(w) - self.bt_add_axes = QPushButton('Add new subplots', w) - self.bt_add_axes.setToolTip( - 'Adds subplots for the selected arrays based the specified number ' - 'of rows and columns') - - self.row_axis_label = QLabel('Row number:', w) - self.row_axis_edit = QLineEdit(w) - self.row_axis_edit.setText('1') - self.col_axis_label = QLabel('Column number', w) - self.col_axis_edit = QLineEdit(w) - self.col_axis_edit.setText('1') - self.bt_add_single_axes = QPushButton('Add one subplot', w) - self.bt_add_single_axes.setToolTip( - 'Add one subplot for the specified row and column') - - self.fmt_tree_label = QLabel( - "Modify the formatoptions of the newly created plots." - "Values must be entered in yaml syntax", - parent=self.fmt_tree_widget) - - self.fmt_tree = RcParamsTree(None, None, None, - parent=self.fmt_tree_widget) - self.fmt_tree.value_col = 3 - self.fmt_tree.setColumnCount(4) - self.fmt_tree.setHeaderLabels(['Formatoption', '', '', 'Value']) - - # --------------------------------------------------------------------- - # ---------------------------- connections ---------------------------- - # --------------------------------------------------------------------- - - # ----------------- dataset combo connections ------------------------ - self.bt_open_file.clicked.connect(lambda: self.open_dataset()) - self.bt_get_ds.object_loaded.connect(self.add_new_ds) - self.ds_combo.currentIndexChanged[int].connect(self.set_ds) - - self.ds_combo.currentIndexChanged[int].connect( - lambda i: self.variables_table.fill_from_ds()) - self.ds_combo.currentIndexChanged[int].connect( - lambda i: self.coords_table.fill_from_ds()) - self.ds_combo.currentIndexChanged[int].connect( - lambda i: self.array_table.setup_from_ds()) - self.ds_combo.currentIndexChanged[int].connect( - lambda i: self.connect_combo_boxes()) - - # ------------------- plot method connections ------------------------- - self.pm_combo.currentIndexChanged[str].connect( - lambda s: self.pm_combo.setToolTip( - getattr(psy.plot, s)._summary) if s else self.NO_PM_TT) - self.pm_info.clicked.connect(self.show_pm_info) - self.pm_combo.currentIndexChanged[str].connect(self.array_table.set_pm) - self.pm_combo.currentIndexChanged[str].connect(self.fill_fmt_tree) - - # ------------------- preset button connections ----------------------- - self.bt_load_preset.clicked.connect(self.load_preset) - - # --------------------- Combo box connections ------------------------- - self.cbox_close_popups.clicked.connect(self.toggle_close_popups) - self.cbox_use_coords.clicked.connect(self.reset_comboboxes) - # connect leftclick of combo boxes to create new arrays or update the - # selected - self.connect_combo_boxes() - - # ----------------- add and remove button connections ----------------- - self.bt_add.clicked.connect(lambda b: self.insert_array( - variables=self.variables_table.selected_variables)) - self.bt_add_all.clicked.connect( - lambda b: self.insert_array( - variables=self.variables_table.variables)) - self.bt_remove_all.clicked.connect( - lambda b: self.array_table.remove_arrays(False)) - self.bt_remove.clicked.connect( - lambda b: self.array_table.remove_arrays(True)) - - # ------------- axes creation connections ----------------------------- - self.rows_axis_edit.returnPressed.connect(self.bt_add_axes.click) - self.cols_axis_edit.returnPressed.connect(self.bt_add_axes.click) - self.max_axis_edit.returnPressed.connect(self.bt_add_axes.click) - self.bt_add_axes.clicked.connect(self.setup_subplots) - self.row_axis_edit.returnPressed.connect(self.bt_add_single_axes.click) - self.col_axis_edit.returnPressed.connect(self.bt_add_single_axes.click) - self.bt_add_single_axes.clicked.connect(self.setup_subplot) - - # -------------------- create and cancel connections ------------------ - self.bbox = bbox = QDialogButtonBox(QDialogButtonBox.Ok | - QDialogButtonBox.Cancel) - bbox.accepted.connect(self.create_plots) - bbox.rejected.connect(self.reject) - - # -------------------- other connections ------------------------------ - # allow only to select either variables or newly created arrays in - # order to control the behaviour of the combo box left click in - # self.insert_array_from_combo - self.array_table.itemSelectionChanged.connect( - self.variables_table.clearSelection) - self.variables_table.itemSelectionChanged.connect( - self.array_table.clearSelection) - - # --------------------------------------------------------------------- - # ---------------------------- layouts -------------------------------- - # --------------------------------------------------------------------- - - self.ds_box = QHBoxLayout() - self.ds_box.addWidget(self.ds_combo) - self.ds_box.addWidget(self.bt_open_file) - self.ds_box.addWidget(self.bt_get_ds) - - self.pm_box = QHBoxLayout() - self.pm_box.addStretch(0) - self.pm_box.addWidget(self.pm_label) - self.pm_box.addWidget(self.pm_combo) - self.pm_box.addWidget(self.bt_load_preset) - self.pm_box.addWidget(self.pm_info) - - self.tree_box = QHBoxLayout() - self.tree_box.addStretch(0) - self.tree_box.addWidget(self.cbox_load) - self.tree_box.addWidget(self.cbox_close_popups) - self.tree_box.addWidget(self.cbox_use_coords) - self.tree_box.addWidget(self.bt_remove_all) - self.tree_box.addWidget(self.bt_remove) - self.tree_box.addWidget(self.bt_add) - self.tree_box.addWidget(self.bt_add_all) - - self.axes_box = QGridLayout() - self.axes_box.addWidget(self.max_axis_label, 0, 0) - self.axes_box.addWidget(self.max_axis_edit, 0, 1) - self.axes_box.addWidget(self.rows_axis_label, 0, 2) - self.axes_box.addWidget(self.rows_axis_edit, 0, 3) - self.axes_box.addWidget(self.cols_axis_label, 0, 4) - self.axes_box.addWidget(self.cols_axis_edit, 0, 5) - self.axes_box.addWidget(self.bt_add_axes, 0, 6) - self.axes_box.addWidget(self.row_axis_label, 1, 2) - self.axes_box.addWidget(self.row_axis_edit, 1, 3) - self.axes_box.addWidget(self.col_axis_label, 1, 4) - self.axes_box.addWidget(self.col_axis_edit, 1, 5) - self.axes_box.addWidget(self.bt_add_single_axes, 1, 6) - - self.vbox = QVBoxLayout() - self.vbox.addLayout(self.ds_box) - self.vbox.addLayout(self.pm_box) - self.vbox.addLayout(self.tree_box) - self.vbox.addWidget(self.variables_table) - self.vbox.addWidget(self.coords_table) - self.vbox.addWidget(self.array_table) - self.vbox.addLayout(self.axes_box) - self.vbox.addWidget(self.bbox) - - w.setLayout(self.vbox) - - fmt_tree_layout = QVBoxLayout() - fmt_tree_layout.addWidget(self.fmt_tree_label) - fmt_tree_layout.addWidget(self.fmt_tree) - self.fmt_tree_widget.setLayout(fmt_tree_layout) - - splitter.addWidget(w) - - splitter.addWidget(self.fmt_tree_widget) - - hbox = QHBoxLayout(self) - hbox.addWidget(splitter) - self.setLayout(hbox) - self.fill_fmt_tree(self.pm_combo.currentText()) - - def toggle_close_popups(self): - """Change the automatic closing of popups""" - close_popups = self.cbox_close_popups.isChecked() - for cb in self.coords_table.combo_boxes: - cb.close_popups = close_popups - - def reset_comboboxes(self): - """Clear all comboboxes""" - use_coords = self.cbox_use_coords.isChecked() - for cb in self.coords_table.combo_boxes: - cb.use_coords = use_coords - cb.clear() - cb._is_empty = True - - def fill_fmt_tree(self, pm): - import psyplot.project as psy - self.fmt_tree.clear() - if not pm: - self.fmt_tree_widget.setVisible(False) - self.bt_load_preset.setEnabled(False) - else: - pm = getattr(psy.plot, pm) - plotter = pm.plotter_cls() - if self._preset: - plotter.update(psy.Project.extract_fmts_from_preset( - self._preset, pm)) - self.fmt_tree.rc = plotter - self.fmt_tree.validators = { - key: getattr(plotter, key).validate for key in plotter} - self.fmt_tree.descriptions = { - key: getattr(plotter, key).name for key in plotter} - self.fmt_tree.initialize() - icon = QIcon(get_icon('info.png')) - docs_funcs = { - key: partial(plotter.show_docs, key) for key in plotter} - for item in self.fmt_tree.top_level_items: - key = item.text(0) - bt = QToolButton() - bt.setIcon(icon) - bt.clicked.connect(docs_funcs[key]) - self.fmt_tree.setItemWidget(item, 2, bt) - self.fmt_tree.resizeColumnToContents(2) - self.fmt_tree_widget.setVisible(True) - self.bt_load_preset.setEnabled(True) - - def setup_subplots(self): - """Method to be emitted to setup the subplots for the selected arrays - on new figures""" - rows = int(self.rows_axis_edit.text()) - cols = int(self.cols_axis_edit.text()) - maxn = int(self.max_axis_edit.text() or 0) - self.array_table.add_subplots(rows, cols, maxn) - - def setup_subplot(self): - """Method to be emitted to setup one subplot at a specific location - for each of the selected arrays on separate (new) figures""" - rows = int(self.rows_axis_edit.text()) - cols = int(self.cols_axis_edit.text()) - row = int(self.row_axis_edit.text()) - col = int(self.col_axis_edit.text()) - self.array_table.add_single_subplot(rows, cols, row, col) - - def show_pm_info(self): - """Shows info on the current plotting method in the help explorer""" - if self.help_explorer is None: - return - pm_name = self.pm_combo.currentText() - if pm_name: - self.help_explorer.show_help(getattr(psy.plot, pm_name), - 'psyplot.project.plot.' + pm_name) - else: - self.help_explorer.show_rst(""" - No plot - ======= - No plot will be created, only the data is extracted""", 'no_plot') - - def connect_combo_boxes(self): - for cb in self.coords_table.combo_boxes: - cb.leftclick.connect(self.insert_array_from_combo) - - def fill_plot_method_combo(self): - """Takes the names of the plotting methods in the current project""" - self.pm_combo.addItems([''] + sorted(psy.plot._plot_methods)) - self.pm_combo.setToolTip(self.NO_PM_TT) - - def set_pm(self, plot_method): - self.pm_combo.setCurrentIndex( - self.pm_combo.findText(plot_method or '')) - - def create_plots(self): - """Method to be called when the `Create plot` button is pressed - - This method reads the data from the :attr:`array_table` attribute and - makes the plot (or extracts the data) based upon the - :attr:`plot_method` attribute""" - import matplotlib.pyplot as plt - names = self.array_table.arr_names_dict - pm = self.pm_combo.currentText() - if pm: - pm = getattr(psy.plot, pm) - for d, (default_dim, default_slice) in product( - six.itervalues(names), six.iteritems(pm._default_dims)): - d.setdefault(default_dim, default_slice) - kwargs = {'ax': self.array_table.axes, - 'fmt': {t[1]: t[2] for t in self.fmt_tree._get_rc()}} - else: - pm = self.open_data - kwargs = {} - fig_nums = plt.get_fignums()[:] - try: - pm(self.ds, arr_names=names, load=self.cbox_load.isChecked(), - **kwargs) - except Exception: - for num in set(plt.get_fignums()).difference(fig_nums): - plt.close(num) - self.error_msg.showTraceback('Failed to create the plots!') - logger.debug('Error while creating the plots with %s!', - names, exc_info=True) - else: - self.close() - - def load_preset(self): - """Load a preset file""" - fname, ok = QFileDialog.getOpenFileName( - self, 'Load preset', os.path.join(get_configdir(), 'presets'), - 'YAML files (*.yml *.yaml);;' - 'All files (*)') - if ok: - self.set_preset(fname) - - def open_dataset(self, fnames=None, *args, **kwargs): - """Opens a file dialog and the dataset that has been inserted""" - - def open_ds(): - if len(fnames) == 1: - kwargs.pop('concat_dim', None) - return psy.open_dataset(fnames[0], *args, **kwargs) - else: - return psy.open_mfdataset(fnames, *args, **kwargs) - - if fnames is None: - fnames = QFileDialog.getOpenFileNames( - self, 'Open dataset', os.getcwd(), - 'NetCDF files (*.nc *.nc4);;' - 'Shape files (*.shp);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fnames = fnames[0] - if isinstance(fnames, xarray.Dataset): - ds = fnames - self.add_new_ds('ds', ds) - elif not fnames: - return - else: - try: - ds = open_ds() - except Exception: - kwargs['decode_times'] = False - try: - ds = open_ds() - except Exception: - self.error_msg.showTraceback( - 'Could not open dataset %s' % (fnames, )) - return - fnames_str = ', '.join(fnames) - self.add_new_ds(fnames_str, ds, fnames_str) - - def set_preset(self, preset): - import psyplot.project as psy - self._preset = psy.Project._load_preset(preset) - if self.fmt_tree_widget.isVisible(): - self.fill_fmt_tree(self.pm_combo.currentText()) - - def add_new_ds(self, oname, ds, fname=None): - d = {'ds': ds} - if fname: - d['fname'] = fname - self.ds_descs.insert(0, d) - self.ds_combo.insertItem(0, 'New: ' + oname) - self.ds_combo.setCurrentIndex(0) - - def set_ds(self, i): - """Set the current dataset""" - self.ds = self.ds_descs[i]['ds'] - - def fill_ds_combo(self, project): - """fill the dataset combobox with datasets of the current main project - """ - self.ds_combo.clear() - self.ds_combo.setInsertPolicy(QComboBox.InsertAtBottom) - ds_descs = project._get_ds_descriptions( - project.array_info(ds_description='all')) - self.ds_combo.addItems( - ['%i: %s' % (i, ds_desc['fname']) for i, ds_desc in six.iteritems( - ds_descs)]) - self.ds_descs = list(ds_descs.values()) - if len(self.ds_descs): - self.set_ds(0) - - def insert_array_from_combo(self, cb, variables=None): - """Insert new arrays into the dataset when the combobox is left-clicked - """ - if variables is None: - variables = self.variables_table.selected_variables - dims = {} - for other_cb in self.coords_table.combo_boxes: - ind = other_cb.currentIndex() - dims[other_cb.dim] = str((ind - 1) if ind not in [-1, 0] else '') - dim = cb.dim - inserts = list( - str(ind.row() - 1) - for ind in cb.view().selectionModel().selectedIndexes() - if ind.row() > 0) - dims.pop(dim) - for name, val in product(variables, inserts): - dims[dim] = val - self.array_table.insert_array(name, check=False, **dims) - if len(inserts) > 1: - inserts = '%s:%s' % (min(inserts), max(inserts)) - elif inserts: - inserts = inserts[0] - else: - return - self.array_table.update_selected(check=False, dims={dim: inserts}) - self.array_table.check_arrays() - - def insert_array(self, variables=None): - """Inserts an array for the given variables (or the ones selected in - the :attr:`variable_table` if `variables` is None) - """ - if variables is None: - variables = self.variables_table.selected_variables - dims = {} - for other_cb in self.coords_table.combo_boxes: - ind = other_cb.currentIndex() - dims[other_cb.dim] = str((ind - 1) if ind not in [-1, 0] else '') - for name in variables: - self.array_table.insert_array(name, check=False, **dims) - self.array_table.check_arrays() - - def get_ds(self, i=None): - """Get the dataset - - Parameters - ---------- - i: int or None - If None, the dataset of the current index in the `ds_combo` is - returned. Otherwise it specifies the locdation of the dictionary in - the :attr:`ds_descs` attribute - - Returns - ------- - xarray.Dataset - The requested dataset""" - if i is None: - i = self.ds_combo.currentIndex() - if not len(self.ds_descs): - return - return self.ds_descs[i]['ds'] - - def close(self, *args, **kwargs): - """Reimplemented to make sure that the data sets are deleted""" - super(PlotCreator, self).close(*args, **kwargs) - if hasattr(self, 'ds_descs'): - del self.ds_descs - - def open_data(self, *args, **kwargs): - """Convenience method to create a sub project without a plotter - - This method is used when the :attr:`pm_combo` is empty""" - p = psy.Project.from_dataset(*args, main=psy.gcp(True), **kwargs) - psy.scp(p) - - def switch2ds(self, ds): - """Switch to the given dataset - - Parameters - ---------- - ds: xarray.Dataset - The dataset to use. It is assumed that this dataset is already - in the dataset combobox""" - for i, desc in enumerate(self.ds_descs): - if desc['ds'] is ds: - self.ds_combo.setCurrentIndex(i) - return - - def keyPressEvent(self, e): - """Reimplemented to close the window when escape is hitted""" - if e.key() == QtCore.Qt.Key_Escape: - self.close() - else: - super(PlotCreator, self).keyPressEvent(e) diff --git a/psyplot_gui/preferences.py b/psyplot_gui/preferences.py deleted file mode 100644 index 11f5ad3..0000000 --- a/psyplot_gui/preferences.py +++ /dev/null @@ -1,659 +0,0 @@ -"""Preferences widget for psyplot_gui - -This module defines the :class:`Preferences` widget that creates an interface -to the rcParams of psyplot and psyplot_gui""" -import yaml -from warnings import warn -from psyplot_gui.compat.qtcompat import ( - QTreeWidget, QTreeWidgetItem, Qt, QMenu, QAction, QTextEdit, QIcon, - QWidget, QVBoxLayout, QHBoxLayout, QtCore, QDialog, QScrollArea, - QDialogButtonBox, QStackedWidget, QListWidget, QListView, QSplitter, - QListWidgetItem, QPushButton, QFileDialog, with_qt5, - QAbstractItemView, QToolButton, QLabel, QtGui, asstring) -from psyplot_gui.common import get_icon -from psyplot_gui import rcParams as rcParams -from psyplot.config.rcsetup import ( - psyplot_fname, RcParams, rcParams as psy_rcParams) - - -class ConfigPage(object): - """An abstract base class for configuration pages""" - - #: A signal that shall be emitted if the validation state changes - validChanged = QtCore.pyqtSignal(bool) - - #: A signal that is emitted if changes are propsed. The signal should be - #: emitted with the instance of the page itself - propose_changes = QtCore.pyqtSignal(object) - - #: The title for the config page - title = None - - #: The icon of the page - icon = None - - #: :class:`bool` that is True, if the changes in this ConfigPage are set - #: immediately - auto_updates = False - - @property - def is_valid(self): - """Check whether the page is valid""" - raise NotImplementedError - - @property - def changed(self): - """Check whether the preferences will change""" - raise NotImplementedError - - def initialize(self): - """Initialize the page""" - raise NotImplementedError - - def apply_changes(self): - """Apply the planned changes""" - raise NotImplementedError - - -class RcParamsTree(QTreeWidget): - """A QTreeWidget that can be used to display a RcParams instance - - This widget is populated by a :class:`psyplot.config.rcsetup.RcParams` - instance and displays whether the values are valid or not""" - - #: A signal that shall be emitted if the validation state changes - validChanged = QtCore.pyqtSignal(bool) - - #: A signal that is emitted if changes are propsed. It is either emitted - #: with the parent of this instance (if this is not None) or with the - #: instance itself - propose_changes = QtCore.pyqtSignal(object) - - #: The :class:`~psyplot.config.rcsetup.RcParams` to display - rc = None - - #: list of :class:`bool`. A boolean for each rcParams key that states - #: whether the proposed value is valid or not - valid = [] - - value_col = 2 - - def __init__(self, rcParams, validators, descriptions, *args, **kwargs): - """ - Parameters - ---------- - rcParams: dict - The dictionary that contains the rcParams - validators: dict - A mapping from the `rcParams` key to the validation function for - the corresponding value - descriptions: dict - A mapping from the `rcParams` key to it's description - - See Also - -------- - psyplot.config.rcsetup.RcParams - psyplot.config.rcsetup.RcParams.validate - psyplot.config.rcsetup.RcParams.descriptions - """ - super(RcParamsTree, self).__init__(*args, **kwargs) - self.rc = rcParams - self.validators = validators - self.descriptions = descriptions - self.setContextMenuPolicy(Qt.CustomContextMenu) - self.customContextMenuRequested.connect(self.open_menu) - self.setColumnCount(self.value_col + 1) - self.setHeaderLabels(['RcParams key', '', 'Value']) - - @property - def is_valid(self): - """True if all the proposed values in this tree are valid""" - return all(self.valid) - - @property - def top_level_items(self): - """An iterator over the topLevelItems in this tree""" - return map(self.topLevelItem, range(self.topLevelItemCount())) - - def initialize(self): - """Fill the items of the :attr:`rc` into the tree""" - rcParams = self.rc - descriptions = self.descriptions - self.valid = [True] * len(rcParams) - validators = self.validators - vcol = self.value_col - for i, (key, val) in enumerate(sorted(rcParams.items())): - item = QTreeWidgetItem(0) - item.setText(0, key) - item.setToolTip(0, key) - item.setIcon(1, QIcon(get_icon('valid.png'))) - desc = descriptions.get(key) - if desc: - item.setText(vcol, desc) - item.setToolTip(vcol, desc) - child = QTreeWidgetItem(0) - item.addChild(child) - self.addTopLevelItem(item) - editor = QTextEdit(self) - # set maximal height of the editor to 3 rows - editor.setMaximumHeight( - 4 * QtGui.QFontMetrics(editor.font()).height()) - editor.setPlainText(yaml.dump(val)) - self.setItemWidget(child, vcol, editor) - editor.textChanged.connect( - self.set_icon_func(i, item, validators[key])) - self.resizeColumnToContents(0) - self.resizeColumnToContents(1) - - def set_icon_func(self, i, item, validator): - """Create a function to change the icon of one topLevelItem - - This method creates a function that can be called when the value of an - item changes to display it's valid state. The returned function changes - the icon of the given topLevelItem depending on - whether the proposed changes are valid or not and it modifies the - :attr:`valid` attribute accordingly - - Parameters - ---------- - i: int - The index of the topLevelItem - item: QTreeWidgetItem - The topLevelItem - validator: func - The validation function - - Returns - ------- - function - The function that can be called to set the correct icon""" - def func(): - editor = self.itemWidget(item.child(0), self.value_col) - s = asstring(editor.toPlainText()) - try: - val = yaml.load(s, Loader=yaml.Loader) - except Exception as e: - item.setIcon(1, QIcon(get_icon('warning.png'))) - item.setToolTip(1, "Could not parse yaml code: %s" % e) - self.set_valid(i, False) - return - try: - validator(val) - except Exception as e: - item.setIcon(1, QIcon(get_icon('invalid.png'))) - item.setToolTip(1, "Wrong value: %s" % e) - self.set_valid(i, False) - else: - item.setIcon(1, QIcon(get_icon('valid.png'))) - self.set_valid(i, True) - self.propose_changes.emit(self.parent() or self) - return func - - def set_valid(self, i, b): - """Set the validation status - - If the validation status changed compared to the old one, the - :attr:`validChanged` signal is emitted - - Parameters - ---------- - i: int - The index of the topLevelItem - b: bool - The valid state of the item - """ - old = self.is_valid - self.valid[i] = b - new = self.is_valid - if new is not old: - self.validChanged.emit(new) - - def open_menu(self, position): - """Open a menu to expand and collapse all items in the tree - - Parameters - ---------- - position: QPosition - The position where to open the menu""" - menu = QMenu() - expand_all_action = QAction('Expand all', self) - expand_all_action.triggered.connect(self.expandAll) - menu.addAction(expand_all_action) - collapse_all_action = QAction('Collapse all', self) - collapse_all_action.triggered.connect(self.collapseAll) - menu.addAction(collapse_all_action) - menu.exec_(self.viewport().mapToGlobal(position)) - - def changed_rc(self, use_items=False): - """Iterate over the changed rcParams - - Parameters - ---------- - use_items: bool - If True, the topLevelItems are used instead of the keys - - Yields - ------ - QTreeWidgetItem or str - The item identifier - object - The proposed value""" - def equals(item, key, val, orig): - return val != orig - for t in self._get_rc(equals): - yield t[0 if use_items else 1], t[2] - - def selected_rc(self, use_items=False): - """Iterate over the selected rcParams - - Parameters - ---------- - use_items: bool - If True, the topLevelItems are used instead of the keys - - Yields - ------ - QTreeWidgetItem or str - The item identifier - object - The proposed value""" - def is_selected(item, key, val, orig): - return item.isSelected() - for t in self._get_rc(is_selected): - yield t[0 if use_items else 1], t[2] - - def _get_rc(self, filter_func=None): - """Iterate over the rcParams - - This function applies the given `filter_func` to check whether the - item should be included or not - - Parameters - ---------- - filter_func: function - A function that accepts the following arguments: - - item - The QTreeWidgetItem - key - The rcParams key - val - The proposed value - orig - The current value - - Yields - ------ - QTreeWidgetItem - The corresponding topLevelItem - str - The rcParams key - object - The proposed value - object - The current value - """ - def no_check(item, key, val, orig): - return True - rc = self.rc - filter_func = filter_func or no_check - for item in self.top_level_items: - key = asstring(item.text(0)) - editor = self.itemWidget(item.child(0), self.value_col) - val = yaml.load(asstring(editor.toPlainText()), Loader=yaml.Loader) - try: - val = rc.validate[key](val) - except: - pass - try: - include = filter_func(item, key, val, rc[key]) - except: - warn('Could not check state for %s key' % key, - RuntimeWarning) - else: - if include: - yield (item, key, val, rc[key]) - - def apply_changes(self): - """Update the :attr:`rc` with the proposed changes""" - new = dict(self.changed_rc()) - if new != self.rc: - self.rc.update(new) - - def select_changes(self): - """Select all the items that changed comparing to the current rcParams - """ - for item, val in self.changed_rc(True): - item.setSelected(True) - - -class RcParamsWidget(ConfigPage, QWidget): - """A configuration page for RcParams instances - - This page displays the :class:`psyplot.config.rcsetup.RcParams` instance in - the :attr:`rc` attribute and let's the user modify it. - - Notes - ----- - After the initialization, you have to call the :meth:`initialize` method""" - - #: the rcParams to use (must be implemented by subclasses) - rc = None - - #: the :class:`RcParamsTree` that is used to display the rcParams - tree = None - - @property - def propose_changes(self): - """A signal that is emitted if the user changes the values in the - rcParams""" - return self.tree.propose_changes - - @property - def validChanged(self): - """A signal that is emitted if the user changes the valid state of this - page""" - return self.tree.validChanged - - @property - def changed(self): - """True if any changes are proposed by this config page""" - return bool(next(self.tree.changed_rc(), None)) - - @property - def is_valid(self): - """True if all the settings are valid""" - return self.tree.is_valid - - @property - def icon(self): - """The icon of this instance in the :class:`Preferences` dialog""" - return QIcon(get_icon('rcParams.png')) - - def __init__(self, *args, **kwargs): - super(RcParamsWidget, self).__init__(*args, **kwargs) - self.vbox = vbox = QVBoxLayout() - - self.description = QLabel( - '

Modify the rcParams for your need. Changes will not be applied' - ' until you click the Apply or Ok button.

' - '

Values must be entered in yaml syntax

', parent=self) - vbox.addWidget(self.description) - self.tree = tree = RcParamsTree( - self.rc, getattr(self.rc, 'validate', None), - getattr(self.rc, 'descriptions', None), parent=self) - tree.setSelectionMode(QAbstractItemView.MultiSelection) - vbox.addWidget(self.tree) - - self.bt_select_all = QPushButton('Select All', self) - self.bt_select_changed = QPushButton('Select changes', self) - self.bt_select_none = QPushButton('Clear Selection', self) - self.bt_export = QToolButton(self) - self.bt_export.setText('Export Selection...') - self.bt_export.setToolTip('Export the selected rcParams to a file') - self.bt_export.setPopupMode(QToolButton.InstantPopup) - self.export_menu = export_menu = QMenu(self) - export_menu.addAction(self.save_settings_action()) - export_menu.addAction(self.save_settings_action(True)) - self.bt_export.setMenu(export_menu) - hbox = QHBoxLayout() - hbox.addWidget(self.bt_select_all) - hbox.addWidget(self.bt_select_changed) - hbox.addWidget(self.bt_select_none) - hbox.addStretch(1) - hbox.addWidget(self.bt_export) - vbox.addLayout(hbox) - - self.setLayout(vbox) - - self.bt_select_all.clicked.connect(self.tree.selectAll) - self.bt_select_none.clicked.connect(self.tree.clearSelection) - self.bt_select_changed.clicked.connect(self.tree.select_changes) - - def save_settings_action(self, update=False, target=None): - """Create an action to save the selected settings in the :attr:`tree` - - Parameters - ---------- - update: bool - If True, it is expected that the file already exists and it will be - updated. Otherwise, existing files will be overwritten - """ - def func(): - if update: - meth = QFileDialog.getOpenFileName - else: - meth = QFileDialog.getSaveFileName - if target is None: - fname = meth( - self, 'Select a file to %s' % ( - 'update' if update else 'create'), - self.default_path, - 'YAML files (*.yml);;' - 'All files (*)' - ) - if with_qt5: # the filter is passed as well - fname = fname[0] - else: - fname = target - if not fname: - return - if update: - rc = self.rc.__class__(defaultParams=self.rc.defaultParams) - rc.load_from_file(fname) - old_keys = list(rc) - selected = dict(self.tree.selected_rc()) - new_keys = list(selected) - rc.update(selected) - rc.dump(fname, include_keys=old_keys + new_keys, - exclude_keys=[]) - else: - rc = self.rc.__class__(self.tree.selected_rc(), - defaultParams=self.rc.defaultParams) - rc.dump(fname, exclude_keys=[]) - - action = QAction('Update...' if update else 'Overwrite...', self) - action.triggered.connect(func) - return action - - def initialize(self, rcParams=None, validators=None, descriptions=None): - """Initialize the config page - - Parameters - ---------- - rcParams: dict - The rcParams to use. If None, the :attr:`rc` attribute of this - instance is used - validators: dict - A mapping from the `rcParams` key to the corresponding validation - function for the value. If None, the - :attr:`~psyplot.config.rcsetup.RcParams.validate` attribute of the - :attr:`rc` attribute is used - descriptions: dict - A mapping from the `rcParams` key to it's description. If None, the - :attr:`~psyplot.config.rcsetup.RcParams.descriptions` attribute of - the :attr:`rc` attribute is used""" - if rcParams is not None: - self.rc = rcParams - self.tree.rc = rcParams - if validators is not None: - self.tree.validators = validators - if descriptions is not None: - self.tree.descriptions = descriptions - self.tree.initialize() - - def apply_changes(self): - """Apply the changes in the config page""" - self.tree.apply_changes() - - -class GuiRcParamsWidget(RcParamsWidget): - """The config page for the :class:`psyplot_gui.config.rcsetup.rcParams`""" - - rc = rcParams - - title = 'GUI defaults' - - default_path = psyplot_fname('PSYPLOTGUIRC', 'psyplotguirc.yml', - if_exists=False) - - -class PsyRcParamsWidget(RcParamsWidget): - """The config page for the :class:`psyplot.config.rcsetup.rcParams`""" - - rc = psy_rcParams - - title = 'psyplot defaults' - - default_path = psyplot_fname(if_exists=False) - - -class Prefences(QDialog): - """Preferences dialog""" - - @property - def bt_apply(self): - return self.bbox.button(QDialogButtonBox.Apply) - - @property - def pages(self): - return map(self.get_page, range(self.pages_widget.count())) - - def __init__(self, main=None): - super(Prefences, self).__init__(parent=main) - self.setWindowTitle('Preferences') - - # Widgets - self.pages_widget = QStackedWidget() - self.contents_widget = QListWidget() - self.bt_reset = QPushButton('Reset to defaults') - self.bt_load_plugins = QPushButton('Load plugin pages') - self.bt_load_plugins.setToolTip( - 'Load the rcParams for the plugins in separate pages') - - self.bbox = bbox = QDialogButtonBox( - QDialogButtonBox.Ok | QDialogButtonBox.Apply | - QDialogButtonBox.Cancel) - - # Widgets setup - # Destroying the C++ object right after closing the dialog box, - # otherwise it may be garbage-collected in another QThread - # (e.g. the editor's analysis thread in Spyder), thus leading to - # a segmentation fault on UNIX or an application crash on Windows - self.setAttribute(Qt.WA_DeleteOnClose) - self.setWindowTitle('Preferences') - self.contents_widget.setMovement(QListView.Static) - self.contents_widget.setSpacing(1) - self.contents_widget.setCurrentRow(0) - - # Layout - hsplitter = QSplitter() - hsplitter.addWidget(self.contents_widget) - hsplitter.addWidget(self.pages_widget) - hsplitter.setStretchFactor(1, 1) - - btnlayout = QHBoxLayout() - btnlayout.addWidget(self.bt_reset) - btnlayout.addWidget(self.bt_load_plugins) - btnlayout.addStretch(1) - btnlayout.addWidget(bbox) - - vlayout = QVBoxLayout() - vlayout.addWidget(hsplitter) - vlayout.addLayout(btnlayout) - - self.setLayout(vlayout) - - # Signals and slots - if main is not None: - self.bt_reset.clicked.connect(main.reset_rcParams) - self.bt_load_plugins.clicked.connect(self.load_plugin_pages) - self.pages_widget.currentChanged.connect(self.current_page_changed) - self.contents_widget.currentRowChanged.connect( - self.pages_widget.setCurrentIndex) - bbox.accepted.connect(self.accept) - bbox.rejected.connect(self.reject) - self.bt_apply.clicked.connect(self.apply_clicked) - self.bt_apply.setEnabled(False) - - def set_current_index(self, index): - """Set current page index""" - self.contents_widget.setCurrentRow(index) - - def current_page_changed(self, index): - configpage = self.get_page(index) - self.bt_apply.setVisible(not configpage.auto_updates) - self.check_changes(configpage) - - def get_page(self, index=None): - """Return page widget""" - if index is None: - widget = self.pages_widget.currentWidget() - else: - widget = self.pages_widget.widget(index) - return widget.widget() - - def accept(self): - """Reimplement Qt method""" - for configpage in self.pages: - if not configpage.is_valid: - continue - configpage.apply_changes() - QDialog.accept(self) - - def apply_clicked(self): - # Apply button was clicked - configpage = self.get_page() - if configpage.is_valid: - configpage.apply_changes() - self.check_changes(configpage) - - def add_page(self, widget): - """Add a new page to the preferences dialog - - Parameters - ---------- - widget: ConfigPage - The page to add""" - widget.validChanged.connect(self.bt_apply.setEnabled) - widget.validChanged.connect( - self.bbox.button(QDialogButtonBox.Ok).setEnabled) - scrollarea = QScrollArea(self) - scrollarea.setWidgetResizable(True) - scrollarea.setWidget(widget) - self.pages_widget.addWidget(scrollarea) - item = QListWidgetItem(self.contents_widget) - try: - item.setIcon(widget.icon) - except TypeError: - pass - item.setText(widget.title) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) - item.setSizeHint(QtCore.QSize(0, 25)) - widget.propose_changes.connect(self.check_changes) - - def check_changes(self, configpage): - """Enable the apply button if there are changes to the settings""" - if configpage != self.get_page(): - return - self.bt_apply.setEnabled( - not configpage.auto_updates and configpage.is_valid and - configpage.changed) - - def load_plugin_pages(self): - """Load the rcParams for the plugins in separate pages""" - validators = psy_rcParams.validate - descriptions = psy_rcParams.descriptions - for ep in psy_rcParams._load_plugin_entrypoints(): - plugin = ep.load() - rc = getattr(plugin, 'rcParams', None) - if rc is None: - rc = RcParams() - w = RcParamsWidget(parent=self) - w.title = 'rcParams of ' + ep.module_name - w.default_path = PsyRcParamsWidget.default_path - w.initialize(rcParams=rc, validators=validators, - descriptions=descriptions) - # use the full rcParams after initialization - w.rc = psy_rcParams - self.add_page(w) diff --git a/psyplot_gui/sphinx_supp/__init__.py b/psyplot_gui/sphinx_supp/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/psyplot_gui/sphinx_supp/conf.py b/psyplot_gui/sphinx_supp/conf.py deleted file mode 100755 index f9d2d8a..0000000 --- a/psyplot_gui/sphinx_supp/conf.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# -# psyplot documentation build configuration file, created by -# sphinx-quickstart on Mon Jul 20 18:01:33 2015. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import sphinx -import sphinx_rtd_theme -import re -import six -from itertools import product -import psyplot_gui - -# -- General configuration ------------------------------------------------ - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.autosummary', - 'sphinx.ext.todo', - 'sphinx.ext.viewcode', - 'psyplot.sphinxext.extended_napoleon', -] - -if psyplot_gui.rcParams['help_explorer.use_intersphinx'] is None: - if sys.platform.startswith("win"): - use_intersphinx = False - else: - use_intersphinx = psyplot_gui.rcParams['help_explorer.online'] -else: - use_intersphinx = psyplot_gui.rcParams['help_explorer.use_intersphinx'] - -if use_intersphinx: - extensions.append('sphinx.ext.intersphinx') -del use_intersphinx - -autodoc_default_options = { - 'show_inheritance': True -} - -try: - import autodocsumm -except ImportError: - pass -else: - extensions.append('autodocsumm') - autodoc_default_options['autosummary'] = True - not_document_data = ['psyplot.config.rcsetup.defaultParams', - 'psyplot.config.rcsetup.rcParams'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -napoleon_use_admonition_for_examples = True - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = '.rst' - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'psyplot' - -autoclass_content = 'both' - -# General information about the project. -project = 'psyplot Help' -copyright = psyplot_gui.__copyright__ -author = psyplot_gui.__author__ - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = re.match(r'\d+\.\d+\.\d+', psyplot_gui.__version__).group() -# The full version, including alpha/beta/rc tags. -release = psyplot_gui.__version__ -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'sphinx_rtd_theme' -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] -html_theme_options = { - 'prev_next_buttons_location': None - } - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# Output file base name for HTML help builder. -htmlhelp_basename = 'psyplotdoc' - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), - 'numpy': ('https://numpy.org/doc/stable/', None), - 'matplotlib': ('https://matplotlib.org/', None), - 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), - 'xarray': ('https://xarray.pydata.org/en/stable/', None), - 'cartopy': ('https://scitools.org.uk/cartopy/docs/latest/', None), - 'psyplot': ('https://psyplot.readthedocs.io/en/latest/', None), - 'psyplot_gui': ('https://psyplot.readthedocs.io/projects/psyplot-gui/en/' - 'latest/', None), - 'psy_maps': ('https://psyplot.readthedocs.io/projects/psy-maps/en/' - 'latest/', None), - 'psy_simple': ('https://psyplot.readthedocs.io/projects/psy-simple/en/' - 'latest/', None), - 'psy_reg': ('https://psyplot.readthedocs.io/projects/psy-reg/en/' - 'latest/', None), -} -if six.PY3: - intersphinx_mapping['python'] = ('https://docs.python.org/3.6/', None) -else: - intersphinx_mapping['python'] = ('https://docs.python.org/2.7/', None) - - -replacements = { - '`psyplot.rcParams`': '`~psyplot.config.rcsetup.rcParams`', - '`psyplot.InteractiveList`': '`~psyplot.data.InteractiveList`', - '`psyplot.InteractiveArray`': '`~psyplot.data.InteractiveArray`', - '`psyplot.open_dataset`': '`~psyplot.data.open_dataset`', - '`psyplot.open_mfdataset`': '`~psyplot.data.open_mfdataset`', - } - - -def link_aliases(app, what, name, obj, options, lines): - for (key, val), (i, line) in product(six.iteritems(replacements), - enumerate(lines)): - lines[i] = line.replace(key, val) - - -def setup(app): - app.connect('autodoc-process-docstring', link_aliases) - return {'version': sphinx.__display_version__, 'parallel_read_safe': True} diff --git a/psyplot_gui/sphinx_supp/psyplot.rst b/psyplot_gui/sphinx_supp/psyplot.rst deleted file mode 100644 index 08456ef..0000000 --- a/psyplot_gui/sphinx_supp/psyplot.rst +++ /dev/null @@ -1,5 +0,0 @@ -=========== -Help Window -=========== - -Welcome to *psyplot*! An interactive framework for code development. diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index fcd336d..0000000 --- a/requirements.txt +++ /dev/null @@ -1,14 +0,0 @@ -# QtConsole -# https://github.com/jupyter/qtconsole/blob/master/docs/source/changelog.rst -qtconsole==4.3.1 # rq.filter: >=4.2, <4.4 - -# IPython kernel -# https://ipython.readthedocs.io/en/stable/whatsnew/index.html -ipykernel==4.3.1 # rq.filter: >= 4.3, <4.4 - -# PyQt4 -PyQt4==4.11.4 # rq.filter: >= 4.11, <5.0 - -# PyQt5 -# https://www.riverbankcomputing.com/static/Downloads/PyQt5/ChangeLog -PyQt5==5.6 # rq.filter: >= 5.5, < 5.7 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 7142a47..0000000 --- a/setup.cfg +++ /dev/null @@ -1,9 +0,0 @@ -[versioneer] -VCS = git -style = pep440 -versionfile_source = psyplot_gui/_version.py -versionfile_build = psyplot_gui/_version.py -tag_prefix = v -parentdir_prefix = psyplot-gui- - - diff --git a/setup.py b/setup.py deleted file mode 100644 index 748c764..0000000 --- a/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -import os -import os.path as osp -from setuptools import setup, find_packages -from setuptools.command.test import test as TestCommand -import sys - - -if os.getenv("READTHEDOCS") == "True": - # to make versioneer working, we need to unshallow this repo - # because RTD does a checkout with --depth 50 - import subprocess as spr - rootdir = osp.dirname(__file__) - spr.call(["git", "-C", rootdir, "fetch", "--unshallow", "origin"]) - - -import versioneer - - -def readme(): - with open('README.rst') as f: - return f.read() - - -class PyTest(TestCommand): - user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")] - - def initialize_options(self): - TestCommand.initialize_options(self) - self.pytest_args = '' - - def run_tests(self): - import shlex - # import here, cause outside the eggs aren't loaded - import pytest - errno = pytest.main(shlex.split(self.pytest_args)) - sys.exit(errno) - - -cmdclass = versioneer.get_cmdclass({'test': PyTest}) - - -setup(name='psyplot-gui', - version=versioneer.get_version(), - description='Graphical user interface for the psyplot package', - long_description=readme(), - long_description_content_type="text/x-rst", - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'Topic :: Scientific/Engineering :: Visualization', - 'Topic :: Scientific/Engineering :: GIS', - 'Topic :: Scientific/Engineering', - 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Operating System :: OS Independent', - ], - keywords=('visualization netcdf raster cartopy earth-sciences pyqt qt ' - 'ipython jupyter qtconsole'), - url='https://github.com/psyplot/psyplot-gui', - author='Philipp S. Sommer', - author_email='philipp.sommer@hzg.de', - license="GPLv2", - packages=find_packages(exclude=['docs', 'tests*', 'examples']), - install_requires=[ - 'psyplot>=1.3.0', - 'qtconsole', - 'fasteners', - 'sphinx>=2.4.0', - 'sphinx_rtd_theme', - ], - package_data={'psyplot_gui': [ - osp.join('psyplot_gui', 'sphinx_supp', 'conf.py'), - osp.join('psyplot_gui', 'sphinx_supp', 'psyplot.rst'), - osp.join('psyplot_gui', 'sphinx_supp', '_static', '*'), - osp.join('psyplot_gui', 'icons', '*.png'), - osp.join('psyplot_gui', 'icons', '*.svg'), - ]}, - project_urls={ - 'Documentation': 'https://psyplot.readthedocs.io/projects/psyplot-gui', - 'Source': 'https://github.com/psyplot/psyplot-gui', - 'Tracker': 'https://github.com/psyplot/psyplot-gui/issues', - }, - include_package_data=True, - tests_require=['pytest', 'psutil'], - cmdclass=cmdclass, - zip_safe=False) diff --git a/tests/_base_testing.py b/tests/_base_testing.py deleted file mode 100644 index 204cb65..0000000 --- a/tests/_base_testing.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -"""Module defining the base class for the gui test""" -import os -import os.path as osp -import unittest - -os.environ['PSYPLOT_PLUGINS'] = ('yes:psyplot_gui_test.plugin::' - 'yes:psy_simple.plugin') - - -from psyplot.config import setup_logging - - -test_dir = osp.dirname(__file__) -setup_logging(osp.join(test_dir, 'logging.yml'), env_key='') - - -from psyplot_gui.compat.qtcompat import QApplication -from psyplot_gui import rcParams -from psyplot import rcParams as psy_rcParams - - -def is_running_in_gui(): - from psyplot_gui.main import mainwindow - return mainwindow is not None - - -running_in_gui = is_running_in_gui() - - -on_travis = os.environ.get('TRAVIS') - - -def setup_rcparams(): - rcParams.defaultParams['console.start_channels'][0] = False - rcParams.defaultParams['main.listen_to_port'][0] = False - rcParams.defaultParams['help_explorer.render_docs_parallel'][0] = False - rcParams.defaultParams['help_explorer.use_intersphinx'][0] = False - rcParams.defaultParams['plugins.include'][0] = ['psyplot_gui_test.plugin'] - rcParams.defaultParams['plugins.exclude'][0] = 'all' - rcParams.update_from_defaultParams() - - -if running_in_gui: - app = QApplication.instance() -else: - setup_rcparams() - app = QApplication([]) - app.setQuitOnLastWindowClosed(False) - - -class PsyPlotGuiTestCase(unittest.TestCase): - """A base class for testing the psyplot_gui module - - At the initializzation of the TestCase, a new - :class:`psyplot_gui.main.MainWindow` widget is created which is closed at - the end of all the tests""" - - @classmethod - def setUpClass(cls): - from psyplot_gui.main import mainwindow - cls._close_app = mainwindow is None - cls._app = app - if not running_in_gui: - import psyplot_gui - psyplot_gui.UNIT_TESTING = True - - @classmethod - def tearDownClass(cls): - del cls._app - - def setUp(self): - import psyplot_gui.main as main - if not running_in_gui: - setup_rcparams() - self.window = main.MainWindow.run(show=False) - else: - self.window = main.mainwindow - - def tearDown(self): - import psyplot.project as psy - import matplotlib.pyplot as plt - if not running_in_gui: - import psyplot_gui.main as main - self.window.close() - rcParams.update_from_defaultParams() - psy_rcParams.update_from_defaultParams() - rcParams.disconnect() - psy_rcParams.disconnect() - main._set_mainwindow(None) - del self.window - psy.close('all') - plt.close('all') - - def get_file(self, fname): - """Get the path to the file `fname` - - Parameters - ---------- - fname: str - The path of the file name (relative to the test directory) - - Returns - ------- - str - The complete path to the given file""" - return osp.join(test_dir, fname) diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index 32489a3..0000000 --- a/tests/conftest.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Configuration module for running tests with pytest - -We use a methodology inspired by -https://nvbn.github.io/2017/02/02/pytest-leaking/ -to show huw many MB are leaked from each test.""" -import os -from psutil import Process -from collections import namedtuple -from itertools import groupby - - -_proc = Process(os.getpid()) - - -def get_consumed_ram(): - return _proc.memory_info().rss - - -def pytest_addoption(parser): - group = parser.getgroup("psyplot", "psyplot specific options") - group.addoption('--leak-threshold', help="Threshold for leak report", - default=20, type=int) - group.addoption( - '--sort-leaks', help="Sort the leaking report in ascending order", - action='store_true') - - -def pytest_configure(config): - global LEAK_LIMIT, SORT_LEAKS - LEAK_LIMIT = config.getoption('leak_threshold') * 1024 * 1024 - SORT_LEAKS = config.getoption('sort_leaks') - - -START = 'START' -END = 'END' -ConsumedRamLogEntry = namedtuple('ConsumedRamLogEntry', - ('nodeid', 'on', 'consumed_ram')) -consumed_ram_log = [] - - -def pytest_runtest_setup(item): - log_entry = ConsumedRamLogEntry(item.nodeid, START, get_consumed_ram()) - consumed_ram_log.append(log_entry) - - -def pytest_runtest_teardown(item): - log_entry = ConsumedRamLogEntry(item.nodeid, END, get_consumed_ram()) - consumed_ram_log.append(log_entry) - - -# display leaks greater than 20 MB -LEAK_LIMIT = 20 * 1024 * 1024 - -SORT_LEAKS = False - - -def pytest_terminal_summary(terminalreporter): - grouped = groupby(consumed_ram_log, lambda entry: entry.nodeid) - leaks = [] - for nodeid, (start_entry, end_entry) in grouped: - leaked = end_entry.consumed_ram - start_entry.consumed_ram - if leaked > LEAK_LIMIT: - leaks.append((leaked // 1024 // 1024, nodeid, - end_entry.consumed_ram // 1024 // 1024)) - if SORT_LEAKS: - leaks.sort() - for t in leaks: - terminalreporter.write( - 'LEAKED %s MB in %s. Total: %s MB\n' % t) diff --git a/tests/dummy_module.py b/tests/dummy_module.py deleted file mode 100644 index 19e7ec1..0000000 --- a/tests/dummy_module.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Dummy module - -Just a dummy module for documentation testing purposes""" - - -class DummyClass(object): - """I am a test class for docs""" - - #: A dummy class attribute that will be replaced by an instance attribute - a = None - - def __init__(self, a=None): - """ - Parameters - ---------- - a: object - anything""" - self.a = a - - def __call__(self, a=None): - """ - Parameters - ---------- - a: object - anything else""" - self.a = a - - def dummy_method(self, a=None): - """A dummy instance method - - Parameters - ---------- - a: object - any dummy value""" - self.a = a - - -def dummy_func(a=None): - """A dummy test function - - Parameters - ---------- - a: object - I don't care""" - pass - - -#: :class:`int`. A dummy module level attribute -a = 1 diff --git a/tests/logging.yml b/tests/logging.yml deleted file mode 100755 index e4c43f9..0000000 --- a/tests/logging.yml +++ /dev/null @@ -1,82 +0,0 @@ ---- -# debug logging settings for the psyplot_gui test suite - -version: 1 - -disable_existing_loggers: False - -formatters: - - simple: - - format: "[%(name)s] - %(levelname)s - %(message)s" - - level_message: - - format: "%(levelname)s: %(message)s" - - full: - format: "%(asctime)s - [%(name)s.%(funcName)s] - %(levelname)s - %(message)s" - - -handlers: - - console: - - class: logging.StreamHandler - - level: INFO - - formatter: simple - - stream: ext://sys.stdout - - warning_console: - - class: logging.StreamHandler - - level: INFO - - formatter: level_message - - stream: ext://sys.stdout - - - debug_file_handler: - - class: logging.handlers.RotatingFileHandler - - mode: w - - level: DEBUG - - formatter: full - - filename: debug_psyplot.log - - maxBytes: 10485760 # 10MB - - backupCount: 5 - - encoding: utf8 - - delay: True - -loggers: - - psyplot_gui: - - handlers: [console, debug_file_handler] - - propagate: False - - level: DEBUG - - psyplot: - - handlers: [console, debug_file_handler] - - propagate: False - - level: DEBUG -... \ No newline at end of file diff --git a/tests/test-t2m-u-v.nc b/tests/test-t2m-u-v.nc deleted file mode 100644 index 7594faf..0000000 Binary files a/tests/test-t2m-u-v.nc and /dev/null differ diff --git a/tests/test_console.py b/tests/test_console.py deleted file mode 100644 index 22dccf9..0000000 --- a/tests/test_console.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -"""Skript to test the InProcessShell that is used in the psyplot gui""" -import re -import six -import unittest -import _base_testing as bt -import psyplot.project as psy -import inspect -from psyplot_gui.compat.qtcompat import QTest, with_qt5 - - -travis_qt_msg = "Does not work on Travis with Qt4" - - -class ConsoleTest(bt.PsyPlotGuiTestCase): - """A testcase to test the InProcess IPython console of the psyplot GUI""" - - def setUp(self): - import psyplot_gui.console - # XXX HACK: Set the _with_prompt attribute to False to tell the - # ConsoleWidget to use the _prompt_cursor - psyplot_gui.console._with_prompt = False - super(ConsoleTest, self).setUp() - - def tearDown(self): - import psyplot_gui.console - # XXX HACK: Set the _with_prompt attribute to True again to tell the - # ConsoleWidget to use the _prompt_cursor - psyplot_gui.console._with_prompt = True - super(ConsoleTest, self).tearDown() - - def insert_text(self, text): - """Convenience method to insert a single line into the console""" - c = self.window.console - return c._insert_plain_text(c._get_prompt_cursor(), text) - - def _test_object_docu(self, symbol): - """Tests whether the documentation of :class:`object` can be displayed - - Parameters - ---------- - symbol: {'?', '('} - The symbol to use for displaying the doc - - See Also - -------- - test_questionmark, test_bracketleft - """ - from psyplot_gui.help_explorer import signature - c = self.window.console - he = self.window.help_explorer - he.set_viewer('Plain text') - # we insert the text here otherwise using console _insert_plain_text - # method because apparently the text is not inserted when using - # QTest.keyClicks - self.insert_text('object') - QTest.keyClicks(c._control, symbol) - sig = '' if six.PY2 else re.sub( - r'^\(\s*self,\s*', '(', str(signature(object.__init__))) - header = "object" + sig - bars = '=' * len(header) - self.assertEqual( - he.viewer.editor.toPlainText(), - '\n'.join([ - bars, header, bars + "\n\n", inspect.getdoc(object), - "\n" + inspect.getdoc(object.__init__)])) - - @unittest.skipIf(bt.on_travis and not with_qt5, travis_qt_msg) - def test_questionmark(self): - """Test the connection to the help explorer by typing '?'""" - self._test_object_docu('?') - - @unittest.skipIf(bt.on_travis and not with_qt5, travis_qt_msg) - def test_bracketleft(self): - """Test the connection to the help explorer by typing '?'""" - self._test_object_docu('(') - - @unittest.skipIf(bt.on_travis and not with_qt5, travis_qt_msg) - def test_current_object(self): - """Test whether the current object is given correctly""" - c = self.window.console - self.insert_text('print(test.anything(object') - self.assertEqual(c.get_current_object(True), 'object') - try: # qtconsole >4.3 uses the _prompt_cursor attribute - cursor = c._prompt_cursor - except AttributeError: - cursor = c._control.textCursor() - curr = cursor.position() - self.insert_text(') + 3') - cursor.setPosition(curr) - self.assertEqual(c.get_current_object(), 'object') - - def test_command(self): - self.window.console.run_command_in_shell('a = 4') - self.assertEqual(self.window.console.get_obj('a')[1], 4) - - def test_mp_sp(self): - """Test whether the mp and sp variables are set correctly""" - from xarray import DataArray - psy.Project.oncpchange.emit(psy.gcp(True)) - psy.Project.oncpchange.emit(psy.gcp()) - self.assertIs(self.window.console.get_obj('mp')[1], psy.gcp(True)) - self.assertIs(self.window.console.get_obj('sp')[1], psy.gcp()) - sp = psy.plot.lineplot(DataArray([1, 2, 3], name='test').to_dataset()) - self.assertIs(self.window.console.get_obj('mp')[1], psy.gcp(True)) - self.assertIs(self.window.console.get_obj('sp')[1], sp) - sp.close(True, True) - self.assertIs(self.window.console.get_obj('mp')[1], psy.gcp(True)) - self.assertIs(self.window.console.get_obj('sp')[1], psy.gcp()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dataframeeditor.py b/tests/test_dataframeeditor.py deleted file mode 100644 index af45f00..0000000 --- a/tests/test_dataframeeditor.py +++ /dev/null @@ -1,270 +0,0 @@ -# -*- coding: utf-8 -*- -"""Test module for the :mod:`psyplot_gui.dataframeeditor` module""" -import six -import sys -import pandas as pd -import numpy as np -import _base_testing as bt -import unittest -from pandas.testing import assert_frame_equal -from psyplot_gui.compat.qtcompat import Qt, QApplication - - -if six.PY2: - try: - import CStringIO as io - except ImportError: - import StringIO as io -else: - import io - - -def df_equals(df, df_ref, *args, **kwargs): - """Simple wrapper around assert_frame_equal to use unittests assertion - - Parameters - ---------- - df: pd.DataFrame - The simulation data frame - df_ref: pd.DataFrame - The reference data frame - - Returns - ------- - None or Exception - Either None if everything went fine, otherwise the raised Exception""" - try: - assert_frame_equal(df, df_ref, *args, **kwargs) - except Exception as e: - return e - - -class DataFrameEditorTest(bt.PsyPlotGuiTestCase): - - #: The :class:`psyplot_gui.dataframeeditor.DataFrameEditor` - editor = None - - @property - def table(self): - return self.editor.table - - @property - def model(self): - return self.table.model() - - def setUp(self): - super(DataFrameEditorTest, self).setUp() - self.editor = self.window.new_data_frame_editor() - - def tearDown(self): - self.editor = None - - def test_dtypes(self): - df = pd.DataFrame([ - [True, "bool"], - [1+1j, "complex"], - ['test', "string"], - [1.11, "float"], - [1, "int"], - [np.random.rand(3, 3), "Unkown type"], - ["áéí", "unicode"], - ], - index=['a', 'b', np.nan, np.nan, np.nan, 'c', - 'd'], - columns=[np.nan, 'Type']) - self.editor.set_df(df) - self.assertIs(self.table.model().df, df) - - def test_multiindex(self): - """Test the handling of DataFrames with MultiIndex""" - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.set_df(df) - self.assertTrue(self.model.index_editable) - self.assertTrue(self.editor.cb_index_editable.isChecked()) - - table = self.table - table.selectColumn(1) - table.set_index_action.trigger() - self.assertEqual(list(df.index.names), ['a']) - self.assertTrue(self.model.index_editable) - self.assertTrue(self.editor.cb_index_editable.isChecked()) - - table.selectColumn(2) - table.append_index_action.trigger() - self.assertEqual(list(df.index.names), ['a', 'b']) - self.assertFalse(self.model.index_editable) - self.assertFalse(self.editor.cb_index_editable.isChecked()) - table.selectColumn(1) - table.set_index_action.trigger() - self.assertEqual(list(df.index.names), ['index']) - self.assertEqual(list(df.columns), list('abc')) - self.assertTrue(self.model.index_editable) - self.assertTrue(self.editor.cb_index_editable.isChecked()) - - def test_sort(self): - """Test the sorting""" - df = pd.DataFrame([[4, 5, 6+1j], [1, object, 3]], columns=list('abc')) - self.editor.set_df(df) - self.assertTrue(self.model.sort(1, return_check=True)) - self.assertEqual(list(df.index.values), [1, 0]) - self.assertTrue(self.model.sort(0, return_check=True)) - self.assertEqual(list(df.index.values), [0, 1]) - - # test complex numbers - self.assertTrue(self.model.sort(3, Qt.AscendingOrder, - return_check=True)) - self.assertEqual(list(df['c'].values), [3+0j, 6+1j]) - self.assertTrue(self.model.sort(3, Qt.DescendingOrder, - return_check=True)) - self.assertEqual(list(df['c'].values), [6+1j, 3+0j]) - - # sorting is not enabled - self.table.sortByColumn(1) - self.assertEqual(list(df['a']), [4, 1]) - - # enable sorting - self.table.setSortingEnabled(True) - self.table.header_class.setSortIndicator(1, Qt.AscendingOrder) - self.table.sortByColumn(1) - self.assertEqual(list(df['a']), [1, 4]) - self.table.header_class.setSortIndicator(1, Qt.DescendingOrder) - self.table.sortByColumn(1) - self.assertEqual(list(df['a']), [4, 1]) - - @unittest.expectedFailure - def test_sort_failure(self): - df = pd.DataFrame([[4, 5, 6+1j], [1, object, 3]], columns=list('abc')) - self.editor.set_df(df) - - # test false sorting - if not six.PY2: - self.assertFalse(self.model.sort(2, return_check=True)) - - @unittest.expectedFailure - def test_sort_failure_2(self): - df = pd.DataFrame([[4, 5, 6+1j], [1, object, 3]], columns=list('abc')) - self.editor.set_df(df) - - # test a column that cannot be sorted - self.table.setSortingEnabled(True) - self.table.sortByColumn(2) - - def test_edit(self): - """Test the editing of the editor""" - - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.set_df(df) - - table = self.table - - # edit a regular cell - table.selectRow(0) - idx = table.selectedIndexes()[2] # first row, second column - self.model.setData(idx, 4) - self.assertEqual(df.iloc[0, 1], 4) - - # now edit the index - table.selectRow(1) - idx = table.selectedIndexes()[0] # first row, second column - self.model.setData(idx, 6) - self.assertEqual(df.index[1], 6) - - # now we change a data type - table.selectColumn(2) - table.dtype_actions['To float'].trigger() - self.assertIs(df.dtypes['b'], np.array(5.4).dtype) - - def test_large_df(self): - df = pd.DataFrame(np.zeros((int(1e6), 100))) - self.editor.set_df(df) - model = self.model - self.assertLess(model.rows_loaded, df.shape[0]) - self.assertLess(model.cols_loaded, df.shape[1]) - self.assertEqual((model.total_rows, model.total_cols), df.shape) - self.assertTrue(model.can_fetch_more(rows=True, columns=True)) - old_rows, old_cols = model.rows_loaded, model.cols_loaded - self.table.load_more_data( - self.table.verticalScrollBar().maximum(), rows=True) - self.table.load_more_data( - self.table.horizontalScrollBar().maximum(), columns=True) - self.assertGreater(model.rows_loaded, old_rows) - self.assertGreater(model.cols_loaded, old_cols) - self.assertLess(model.rows_loaded, df.shape[0]) - self.assertLess(model.cols_loaded, df.shape[1]) - - def test_insert_rows_above(self): - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.set_df(df) - - # insert one row - self.table.selectRow(1) - self.table.insert_row_above_action.trigger() - self.assertEqual(df.shape, (3, 3)) - self.assertEqual(list(df.index), [0, 0, 1]) - self.assertTrue(np.isnan(df.iloc[1, :].values).all(), - msg=str(df.iloc[1, :])) - - # insert two rows - self.model.insertRows(2, 2) - self.assertEqual(df.shape, (5, 3)) - self.assertEqual(list(df.index), [0, 0, 0, 0, 1]) - self.assertTrue(np.isnan(df.iloc[2:-1, :].values).all(), - msg=str(df.iloc[2:-1, :])) - - def test_insert_rows_below(self): - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.set_df(df) - - # insert one row - self.table.selectRow(1) - self.table.insert_row_below_action.trigger() - self.assertEqual(df.shape, (3, 3)) - self.assertEqual(list(df.index), [0, 1, 1]) - self.assertTrue(np.isnan(df.iloc[2, :].values).all(), - msg=str(df.iloc[2, :])) - - # insert two rows - self.model.insertRows(3, 2) - self.assertEqual(df.shape, (5, 3)) - self.assertEqual(list(df.index), [0, 1, 1, 1, 1]) - self.assertTrue(np.isnan(df.iloc[-2:, :].values).all(), - msg=str(df.iloc[-2:, :])) - - def test_copy(self): - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.set_df(df) - self.table.selectAll() - self.table.copy() - clipboard = QApplication.clipboard() - stream = io.StringIO(clipboard.text()) - - df2 = pd.read_csv(stream, delim_whitespace=True) - self.assertIsNone(df_equals(df2, df)) - - self.table.selectColumn(1) - self.table.copy() - stream = io.StringIO(clipboard.text()) - arr = np.loadtxt(stream) - self.assertEqual(arr.tolist(), [1, 4]) - - @unittest.skipIf(sys.platform == 'win32', - 'Avoid potential troubles with temporary csv files.') - def test_open_dataframe(self): - """Test the opening of a dataframe""" - from tempfile import NamedTemporaryFile - df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('abc')) - self.editor.open_dataframe(df) - self.editor.open_dataframe('') - f = NamedTemporaryFile(suffix='.csv') - df.to_csv(f.name, index=False) - self.editor.open_dataframe(f.name) - self.assertIsNone(df_equals(self.model.df, df)) - - @unittest.expectedFailure - def test_open_nonexistent(self): - self.editor.open_dataframe(u'NONEXISTENT.csv') - self.assertIsNone(df_equals(self.model.df, df)) - - def test_close(self): - self.editor.close() - self.assertFalse(self.window.dataframeeditors) diff --git a/tests/test_dependencies.py b/tests/test_dependencies.py deleted file mode 100644 index c62f39f..0000000 --- a/tests/test_dependencies.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -"""Script to test the :mod:`psyplot_gui.dependencies` module""" -import unittest -import yaml -import _base_testing as bt -from psyplot_gui.compat.qtcompat import QLabel -import psyplot -import numpy as np -import psyplot_gui - - -class TestDependencies(bt.PsyPlotGuiTestCase): - """Test the :class:`psyplot_gui.preferences.Preferences` widget""" - - def setUp(self): - super(TestDependencies, self).setUp() - self.window.show_dependencies() - self.deps = self.window.dependencies - - def tearDown(self): - # make sure the preferences widget is closed completely - self.deps.close() - del self.deps - super(TestDependencies, self).tearDown() - - def test_widget(self): - """Test whether the tree is filled correctly""" - deps = self.deps - label = QLabel('', parent=self.window) - deps.tree.selectAll() - deps.copy_selected(label) - d = yaml.load(str(label.text()), Loader=yaml.Loader) - self.assertEqual(d['psyplot'], psyplot.__version__) - self.assertEqual(d['psyplot_gui'], psyplot_gui.__version__) - self.assertIn('numpy', d) - self.assertEqual(d['numpy'], np.__version__) - label.close() - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_fmt_widget.py b/tests/test_fmt_widget.py deleted file mode 100644 index 267527f..0000000 --- a/tests/test_fmt_widget.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Test module for the psyplot_gui.fmt_widget module""" -import yaml -import _base_testing as bt -from psyplot_gui.compat.qtcompat import ( - QTest, Qt, QPushButton, QtCore, QtGui, with_qt5) - -if with_qt5: - ClearAndSelect = QtCore.QItemSelectionModel.ClearAndSelect -else: - ClearAndSelect = QtGui.QItemSelectionModel.ClearAndSelect - - -class FormatoptionWidgetTest(bt.PsyPlotGuiTestCase): - """Test case for the :class:`psyplot_gui.fmt_widget.FormatoptionWidget`""" - - @property - def fmt_widget(self): - return self.window.fmt_widget - - def setUp(self): - import psyplot.project as psy - super(FormatoptionWidgetTest, self).setUp() - self.project = psy.plot.gui_test_plotter( - self.get_file('test-t2m-u-v.nc'), name='t2m') - - def tearDown(self): - import psyplot.project as psy - super(FormatoptionWidgetTest, self).tearDown() - psy.close('all') - del self.project - - def test_fmto_groups(self): - """Test whether the group combo is filled correctly""" - fmt_w = self.fmt_widget - # test groups - self.assertEqual( - list(map(fmt_w.group_combo.itemText, - range(fmt_w.group_combo.count()))), - ['Dimensions', - 'All formatoptions', - 'Miscallaneous formatoptions', - 'Post processing formatoptions']) - - def test_dims(self): - """Test whether the fmto combo for dimensions is filled correctly""" - fmt_w = self.fmt_widget - # test groups - self.assertEqual( - list(map(fmt_w.fmt_combo.itemText, - range(fmt_w.fmt_combo.count()))), - list(self.project[0].psy.base['t2m'].dims)) - - def test_dim_widget(self): - """Test the :class:`psyplot_gui.fmt_widget.DimensionsWidget`""" - fmt_w = self.fmt_widget - fmt_w.clear_text() - self.assertTrue(fmt_w.dim_widget.isVisible()) - fmt_w.dim_widget.coord_combo.load_coord() - model = fmt_w.dim_widget.coord_combo.model() - selection_model = fmt_w.dim_widget.coord_combo.view().selectionModel() - item = model.item(2) - selection_model.select(model.indexFromItem(item), ClearAndSelect) - fmt_w.dim_widget.insert_from_combo() - self.assertEqual(fmt_w.get_text(), '[1]') - # select a second item - item = model.item(3) - selection_model.select(model.indexFromItem(item), ClearAndSelect) - fmt_w.dim_widget.insert_from_combo() - self.assertEqual(fmt_w.get_text(), '[1, 2]') - - # change to single selection - fmt_w.dim_widget.set_single_selection(True) - fmt_w.dim_widget.insert_from_combo() - self.assertEqual(fmt_w.get_text(), '2') - - def test_fmtos(self): - """Test whether the fmto combo for formatoptions is filled correctly""" - fmt_w = self.fmt_widget - fmt_w.group_combo.setCurrentIndex(fmt_w.group_combo.findText( - 'Miscallaneous formatoptions')) - # test groups - self.assertEqual( - list(map(fmt_w.fmt_combo.itemText, - range(fmt_w.fmt_combo.count()))), - ['Test formatoption (fmt1)', 'Second test formatoption (fmt2)']) - - def test_toggle_multiline(self): - """Test toggle the multiline text editor""" - fmt_w = self.fmt_widget - self.assertTrue(fmt_w.line_edit.isVisible()) - self.assertFalse(fmt_w.text_edit.isVisible()) - fmt_w.set_obj('test') - self.assertEqual(fmt_w.line_edit.text()[1:-1], 'test') - - # now toggle the button - QTest.mouseClick(fmt_w.multiline_button, Qt.LeftButton) - self.assertFalse(fmt_w.line_edit.isVisible()) - self.assertTrue(fmt_w.text_edit.isVisible()) - self.assertEqual(fmt_w.text_edit.toPlainText()[1:-1], 'test') - fmt_w.insert_obj('test') - self.assertEqual(fmt_w.text_edit.toPlainText()[1:-1], 'testtest') - - # and toggle again - QTest.mouseClick(fmt_w.multiline_button, Qt.LeftButton) - self.assertTrue(fmt_w.line_edit.isVisible()) - self.assertFalse(fmt_w.text_edit.isVisible()) - self.assertEqual(fmt_w.line_edit.text()[1:-1], 'testtest') - - def test_run_code(self): - """Test updating the plot""" - fmt_w = self.fmt_widget - self.assertTrue(fmt_w.yaml_cb.isChecked()) - fmt_w.group_combo.setCurrentIndex(fmt_w.group_combo.findText( - 'Miscallaneous formatoptions')) - fmt_w.set_obj('test') - QTest.keyClick(fmt_w.line_edit, Qt.Key_Return) - self.assertEqual(self.project.plotters[0].fmt1.value, 'test') - - # test python code - fmt_w.fmt_combo.setCurrentIndex(1) - fmt_w.yaml_cb.setChecked(False) - fmt_w.set_obj("second test") - QTest.mouseClick(fmt_w.run_button, Qt.LeftButton) - self.assertEqual(self.project.plotters[0].fmt2.value, 'second test') - - def test_fmt_widget(self): - """Test the :meth:`psyplot.plotter.Formatoption.get_fmt_widget` method - """ - fmt_w = self.fmt_widget - self.assertIs(fmt_w.fmt_widget, fmt_w.dim_widget) - fmt_w.group_combo.setCurrentIndex(fmt_w.group_combo.findText( - 'Miscallaneous formatoptions')) - self.assertIsInstance(fmt_w.fmt_widget, QPushButton) - self.assertFalse(yaml.load(fmt_w.line_edit.text(), Loader=yaml.Loader)) - fmt_w.line_edit.setText('') - QTest.mouseClick(fmt_w.fmt_widget, Qt.LeftButton) - self.assertEqual(fmt_w.line_edit.text()[1:-1], 'Test') - # test with objects other than string - fmt_w.fmt_combo.setCurrentIndex(1) - self.assertIsInstance(fmt_w.fmt_widget, QPushButton) - fmt_w.clear_text() - QTest.mouseClick(fmt_w.fmt_widget, Qt.LeftButton) - self.assertEqual(fmt_w.line_edit.text(), '2') - - # check without yaml - fmt_w.yaml_cb.setChecked(False) - QTest.mouseClick(fmt_w.fmt_widget, Qt.LeftButton) - self.assertEqual(fmt_w.line_edit.text(), '22') - - def test_get_obj(self): - self.fmt_widget.line_edit.setText('{"okay": True}') - self.assertEqual(self.fmt_widget.get_obj(), {'okay': True}) diff --git a/tests/test_help_explorer.py b/tests/test_help_explorer.py deleted file mode 100644 index 818fcc0..0000000 --- a/tests/test_help_explorer.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Module for testing the components of the -:class:`psyplot_gui.help_explorer.HelpExplorer` class""" -import unittest -import inspect -import os.path as osp -import _base_testing as bt -import dummy_module as d -from psyplot_gui import rcParams -from psyplot_gui.compat.qtcompat import QTest, Qt, asstring -from psyplot_gui.help_explorer import ( - html2file, UrlHelp, HelpExplorer, _viewers) - - -class UrlHelpTestMixin(bt.PsyPlotGuiTestCase): - """Convenience class for UrlHelp tests""" - - @classmethod - def setUpClass(cls): - super(UrlHelpTestMixin, cls).setUpClass() - cls._original_intersphinx = rcParams['help_explorer.use_intersphinx'] - rcParams['help_explorer.use_intersphinx'] = False - # we render the docs in the same process to avoid problems with - # signals not being send and time problems - cls._original_pdocs = rcParams['help_explorer.render_docs_parallel'] - rcParams['help_explorer.render_docs_parallel'] = False - - @classmethod - def tearDownClass(cls): - super(UrlHelpTestMixin, cls).tearDownClass() - rcParams['help_explorer.use_intersphinx'] = cls._original_intersphinx - rcParams['help_explorer.render_docs_parallel'] = cls._original_pdocs - - def setUp(self): - super(UrlHelpTestMixin, self).setUp() - self.help_explorer.set_viewer('HTML help') - - @property - def help_explorer(self): - return self.window.help_explorer - - @property - def viewer(self): - ret = self.help_explorer.viewer - self.assertIs(ret, self.help_explorer.viewers['HTML help']) - return ret - - def _test_if_sphinx_worked(self, oname): - html = osp.join(osp.join(self.viewer.sphinx_dir, '_build', - 'html', oname + '.html')) - self.assertEqual(html2file(self.viewer.html.url().toString()), html) - # we emit the urlChanged signal manually because it is not emitted - # without main loop - self.viewer.html.urlChanged.emit(self.viewer.html.url()) - self.assertEqual(self.viewer.tb_url.currentText(), oname) - - def _test_browsing(self): - rcParams['help_explorer.online'] = True - self.viewer.browse('www.google.de') - url = asstring(self.viewer.html.url().toString()) - self.assertTrue(url.startswith('https://www.google.de'), - msg='Wrong url ' + url) - - def _test_object_docu(self, obj, oname): - """Test whether an html help of a python object can be shown""" - self.help_explorer.show_help(obj, oname) - fname = osp.join(self.viewer.sphinx_dir, oname + '.rst') - self.assertTrue(osp.exists(fname), msg=fname + " is not existent!") - self._test_if_sphinx_worked(oname) - - -class UrlHelpTest(UrlHelpTestMixin): - """Test the :class:`psyplot_gui.help_explorer.UrlHelp`""" - - def test_browsing(self): - """Test browsing""" - self._test_browsing() - - def test_show_rst(self): - """Test whether the showing of an rst string is working""" - s = """ - That's a test - ============= - - Just a dummy string""" - self.help_explorer.show_rst(s, 'test') - fname = osp.join(self.viewer.sphinx_dir, 'test.rst') - self.assertTrue(osp.exists(fname), msg=fname + " is not existent!") - self._test_if_sphinx_worked('test') - - def test_module_doc(self): - """Test whether the sphinx rendering works for a module""" - self._test_object_docu(d, 'dummy_module') - - def test_class_doc(self): - """Test whether the sphinx rendering works for a class""" - self._test_object_docu(d.DummyClass, 'd.DummyClass') - - def test_func_doc(self): - """Test whether the sphinx rendering works for a class""" - self._test_object_docu(d.dummy_func, 'd.dummy_func') - - def test_method_doc(self): - """Test whether the sphinx rendering works for a method""" - self._test_object_docu(d.DummyClass.dummy_method, - 'd.DummyClass.dummy_method') - ini = d.DummyClass() - self._test_object_docu(ini.dummy_method, 'ini.dummy_method') - - def test_instance_doc(self): - """Test whether the sphinx rendering works for a instance of a class""" - ini = d.DummyClass() - self._test_object_docu(ini, 'ini') - -# XXX Not yet working XXX -# def test_classattr_doc(self): -# """Test whether the sphinx rendering works for a method""" -# ini = d.DummyClass(2) -# self._test_object_docu(ini.a, 'ini.a') -# -# def test_moduleattr_doc(self): -# """Test whether the sphinx rendering works for a method""" -# self._test_object_docu(d.a, 'd.a') - - -class BrowserTest(UrlHelpTestMixin): - """Testcase for the :class:`psyplot_gui.help_explorer.UrlBrowser` class""" - - def setUp(self): - super(BrowserTest, self).setUp() - self._help = viewer = UrlHelp(parent=self.window.help_explorer) - self.window.help_explorer.viewers['HTML help'] = viewer - self.window.help_explorer.set_viewer(viewer) - - def tearDown(self): - self._help.close(force=True) - super(BrowserTest, self).tearDown() - - def test_added_url(self): - """Test to add an url on the top""" - def check_google(): - combo.add_text_on_top('https://www.google.com/', block=True) - self.assertEqual(combo.itemText(0), 'https://www.google.com/') - combo = self.viewer.tb_url - current = combo.itemText(0) - check_google() - combo.insertItem(0, 'test') - check_google() - self.assertEqual(combo.itemText(1), 'test') - self.assertEqual(combo.itemText(2), current) - - def test_lock(self): - """Test the url lock""" - url = self.viewer.html.url().toString() - QTest.mouseClick(self.viewer.bt_lock, Qt.LeftButton) - self.help_explorer.show_help(int, 'int') - fname = osp.join(self.viewer.sphinx_dir, 'int.rst') - self.assertFalse(osp.exists(fname), msg=fname + ' exists wrongly!') - self.help_explorer.show_rst(int.__doc__, 'int') - self.assertFalse(osp.exists(fname), msg=fname + ' exists wrongly!') - self.viewer.browse('www.google.de') - self.assertEqual(self.viewer.html.url().toString(), url) - - def test_url_lock(self): - """Test whether to object documentation works""" - self._test_browsing() - QTest.mouseClick(self.viewer.bt_url_lock, Qt.LeftButton) - self.help_explorer.show_help(int, 'int') - self._test_object_docu(int, 'int') - self.viewer.browse('www.unil.ch') - self._test_object_docu(int, 'int') - - -class TextHelpTest(bt.PsyPlotGuiTestCase): - """Testcase for the :class:`psyplot_gui.help_explorer.TextHelp` class""" - - def setUp(self): - super(TextHelpTest, self).setUp() - self.help_explorer.set_viewer('Plain text') - - @property - def help_explorer(self): - return self.window.help_explorer - - @property - def viewer(self): - return self.help_explorer.viewer - - def _test_doc(self, doc, oname, obj=None): - """Test whether an the documentation is shown correctly - - Notes - ----- - May be improved in the future for a more exact test""" - self.assertTrue( - doc in self.viewer.editor.toPlainText(), - msg="%s was not documented!\nObject docu: %s\nHelp test: %s" % ( - oname, doc, self.viewer.editor.toPlainText())) - - def _test_object_docu(self, obj, oname, doc=None): - """Test whether an help of a python object can be shown""" - self.help_explorer.show_help(obj, oname) - if doc is None: - doc = inspect.getdoc(obj) - self._test_doc(doc, oname, obj) - - def test_show_rst(self): - """Test whether the showing of an rst string is working""" - s = """ - That's a test - ============= - - Just a dummy string""" - self.help_explorer.show_rst(s, 'test') - self._test_doc(s, 'test') - - def test_module_doc(self): - """Test whether the sphinx rendering works for a module""" - self._test_object_docu(d, 'dummy_module') - - def test_class_doc(self): - """Test whether the sphinx rendering works for a class""" - self._test_object_docu(d.DummyClass, 'd.DummyClass') - - def test_func_doc(self): - """Test whether the sphinx rendering works for a class""" - self._test_object_docu(d.dummy_func, 'd.dummy_func') - - def test_method_doc(self): - """Test whether the sphinx rendering works for a method""" - self._test_object_docu(d.DummyClass.dummy_method, - 'd.DummyClass.dummy_method') - ini = d.DummyClass() - self._test_object_docu(ini.dummy_method, 'ini.dummy_method') - - def test_instance_doc(self): - """Test whether the sphinx rendering works for a instance of a class""" - ini = d.DummyClass() - self._test_object_docu(ini, 'ini') - - -class NoHTMLTest(TextHelpTest): - """Test running without the HTML viewer""" - - @classmethod - def setUpClass(cls): - super().setUpClass() - rcParams['help_explorer.use_webengineview'] = False - del HelpExplorer.viewers['HTML help'] - cls._orig_viewers = _viewers.copy() - _viewers.clear() - - def setUp(self): - super(TextHelpTest, self).setUp() - - @classmethod - def tearDownClass(cls): - rcParams['help_explorer.use_webengineview'] = True - HelpExplorer.viewers['HTML help'] = UrlHelp - for key, val in cls._orig_viewers.items(): - _viewers[key] = val - super().tearDownClass() - - def test_no_html(self): - """Test if the HTML help has been removed""" - self.assertNotIn('HTML help', self.help_explorer.viewers) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_main.py b/tests/test_main.py deleted file mode 100644 index 1623cd1..0000000 --- a/tests/test_main.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Test utilities for the :mod:`psyplot_gui.main` module -""" -import unittest -import _base_testing as bt - - -class TestMainWindow(bt.PsyPlotGuiTestCase): - - def test_plugin(self): - from psyplot_gui.main import mainwindow - try: - from psyplot_gui_test.plugin import W1, W2 - except ImportError: - self.skipTest("Test plugin not installed") - self.assertIn('psyplot_gui_test.plugin:W1:w1', mainwindow.plugins) - self.assertIn('psyplot_gui_test.plugin:W2:w2', mainwindow.plugins) - self.assertIsInstance( - mainwindow.plugins['psyplot_gui_test.plugin:W1:w1'], W1) - self.assertIsInstance( - mainwindow.plugins['psyplot_gui_test.plugin:W2:w2'], W2) - w = mainwindow.plugins['psyplot_gui_test.plugin:W2:w2'] - a = w.dock.toggleViewAction() - # the plugin should be hidden - self.assertFalse(a.isChecked()) - w.show_plugin() - self.assertTrue(a.isChecked()) - - def test_central_widget(self): - """Test changing the central widget""" - self.window.set_central_widget('help_explorer') - self.assertIs(self.window.centralWidget(), self.window.help_explorer) - self.window.set_central_widget(self.window.figures_tree) - self.assertIs(self.window.centralWidget(), self.window.figures_tree) - - def test_remove_plugin(self): - self.window.plugins['psyplot_gui_test.plugin:W1:w1'].remove_plugin() - self.assertNotIn('psyplot_gui_test.plugin:W1:w1', self.window.plugins) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_plot_creator.py b/tests/test_plot_creator.py deleted file mode 100644 index 18f4ddc..0000000 --- a/tests/test_plot_creator.py +++ /dev/null @@ -1,410 +0,0 @@ -# -*- coding: utf-8 -*- -"""Skript to test the InProcessShell that is used in the psyplot gui""" -import sys -import six -import unittest -from itertools import chain -import _base_testing as bt -import psyplot.project as psy -from psyplot.compat.pycompat import range -from psyplot_gui.compat.qtcompat import ( - QTest, Qt, QStyleOptionViewItem, QWidget, QValidator, QtGui, QtCore, - asstring) - - -def get_col_num(ax): - try: - return ax.get_subplotspec().colspan.start - except AttributeError: # matplotlib<3.2 - return ax.colNum - - -def get_row_num(ax): - try: - return ax.get_subplotspec().rowspan.start - except AttributeError: # matplotlib<3.2 - return ax.rowNum - - -class PlotCreatorTest(bt.PsyPlotGuiTestCase): - """Tests concerning the plot creator""" - - def setUp(self): - super(PlotCreatorTest, self).setUp() - self.window.new_plots() - self.pc = self.window.plot_creator - - def tearDown(self): - if getattr(self.pc, 'ds', None) is not None: - self.pc.ds.close() - # make sure the plot creator is closed completely - self.pc.close() - del self.pc - super(PlotCreatorTest, self).tearDown() - - def test_load_external_file(self): - """Test whether an external netCDF file can be loaded""" - fname = self.get_file('test-t2m-u-v.nc') - self.pc.open_dataset([fname]) - vtab = self.pc.variables_table - ds = psy.open_dataset(fname) - self.assertIn(fname, self.pc.ds_combo.currentText()) - self.assertEqual( - {asstring(vtab.item(irow, 0).text()) for irow in range( - vtab.rowCount())}, - set(ds.variables) - set(ds.coords)) - ds.close() - - def test_load_from_console(self): - """Test whether a dataset can be loaded that is defined in the - console""" - fname = self.get_file('test-t2m-u-v.nc') - if sys.platform == 'win32': - fname = fname.replace('\\', '\\\\') - self.window.console.execute( - "ds = psy.open_dataset('%s')" % fname) - vtab = self.pc.variables_table - ds = psy.open_dataset(self.get_file('test-t2m-u-v.nc')) - self.pc.bt_get_ds.get_from_shell('ds') - self.assertIn('ds', self.pc.ds_combo.currentText()) - self.assertEqual( - {asstring(vtab.item(irow, 0).text()) for irow in range( - vtab.rowCount())}, - set(ds.variables) - set(ds.coords)) - ds.close() - self.window.console.execute("ds.close()") - - def test_plusplus(self): - """Test the add all button""" - # loag a dataset - self.test_load_external_file() - QTest.mouseClick(self.pc.bt_add_all, Qt.LeftButton) - atab = self.pc.array_table - vtab = self.pc.variables_table - self.assertEqual( - [asstring(atab.item(irow, 0).text()) for irow in range( - atab.rowCount())], - [asstring(vtab.item(irow, 0).text()) for irow in range( - vtab.rowCount())]) - - def test_minusminus(self): - """Test the remove all button""" - self.test_plusplus() - QTest.mouseClick(self.pc.bt_remove_all, Qt.LeftButton) - self.assertEqual(self.pc.array_table.rowCount(), 0) - - def test_plus(self): - """Test the add button""" - self.test_load_external_file() - vtab = self.pc.variables_table - atab = self.pc.array_table - nvar = vtab.rowCount() - rows = [nvar - 2, nvar - 1] - for row in rows: - vtab.item(row, 0).setSelected(True) - QTest.mouseClick(self.pc.bt_add, Qt.LeftButton) - self.assertEqual( - [asstring(atab.item(irow, 0).text()) for irow in range( - atab.rowCount())], - [asstring(vtab.item(irow, 0).text()) for irow in rows]) - - def test_minus(self): - """Test the minus button""" - self.test_plusplus() - vtab = self.pc.variables_table - atab = self.pc.array_table - nvar = atab.rowCount() - rows = [nvar - 2, nvar - 1] - for row in rows: - atab.item(row, 0).setSelected(True) - QTest.mouseClick(self.pc.bt_remove, Qt.LeftButton) - variables = [asstring(vtab.item(row, 0).text()) - for row in range(vtab.rowCount()) if row not in rows] - self.assertEqual( - [asstring(atab.item(irow, 0).text()) for irow in range( - atab.rowCount())], - variables) - - def test_update_with_dims(self): - """Test the update with the given dimensions""" - self.test_plusplus() - atab = self.pc.array_table - atab.selectAll() - atab.update_selected(dims={'time': '3'}) - icol = len(atab.desc_cols) + atab.dims.index('time') - vars3d = {var for var, varo in atab.get_ds().variables.items() - if 'time' in varo.dims} - for irow in range(atab.rowCount()): - vname = atab.item(irow, atab.var_col).text() - if vname in vars3d: - item = atab.item(irow, icol) - self.assertEqual( - item.text(), '3', - msg='Wrong time value %s in row %s' % ( - item.text(), irow)) - - def test_add_subplots(self): - """Test the add subplots button""" - from math import ceil - import matplotlib.pyplot as plt - self.test_load_external_file() - self.test_plusplus() - self.pc.cols_axis_edit.setText('2') - self.pc.rows_axis_edit.setText('2') - self.pc.max_axis_edit.setText('3') - QTest.mouseClick(self.pc.bt_add_axes, Qt.LeftButton) - nvar = self.pc.array_table.rowCount() - nfigs = int(ceil(nvar / 3.)) - # create the subplots - axes = self.pc.array_table.axes - self.assertEqual([ax.numCols for ax in axes], [2] * nvar) - self.assertEqual([ax.numRows for ax in axes], [2] * nvar) - rows = [0, 0, 1] * nfigs - cols = [0, 1, 0] * nfigs - self.assertEqual([get_row_num(ax) for ax in axes], rows) - self.assertEqual([get_col_num(ax) for ax in axes], cols) - fig_nums = list(chain(*([i] * 3 for i in range(1, nfigs + 1)))) - self.assertEqual([ax.get_figure().number for ax in axes], fig_nums) - plt.close('all') - - def test_add_single_subplots(self): - """Test the add single subplot button""" - import matplotlib.pyplot as plt - self.test_load_external_file() - self.test_plusplus() - self.pc.cols_axis_edit.setText('2') - self.pc.rows_axis_edit.setText('2') - self.pc.row_axis_edit.setText('1') - self.pc.col_axis_edit.setText('2') - self.pc.array_table.selectAll() - QTest.mouseClick(self.pc.bt_add_single_axes, Qt.LeftButton) - nvar = self.pc.array_table.rowCount() - # create the subplots - axes = self.pc.array_table.axes - # test rows, cols and figure numbers - self.assertEqual([ax.numCols for ax in axes], [2] * nvar) - self.assertEqual([ax.numRows for ax in axes], [2] * nvar) - self.assertEqual([get_row_num(ax) for ax in axes], [0] * nvar) - self.assertEqual([get_col_num(ax) for ax in axes], [1] * nvar) - self.assertEqual([ax.get_figure().number for ax in axes], list( - range(1, nvar + 1))) - plt.close('all') - - def test_axescreator_subplots(self): - """Test the :class:`psyplot_gui.plot_creator.SubplotCreator`""" - import matplotlib.pyplot as plt - from psyplot_gui.plot_creator import AxesCreatorCollection - # load dataset - self.test_load_external_file() - # create arrays - self.test_plusplus() - # use all items - atab = self.pc.array_table - items = [atab.item(i, atab.axes_col) for i in range(atab.rowCount())] - # create the widget to select the subplots - ac = AxesCreatorCollection('subplot') - w = ac.tb.currentWidget() - w.fig_edit.setText('') - w.cols_edit.setText('2') - w.rows_edit.setText('2') - w.num1_edit.setText('2') - w.num2_edit.setText('2') - ac.okpressed.connect(lambda it: atab._change_axes(items, it)) - QTest.mouseClick(ac.bt_ok, Qt.LeftButton) - nvar = self.pc.array_table.rowCount() - # create the subplots - axes = self.pc.array_table.axes - # test rows, cols and figure numbers - self.assertEqual([ax.numCols for ax in axes], [2] * nvar) - self.assertEqual([ax.numRows for ax in axes], [2] * nvar) - self.assertEqual([get_row_num(ax) for ax in axes], [0] * nvar) - self.assertEqual([get_col_num(ax) for ax in axes], [1] * nvar) - self.assertEqual([ax.get_figure().number for ax in axes], list( - range(1, nvar + 1))) - # close figures - plt.close('all') - - def test_axescreator_axes(self): - """Test the :class:`psyplot_gui.plot_creator.AxesCreator`""" - import matplotlib.pyplot as plt - from psyplot_gui.plot_creator import AxesCreatorCollection - # load dataset - self.test_load_external_file() - # create arrays - self.test_plusplus() - # use all items - atab = self.pc.array_table - items = [atab.item(i, atab.axes_col) for i in range(atab.rowCount())] - # create the widget to select the subplots - ac = AxesCreatorCollection('axes') - w = ac.tb.currentWidget() - w.fig_edit.setText('') - w.x0_edit.setText('0.3') - w.y0_edit.setText('0.4') - w.x1_edit.setText('0.7') - w.y1_edit.setText('0.8') - ac.okpressed.connect(lambda it: atab._change_axes(items, it)) - QTest.mouseClick(ac.bt_ok, Qt.LeftButton) - nvar = self.pc.array_table.rowCount() - # create the subplots - axes = self.pc.array_table.axes - boxes = [ax.get_position() for ax in axes] - # test rows, cols and figure numbers - self.assertEqual([box.x0 for box in boxes], [0.3] * nvar) - self.assertEqual([box.y0 for box in boxes], [0.4] * nvar) - self.assertEqual([box.x1 for box in boxes], [0.7] * nvar) - self.assertEqual([box.y1 for box in boxes], [0.8] * nvar) - self.assertEqual([ax.get_figure().number for ax in axes], list( - range(1, nvar + 1))) - # close figures - plt.close('all') - - def test_axescreator_select(self): - """Test the :class:`psyplot_gui.plot_creator.AxesSelector`""" - import matplotlib.pyplot as plt - import numpy as np - from matplotlib.backend_bases import MouseEvent, PickEvent - from psyplot_gui.plot_creator import AxesCreatorCollection - # load dataset - self.test_load_external_file() - # create arrays - self.test_plusplus() - # use all items - atab = self.pc.array_table - items = [atab.item(i, atab.axes_col) for i in range(2)] - # create the widget to select the subplots - ax1 = plt.axes([0.3, 0.4, 0.6, 0.3]) - plt.figure() - ax2 = plt.subplot(211) - ac = AxesCreatorCollection('choose') - w = ac.tb.currentWidget() - fig = ax1.get_figure() - mouseevent1 = MouseEvent( - 'button_release_event', fig.canvas, - *np.mean(ax1.get_position().get_points().T, axis=1)) - w.get_picked_ax(PickEvent('pick', fig.canvas, mouseevent1, artist=ax1)) - fig = ax2.get_figure() - mouseevent2 = MouseEvent( - 'button_release_event', ax2.get_figure().canvas, - *np.mean(ax2.get_position().get_points().T, axis=1)) - w.get_picked_ax(PickEvent('pick', fig.canvas, mouseevent2, artist=ax2)) - - ac.okpressed.connect(lambda it: atab._change_axes(items, it)) - QTest.mouseClick(ac.bt_ok, Qt.LeftButton) - # create the subplots - axes = self.pc.array_table.axes - # check them - self.assertIs(axes[0], ax1) - self.assertIs(axes[1], ax2) - # close figures - plt.close('all') - - def test_arrayname_validator(self): - """Test the :class:`psyplot_gui.plot_creator.ArrayNameValidator`""" - # open dataset - fname = self.get_file('test-t2m-u-v.nc') - ds = psy.open_dataset(fname) - self.pc.bt_get_ds.get_from_shell(ds) - - # add data arrays - QTest.mouseClick(self.pc.bt_add_all, Qt.LeftButton) - - # get names - atab = self.pc.array_table - names = atab.current_names - - # get itemdelegate - item_delegate = atab.itemDelegateForColumn(atab.arr_col) - - # create editor and validator - widget = QWidget() - option = QStyleOptionViewItem() - index = atab.indexFromItem(atab.item(0, atab.arr_col)) - editor = item_delegate.createEditor(widget, option, index) - validator = editor.validator() - - # check validation - self.assertEqual(validator.validate(names[1], len(names[1]))[0], - validator.Intermediate) - self.assertEqual(validator.validate('dummy', 5)[0], - validator.Acceptable) - self.assertNotIn(validator.fixup(names[1]), names) - ds.close() - - def test_variablename_validator(self): - """Test the :class:`psyplot_gui.plot_creator.VariableItemDelegate`""" - # open dataset - try: - from psyplot_gui.compat.qtcompat import QString - except ImportError: - QString = six.text_type - fname = self.get_file('test-t2m-u-v.nc') - ds = psy.open_dataset(fname) - self.pc.bt_get_ds.get_from_shell(ds) - - # add data arrays - QTest.mouseClick(self.pc.bt_add_all, Qt.LeftButton) - - # get names - atab = self.pc.array_table - names = sorted(list(set(ds.variables).difference(ds.coords))) - - # get itemdelegate - item_delegate = atab.itemDelegateForColumn(atab.var_col) - - # create editor and validator - widget = QWidget() - option = QStyleOptionViewItem() - index = atab.indexFromItem(atab.item(0, atab.arr_col)) - editor = item_delegate.createEditor(widget, option, index) - validator = editor.validator() - - # check validation - self.assertEqual(validator.validate(QString('dummy'), 5)[0], - QValidator.Invalid) - self.assertEqual(validator.validate(QString(names[0]), - len(names[0]))[0], - QValidator.Acceptable) - self.assertEqual(validator.validate(QString(names[0])[:2], 2)[0], - QValidator.Intermediate) - s = atab.sep.join(names) - self.assertEqual(validator.validate(QString(s), len(s))[0], - QValidator.Acceptable) - self.assertEqual( - validator.validate( - QString(s[:3] + 'dummy' + s[3:]), len(s) + 5)[0], - QValidator.Invalid) - ds.close() - - def test_drag_drop(self): - """Test the drag and drop of the - :class:`psyplot_gui.plot_creator.ArrayTable`""" - self.pc.show() - # XXX Try to use directly the dropEvent method by setting the source of - # the event! - point = QtCore.QPoint(0, 0) - data = QtCore.QMimeData() - event = QtGui.QDropEvent(point, Qt.MoveAction, data, Qt.LeftButton, - Qt.NoModifier, QtCore.QEvent.Drop) - - # open dataset - fname = self.get_file('test-t2m-u-v.nc') - ds = psy.open_dataset(fname) - self.pc.bt_get_ds.get_from_shell(ds) - - # add data arrays - QTest.mouseClick(self.pc.bt_add_all, Qt.LeftButton) - - # move rows - atab = self.pc.array_table - old = list(atab.arr_names_dict.items()) - atab.selectRow(2) - atab.dropOn(event) - resorted = [old[i] for i in [2, 0, 1] + list(range(3, len(old)))] - self.assertEqual(list(atab.arr_names_dict.items()), resorted, - msg="Rows not moved correctly!") - ds.close() - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_plugin/psyplot_gui_test/__init__.py b/tests/test_plugin/psyplot_gui_test/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_plugin/psyplot_gui_test/plotter.py b/tests/test_plugin/psyplot_gui_test/plotter.py deleted file mode 100644 index 8217e4a..0000000 --- a/tests/test_plugin/psyplot_gui_test/plotter.py +++ /dev/null @@ -1,44 +0,0 @@ -# Test module that defines a plotter -# -# The plotter in this module has been registered by the rcParams in the plugin -# package -from psyplot.plotter import Plotter, Formatoption - - -class TestFmt(Formatoption): - """Some documentation""" - - default = None - - name = 'Test formatoption' - - def get_fmt_widget(self, parent, project): - """Get the formatoption widget to update this formatoption in the GUI - """ - from psyplot_gui.compat.qtcompat import QPushButton - button = QPushButton('Test', parent) - button.clicked.connect(lambda: parent.insert_obj(button.text())) - return button - - def update(self, value): - pass - - -class TestFmt2(TestFmt): - """Another formatoption to the different types of get_fmt_widget""" - - name = 'Second test formatoption' - - def get_fmt_widget(self, parent, project): - """Get the formatoption widget to update this formatoption in the GUI - """ - from psyplot_gui.compat.qtcompat import QPushButton - button = QPushButton('Test', parent) - button.clicked.connect(lambda: parent.insert_obj(2)) - return button - - -class TestPlotter(Plotter): - - fmt1 = TestFmt('fmt1') - fmt2 = TestFmt2('fmt2') diff --git a/tests/test_plugin/psyplot_gui_test/plugin.py b/tests/test_plugin/psyplot_gui_test/plugin.py deleted file mode 100644 index daa2e44..0000000 --- a/tests/test_plugin/psyplot_gui_test/plugin.py +++ /dev/null @@ -1,25 +0,0 @@ -from psyplot.config.rcsetup import RcParams, validate_bool, validate_dict -from psyplot_gui.common import DockMixin -from psyplot_gui.compat.qtcompat import QWidget, Qt - - -class W1(QWidget, DockMixin): - title = 'w1' - dock_position = Qt.LeftDockWidgetArea - - -class W2(QWidget, DockMixin): - title = 'w2' - dock_position = Qt.BottomDockWidgetArea - hidden = True - - -rcParams = RcParams( - defaultParams={ - 'test_plugin': [True, validate_bool], - 'project.plotters': [ - {'gui_test_plotter': { - 'module': 'psyplot_gui_test.plotter', - 'plotter_name': 'TestPlotter', 'import_plotter': True}}, - validate_dict]}) -rcParams.update_from_defaultParams() diff --git a/tests/test_plugin/setup.py b/tests/test_plugin/setup.py deleted file mode 100644 index 9119ccc..0000000 --- a/tests/test_plugin/setup.py +++ /dev/null @@ -1,11 +0,0 @@ -from setuptools import setup, find_packages - - -setup(name='psyplot_gui_test', - version='1.0.0', - license="GPLv2", - packages=find_packages(exclude=['docs', 'tests*', 'examples']), - entry_points={'psyplot_gui': ['w1=psyplot_gui_test.plugin:W1', - 'w2=psyplot_gui_test.plugin:W2'], - 'psyplot': ['plugin=psyplot_gui_test.plugin']}, - zip_safe=False) diff --git a/tests/test_preferences.py b/tests/test_preferences.py deleted file mode 100644 index cc42fa7..0000000 --- a/tests/test_preferences.py +++ /dev/null @@ -1,299 +0,0 @@ -# -*- coding: utf-8 -*- -"""Script to test the :mod:`psyplot_gui.preferences` module""" -import os -import os.path as osp -import shutil -import unittest -import yaml -import tempfile -from itertools import islice -import _base_testing as bt -from psyplot_gui.compat.qtcompat import QTest, Qt, QDialogButtonBox, asstring -from psyplot_gui import rcParams as gui_rcParams -from psyplot import rcParams as psy_rcParams -from psyplot_gui.config.rcsetup import GuiRcParams -import psyplot_gui.preferences as prefs - - -class TestRcParamsWidget(bt.PsyPlotGuiTestCase): - """Test the :class:`psyplot_gui.preferences.RcParamsWidget` class""" - - _created_files = set() - - def setUp(self): - super(TestRcParamsWidget, self).setUp() - self._created_files = set() - - def tearDown(self): - super(TestRcParamsWidget, self).tearDown() - for f in self._created_files: - if osp.exists(f) and osp.isdir(f): - shutil.rmtree(f) - elif osp.exists(f): - os.remove(f) - self._created_files.clear() - - def test_loading(self): - """Test whether the rcParams are loaded correctly""" - # create the preferences window - w = prefs.GuiRcParamsWidget() - w.initialize() - items = list(w.tree.top_level_items) - self.assertEqual(len(items), len(gui_rcParams)) - # test keys - keys = set(gui_rcParams) - for item in items: - keys.remove(asstring(item.text(0))) - self.assertFalse(keys) - - # test values - for item in items: - key = asstring(item.text(0)) - s_val = asstring(w.tree.itemWidget(item.child(0), 2).toPlainText()) - val = yaml.load(s_val, Loader=yaml.Loader) - self.assertEqual(val, gui_rcParams[key], - msg='Failed item %s: %s' % (key, s_val)) - - def test_changing(self): - """Test whether the changes are displayed correctly""" - w = prefs.GuiRcParamsWidget() - gui_rcParams['console.auto_set_mp'] = True - w.initialize() - items = list(w.tree.top_level_items) - for item in items: - if item.text(0) == 'console.auto_set_mp': - iw = w.tree.itemWidget(item.child(0), 2) - iw.setPlainText('f') - QTest.mouseClick(w.bt_select_changed, Qt.LeftButton) - selected_rc = dict(w.tree.selected_rc()) - self.assertEqual(len(selected_rc), 1, msg=selected_rc) - self.assertIn('console.auto_set_mp', selected_rc) - self.assertEqual(selected_rc['console.auto_set_mp'], False) - - for item in items: - if item.text(0) == 'console.auto_set_mp': - iw = w.tree.itemWidget(item.child(0), 2) - iw.setPlainText('t') - - QTest.mouseClick(w.bt_select_none, Qt.LeftButton) - self.assertFalse(dict(w.tree.selected_rc())) - - QTest.mouseClick(w.bt_select_changed, Qt.LeftButton) - self.assertFalse(w.tree.selectedItems()) - - def test_validation(self): - """Test whether the validation works correctly""" - self.window.showMaximized() - w = prefs.GuiRcParamsWidget() - w.initialize() - - # choose an item - for i, item in enumerate(w.tree.top_level_items): - if asstring(item.text(0)) == 'console.auto_set_mp': - break - - self.assertTrue(w.is_valid, msg=w.tree.valid) - # set an invalid value - w.tree.itemWidget(item.child(0), 2).setPlainText('tg') - self.assertFalse(w.tree.valid[i]) - self.assertFalse(w.is_valid) - w.tree.itemWidget(item.child(0), 2).setPlainText('t') - self.assertTrue(w.tree.valid[i]) - self.assertTrue(w.is_valid) - - # set a value that cannot be loaded by yaml - w.tree.itemWidget(item.child(0), 2).setPlainText('"t') - self.assertFalse(w.tree.valid[i]) - self.assertFalse(w.is_valid) - - def test_save_01_all(self): - """Test saving the rcParams""" - w = prefs.GuiRcParamsWidget() - w.initialize() - - QTest.mouseClick(w.bt_select_all, Qt.LeftButton) - self.assertEqual(len(w.tree.selectedItems()), len(gui_rcParams)) - - fname = tempfile.NamedTemporaryFile( - prefix='psyplot_gui_test', suffix='.yml').name - self._created_files.add(fname) - action = w.save_settings_action(target=fname) - action.trigger() - self.assertTrue(osp.exists(fname)) - rc = GuiRcParams(defaultParams=gui_rcParams.defaultParams) - rc.load_from_file(fname) - - self.assertEqual(rc, gui_rcParams) - - def test_save_02_some(self): - """Test saving some parts the rcParams""" - w = prefs.GuiRcParamsWidget() - w.initialize() - - keys = [] - - for item in islice(w.tree.top_level_items, 0, None, 2): - item.setSelected(True) - keys.append(asstring(item.text(0))) - - self.assertEqual(len(w.tree.selectedItems()), len(keys)) - - fname = tempfile.NamedTemporaryFile( - prefix='psyplot_gui_test', suffix='.yml').name - self._created_files.add(fname) - action = w.save_settings_action(target=fname) - action.trigger() - self.assertTrue(osp.exists(fname)) - rc = GuiRcParams(defaultParams=gui_rcParams.defaultParams) - rc.load_from_file(fname) - - self.assertEqual(dict(rc), {key: gui_rcParams[key] for key in keys}) - - def test_update(self): - """Test updating the rcParams""" - w = prefs.GuiRcParamsWidget() - w.initialize() - - fname = tempfile.NamedTemporaryFile( - prefix='psyplot_gui_test', suffix='.yml').name - self._created_files.add(fname) - gui_rcParams.find_all('console').dump(fname) - - keys = [] - - for item in w.tree.top_level_items: - if asstring(item.text(0)).startswith('help_explorer'): - item.setSelected(True) - keys.append(asstring(item.text(0))) - - self.assertEqual(len(w.tree.selectedItems()), len(keys)) - - action = w.save_settings_action(update=True, target=fname) - action.trigger() - self.assertTrue(osp.exists(fname)) - rc = GuiRcParams(defaultParams=gui_rcParams.defaultParams) - rc.load_from_file(fname) - - self.assertEqual( - dict(rc), - {key: gui_rcParams[key] for key in gui_rcParams - if key.startswith('console') or key.startswith('help_explorer')}) - - -class TestPreferences(bt.PsyPlotGuiTestCase): - """Test the :class:`psyplot_gui.preferences.Preferences` widget""" - - def setUp(self): - super(TestPreferences, self).setUp() - self.window.edit_preferences() - self.prefs = self.window.preferences - - def tearDown(self): - # make sure the preferences widget is closed completely - self.prefs.close() - del self.prefs - super(TestPreferences, self).tearDown() - - def test_pages(self): - """Test whether all pages are loaded""" - pref_w = self.prefs - pages = list(pref_w.pages) - self.assertTrue(pages) - self.assertTrue( - any(isinstance(p, prefs.GuiRcParamsWidget) for p in pages), - msg=pages) - self.assertTrue( - any(isinstance(p, prefs.PsyRcParamsWidget) for p in pages), - msg=pages) - - def test_apply(self): - """Test the apply button""" - pref_w = self.prefs - i, cp = next(t for t in enumerate(pref_w.pages) - if isinstance(t[1], prefs.GuiRcParamsWidget)) - pref_w.set_current_index(i) - self.assertIsInstance(pref_w.get_page(), prefs.GuiRcParamsWidget) - self.assertFalse(pref_w.bt_apply.isEnabled()) - - # change a value - current = gui_rcParams['console.auto_set_mp'] - for item in cp.tree.top_level_items: - if item.text(0) == 'console.auto_set_mp': - break - cp.tree.itemWidget(item.child(0), 2).setPlainText( - yaml.dump(not current)) - self.assertTrue(pref_w.bt_apply.isEnabled()) - - QTest.mouseClick(pref_w.bt_apply, Qt.LeftButton) - self.assertEqual(gui_rcParams['console.auto_set_mp'], not current) - self.assertFalse(pref_w.bt_apply.isEnabled()) - - # change the value and the page - cp.tree.itemWidget(item.child(0), 2).setPlainText( - yaml.dump(current)) - self.assertTrue(pref_w.bt_apply.isEnabled()) - j, cp2 = next(t for t in enumerate(pref_w.pages) - if isinstance(t[1], prefs.PsyRcParamsWidget)) - pref_w.set_current_index(j) - self.assertIsInstance(pref_w.get_page(), prefs.PsyRcParamsWidget) - self.assertFalse(pref_w.bt_apply.isEnabled()) - pref_w.set_current_index(i) - self.assertTrue(pref_w.bt_apply.isEnabled()) - - def test_ok(self): - """Test the apply button""" - pref_w = self.prefs - i, cp = next(t for t in enumerate(pref_w.pages) - if isinstance(t[1], prefs.GuiRcParamsWidget)) - pref_w.set_current_index(i) - self.assertIsInstance(pref_w.get_page(), prefs.GuiRcParamsWidget) - self.assertFalse(pref_w.bt_apply.isEnabled()) - - # change a value - current = gui_rcParams['console.auto_set_mp'] - for item in cp.tree.top_level_items: - if item.text(0) == 'console.auto_set_mp': - break - cp.tree.itemWidget(item.child(0), 2).setPlainText( - yaml.dump(not current)) - self.assertTrue(pref_w.bt_apply.isEnabled()) - - # change a value in the PsyRcParamsWidget - i, cp = next(t for t in enumerate(pref_w.pages) - if isinstance(t[1], prefs.PsyRcParamsWidget)) - pref_w.set_current_index(i) - self.assertIsInstance(pref_w.get_page(), prefs.PsyRcParamsWidget) - self.assertFalse(pref_w.bt_apply.isEnabled()) - - # change a value - for item in cp.tree.top_level_items: - if item.text(0) == 'decoder.x': - break - cp.tree.itemWidget(item.child(0), 2).setPlainText( - yaml.dump({'test'})) - self.assertTrue(pref_w.bt_apply.isEnabled()) - - QTest.mouseClick(pref_w.bbox.button(QDialogButtonBox.Ok), - Qt.LeftButton) - self.assertEqual(gui_rcParams['console.auto_set_mp'], not current) - self.assertEqual(psy_rcParams['decoder.x'], {'test'}) - - def test_plugin_pages(self): - try: - from psyplot_gui_test.plugin import rcParams - except ImportError: - self.skipTest("psyplot_gui_test not installed") - pref_w = self.prefs - QTest.mouseClick(pref_w.bt_load_plugins, Qt.LeftButton) - i, cp = next(t for t in enumerate(pref_w.pages) - if isinstance(t[1], prefs.RcParamsWidget) and - not isinstance(t[1], prefs.PsyRcParamsWidget) and - 'test_plugin' in ( - item.text(0) for item in t[1].tree.top_level_items)) - pref_w.set_current_index(i) - self.assertEqual(len(list(cp.tree.top_level_items)), len(rcParams), - msg=cp) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_project_content.py b/tests/test_project_content.py deleted file mode 100644 index df69c30..0000000 --- a/tests/test_project_content.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -from collections import defaultdict -import os.path as osp -import unittest -import _base_testing as bt -import xarray as xr -import psyplot.data as psyd -import psyplot.project as psy -from psyplot_gui.compat.qtcompat import QTest, Qt, QDialogButtonBox, asstring - - -class ProjectContentTest(bt.PsyPlotGuiTestCase): - """Test case for testing whether the project content part is updated - correctly""" - - @property - def project_content(self): - return self.window.project_content - - @property - def content_widget(self): - return self.project_content.content_widget - - def get_list(self, key): - return self.content_widget.lists[key] - - def _selected_rows(self, name): - return list(map(lambda ind: ind.row(), - self.get_list(name).selectedIndexes())) - - def test_content_update(self): - """Test whether the list is updated correctly""" - w = self.content_widget - lists = w.lists - # currently it should be empty - self.assertEqual(w.count(), 1) - self.assertEqual(w.indexOf(lists['All']), 0) - self.assertFalse(w.isItemEnabled(0), msg='List "All" is enabled!') - - # create some plots - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m') - sp2 = psy.plot.lineplot(self.get_file('test-t2m-u-v.nc'), name='t2m', - t=0, x=0, y=0) - d = defaultdict(lambda: 1) - d['All'] = 2 - d['simple'] = 2 - for name in ['All', 'simple', 'lineplot', 'plot2d']: - self.assertIn(name, lists) - l = lists[name] - i = self.content_widget.indexOf(l) - self.assertNotEqual(i, -1, msg='Missing the list in the widget!') - self.assertTrue(self.content_widget.isItemEnabled(i), - msg='%s is not enabled!' % name) - self.assertEqual(l.count(), d[name], - msg='Wrong number of arrays in %s' % name) - if name == 'plot2d': - self.assertEqual(asstring(l.item(0).text()), - sp[0].psy._short_info(), - msg='Wrong text in plot2d') - else: - self.assertEqual( - asstring(l.item(d[name] - 1).text()), sp2[0]._short_info(), - msg='Wrong text in %s' % name) - self.assertEqual(self._selected_rows('plot2d'), [], - msg='Array in %s is wrongly selected!' % name) - self.assertEqual(self._selected_rows('lineplot'), [0], - msg='Array in %s is not selected!' % name) - self.assertEqual(self._selected_rows('simple'), [1], - msg='Wrong selection!') - self.assertEqual(self._selected_rows('All'), [1], - msg='Wrong selection!') - - # close the project - full = sp + sp2 - full.close(True, True, True) - self.assertEqual(w.count(), 1) - self.assertEqual(w.indexOf(lists['All']), 0) - self.assertFalse(w.isItemEnabled(0), msg='List "All" is enabled!') - - def test_select_all_button(self): - """Test whether the subproject is changed correctly when selecting all - """ - self.window.showMaximized() - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m', - time=[0, 1]) - psy.scp(None) - QTest.mouseClick(self.project_content.select_all_button, Qt.LeftButton) - self.assertIs(psy.gcp()[0], sp[0], - msg='actual: %s, expected: %s' % (psy.gcp(), sp)) - self.assertIs(psy.gcp()[1], sp[1]) - self.assertEqual(self._selected_rows('All'), [0, 1], - msg='Not all arrays selected!') - - def test_unselect_all_button(self): - """Test whether the subproject is changed cleared when unselecting all - """ - self.window.showMaximized() - psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m', - time=[0, 1]) - # test whether the current subproject is not empty - self.assertTrue(bool(psy.gcp())) - # unselect all - QTest.mouseClick(self.project_content.unselect_button, Qt.LeftButton) - self.assertFalse(bool(psy.gcp())) - - def test_item_selection(self): - """Test whether the subproject is changed correctly if the selection in - the list changes""" - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m', - time=[0, 1]) - self.assertIs(psy.gcp()[0], sp[0]) - self.assertIs(psy.gcp()[1], sp[1]) - self.content_widget.lists['All'].item(0).setSelected(False) - self.assertIs(psy.gcp()[0], sp[1]) - self.content_widget.lists['All'].item(0).setSelected(True) - self.assertIs(psy.gcp()[0], sp[0], msg='Reselection failed!') - self.assertIs(psy.gcp()[1], sp[1], msg='Reselection failed!') - - -class FiguresTreeTest(bt.PsyPlotGuiTestCase): - """Test to check whether the figures tree behaves correctly""" - - @property - def tree(self): - return self.window.figures_tree - - def test_toplevel(self): - """Test whether the figures are updated correctly""" - def check_figs(msg=None): - figs = iter(sp.figs) - for item in map(self.tree.topLevelItem, - range(self.tree.topLevelItemCount())): - self.assertEqual(asstring(item.text(0)), - next(figs).canvas.get_window_title(), msg=msg) - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m', - time=[0, 1]) - check_figs() - sp[1:].close(True, True) - check_figs('Figures not updated correctly!') - - def test_sublevel(self): - """Test whether the arrays are updated correctly""" - def check_figs(msg=None): - arrays = iter(sp) - for i, (fig, val) in enumerate(sp.figs.items()): - top = self.tree.topLevelItem(i) - self.assertEqual(asstring(top.text(0)), - fig.canvas.get_window_title()) - for child in map(top.child, range(top.childCount())): - self.assertEqual(asstring(child.text(0)), - next(arrays).psy._short_info(), msg=msg) - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m', - time=[0, 1, 2], ax=(1, 2)) - check_figs() - sp[1:2].close(False, True) - sp = sp[0::2] - check_figs('Arrays not updated correctly!') - sp.close(True, True) - self.assertEqual(self.tree.topLevelItemCount(), 0) - - -class DatasetTreeTest(bt.PsyPlotGuiTestCase): - """Test to check whether the dataset tree behaves correctly""" - - @property - def tree(self): - return self.window.ds_tree - - def test_toplevel(self): - """Test whether the toplevel items are shown correctly""" - fname = self.get_file('test-t2m-u-v.nc') - sp1 = psy.plot.plot2d(fname, name='t2m') - sp2 = psy.plot.plot2d(fname, name='t2m') - count = next(psyd._ds_counter) - 1 - fname = osp.basename(fname) - ds1 = sp1[0].psy.base - ds2 = sp2[0].psy.base - - self.assertEqual(self.tree.topLevelItemCount(), 2) - self.assertEqual(asstring(self._get_toplevel_item(ds1).text(0)), - '%i: %s' % (count - 1, fname)) - self.assertEqual(asstring(self._get_toplevel_item(ds2).text(0)), - '*%i: %s' % (count, fname)) - psy.scp(sp1) - self.assertEqual(asstring(self._get_toplevel_item(ds1).text(0)), - '*%i: %s' % (count - 1, fname)) - self.assertEqual(asstring(self._get_toplevel_item(ds2).text(0)), - '%i: %s' % (count, fname)) - sp2.close(True, True) - self.assertEqual(asstring(self._get_toplevel_item(ds1).text(0)), - '*%i: %s' % (count - 1, fname)) - self.assertEqual(self.tree.topLevelItemCount(), 1) - - def _get_toplevel_item(self, ds): - toplevel = None - for item in map(self.tree.topLevelItem, - range(self.tree.topLevelItemCount())): - if item.ds() is ds: - toplevel = item - break - self.assertIsNotNone( - toplevel, msg='No item found that corresponds to %s' % ds) - return toplevel - - def _test_ds_representation(self, ds): - toplevel = self._get_toplevel_item(ds) - coords = set(ds.coords) - variables = set(ds.variables) - coords - for child in map(toplevel.variables.child, - range(toplevel.variables.childCount())): - variables.remove(asstring(child.text(0))) - self.assertEqual(len(variables), 0, msg='Variables not found: %s' % ( - variables)) - for child in map(toplevel.coords.child, - range(toplevel.coords.childCount())): - coords.remove(asstring(child.text(0))) - self.assertEqual(len(coords), 0, msg='Coordinates not found: %s' % ( - coords)) - - def test_sublevel(self): - """Test whether the variables and coordinates are displayed correctly - """ - sp = psy.plot.plot2d(self.get_file('test-t2m-u-v.nc'), name='t2m') - ds = sp[0].psy.base - self._test_ds_representation(ds) - - def test_refresh(self): - """Test the refreshing of a dataset""" - fname = self.get_file('test-t2m-u-v.nc') - sp1 = psy.plot.plot2d(fname, name='t2m') - sp2 = psy.plot.plot2d(fname, name='t2m') - ds = sp1[0].psy.base - ds['test'] = xr.Variable(('testdim', ), list(range(5))) - item = self.tree.topLevelItem(0) - self.tree.refresh_items(item) - self._test_ds_representation(ds) - self._test_ds_representation(sp2[0].psy.base) - - def test_refresh_all(self): - """Test the refreshing of a dataset""" - fname = self.get_file('test-t2m-u-v.nc') - sp1 = psy.plot.plot2d(fname, name='t2m') - sp2 = psy.plot.plot2d(fname, name='t2m') - ds = sp1[0].psy.base - ds['test'] = xr.Variable(('testdim', ), list(range(5))) - ds2 = sp2[0].psy.base - ds2['test2'] = list(range(10)) - self.tree.refresh_items() - self._test_ds_representation(ds) - self._test_ds_representation(ds2) - - def test_expansion_reset(self): - """Test whether the expansion state is recovered""" - fname = self.get_file('test-t2m-u-v.nc') - psy.plot.plot2d(fname, name='t2m') - self.tree.expandItem(self.tree.topLevelItem(0)) - self.tree.expandItem(self.tree.topLevelItem(0).child(1)) - - # trigger an update - psy.plot.plot2d(fname, name='t2m') - self.assertTrue(self.tree.topLevelItem(0).isExpanded()) - self.assertFalse(self.tree.topLevelItem(0).child(0).isExpanded()) - self.assertTrue(self.tree.topLevelItem(0).child(1).isExpanded()) - self.assertFalse(self.tree.topLevelItem(0).child(2).isExpanded()) - - def test_make_plot(self): - """Test the making of plots""" - fname = self.get_file('test-t2m-u-v.nc') - sp1 = psy.plot.plot2d(fname, name='t2m') - # to make sure, have in the mean time another dataset in the current - # subproject, we create a second plot - psy.plot.plot2d(fname, name='t2m') - ds = sp1[0].psy.base - name = 't2m' - self.tree.make_plot(ds, name) - try: - self.window.plot_creator.pm_combo.setCurrentText('plot2d') - except AttributeError: - self.window.plot_creator.pm_combo.setEditText('plot2d') - QTest.mouseClick( - self.window.plot_creator.bbox.button(QDialogButtonBox.Ok), - Qt.LeftButton) - self.assertIs(ds, psy.gcp()[0].psy.base) - - -if __name__ == '__main__': - unittest.main() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 719036f..0000000 --- a/versioneer.py +++ /dev/null @@ -1,1822 +0,0 @@ - -# Version: 0.18 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -""" - -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -LONG_VERSION_PY['git'] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 - except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)