diff --git a/.doctr-files b/.doctr-files index 910b1b6..4ab2ab9 100644 --- a/.doctr-files +++ b/.doctr-files @@ -13,7 +13,6 @@ ./_images/Tutorial_05_Monte_Carlo_studies_etc_28_1.png ./_images/Tutorial_06_Tips&Tricks_25_0.png ./_images/relax.png -./_modules/IPython/core/display.html ./_modules/anypytools/abcutils.html ./_modules/anypytools/datautils.html ./_modules/anypytools/h5py_wrapper.html @@ -21,7 +20,6 @@ ./_modules/anypytools/pytest_plugin.html ./_modules/anypytools/tools.html ./_modules/index.html -./_modules/logging.html ./_sources/Tutorial/01_Getting_started_with_anypytools.ipynb.txt ./_sources/Tutorial/02_Generating_macros.ipynb.txt ./_sources/Tutorial/03_Working_with_output_from_Anybody.ipynb.txt @@ -63,7 +61,7 @@ ./_static/icon-seealso.png ./_static/icon-todo.png ./_static/icon-warning.png -./_static/jquery-3.2.1.js +./_static/jquery-3.4.1.js ./_static/jquery.cookie.js ./_static/jquery.js ./_static/language_data.js diff --git a/Tutorial/01_Getting_started_with_anypytools.html b/Tutorial/01_Getting_started_with_anypytools.html index c3027e3..f5a1341 100644 --- a/Tutorial/01_Getting_started_with_anypytools.html +++ b/Tutorial/01_Getting_started_with_anypytools.html @@ -6,7 +6,7 @@ - Getting Started with AnyPyTools — AnyPyTools 1.2.0 documentation + Getting Started with AnyPyTools — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -597,7 +597,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -605,7 +605,7 @@

    Navigation

    diff --git a/Tutorial/02_Generating_macros.html b/Tutorial/02_Generating_macros.html index f7c3606..e92cc53 100644 --- a/Tutorial/02_Generating_macros.html +++ b/Tutorial/02_Generating_macros.html @@ -6,7 +6,7 @@ - Creating AnyScript Macros — AnyPyTools 1.2.0 documentation + Creating AnyScript Macros — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -689,7 +689,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -697,7 +697,7 @@

    Navigation

    diff --git a/Tutorial/03_Working_with_output_from_Anybody.html b/Tutorial/03_Working_with_output_from_Anybody.html index 5fef3e6..32141cb 100644 --- a/Tutorial/03_Working_with_output_from_Anybody.html +++ b/Tutorial/03_Working_with_output_from_Anybody.html @@ -6,7 +6,7 @@ - Working with data from AnyBody — AnyPyTools 1.2.0 documentation + Working with data from AnyBody — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -647,7 +647,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -655,7 +655,7 @@

    Navigation

    diff --git a/Tutorial/04_Batch_processing_multiple_models.html b/Tutorial/04_Batch_processing_multiple_models.html index ff633aa..94827b5 100644 --- a/Tutorial/04_Batch_processing_multiple_models.html +++ b/Tutorial/04_Batch_processing_multiple_models.html @@ -6,7 +6,7 @@ - Batch processing — AnyPyTools 1.2.0 documentation + Batch processing — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -471,7 +471,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -479,7 +479,7 @@

    Navigation

    diff --git a/Tutorial/05_Monte_Carlo_studies_etc.html b/Tutorial/05_Monte_Carlo_studies_etc.html index d5d5f4b..919c08d 100644 --- a/Tutorial/05_Monte_Carlo_studies_etc.html +++ b/Tutorial/05_Monte_Carlo_studies_etc.html @@ -6,7 +6,7 @@ - Advanced Examples — AnyPyTools 1.2.0 documentation + Advanced Examples — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -707,7 +707,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -715,7 +715,7 @@

    Navigation

    diff --git a/Tutorial/06_Tips&Tricks.html b/Tutorial/06_Tips&Tricks.html index 8ae1f72..35a9517 100644 --- a/Tutorial/06_Tips&Tricks.html +++ b/Tutorial/06_Tips&Tricks.html @@ -6,7 +6,7 @@ - Tips & Trics for anypytools — AnyPyTools 1.2.0 documentation + Tips & Trics for anypytools — AnyPyTools 1.2.1 documentation @@ -45,7 +45,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -759,7 +759,7 @@

    Navigation

  • previous    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -767,7 +767,7 @@

    Navigation

    diff --git a/_modules/IPython/core/display.html b/_modules/IPython/core/display.html deleted file mode 100644 index 14589a2..0000000 --- a/_modules/IPython/core/display.html +++ /dev/null @@ -1,1592 +0,0 @@ - - - - - - - - - IPython.core.display — AnyPyTools 1.2.0 documentation - - - - - - - - - - - - - - - - -
    - - -
    - - -
    -
    -
    -
    - -

    Source code for IPython.core.display

    -# -*- coding: utf-8 -*-
    -"""Top-level display functions for displaying object in different formats."""
    -
    -# Copyright (c) IPython Development Team.
    -# Distributed under the terms of the Modified BSD License.
    -
    -
    -from binascii import b2a_hex, b2a_base64, hexlify
    -import json
    -import mimetypes
    -import os
    -import struct
    -import sys
    -import warnings
    -from copy import deepcopy
    -
    -from IPython.utils.py3compat import cast_unicode
    -from IPython.testing.skipdoctest import skip_doctest
    -
    -__all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
    -'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
    -'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
    -'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON',
    -'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats',
    -'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle',
    -'Video']
    -
    -#-----------------------------------------------------------------------------
    -# utility functions
    -#-----------------------------------------------------------------------------
    -
    -def _safe_exists(path):
    -    """Check path, but don't let exceptions raise"""
    -    try:
    -        return os.path.exists(path)
    -    except Exception:
    -        return False
    -
    -def _merge(d1, d2):
    -    """Like update, but merges sub-dicts instead of clobbering at the top level.
    -
    -    Updates d1 in-place
    -    """
    -
    -    if not isinstance(d2, dict) or not isinstance(d1, dict):
    -        return d2
    -    for key, value in d2.items():
    -        d1[key] = _merge(d1.get(key), value)
    -    return d1
    -
    -def _display_mimetype(mimetype, objs, raw=False, metadata=None):
    -    """internal implementation of all display_foo methods
    -
    -    Parameters
    -    ----------
    -    mimetype : str
    -        The mimetype to be published (e.g. 'image/png')
    -    objs : tuple of objects
    -        The Python objects to display, or if raw=True raw text data to
    -        display.
    -    raw : bool
    -        Are the data objects raw data or Python objects that need to be
    -        formatted before display? [default: False]
    -    metadata : dict (optional)
    -        Metadata to be associated with the specific mimetype output.
    -    """
    -    if metadata:
    -        metadata = {mimetype: metadata}
    -    if raw:
    -        # turn list of pngdata into list of { 'image/png': pngdata }
    -        objs = [ {mimetype: obj} for obj in objs ]
    -    display(*objs, raw=raw, metadata=metadata, include=[mimetype])
    -
    -#-----------------------------------------------------------------------------
    -# Main functions
    -#-----------------------------------------------------------------------------
    -
    -# use * to indicate transient is keyword-only
    -def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
    -    """Publish data and metadata to all frontends.
    -
    -    See the ``display_data`` message in the messaging documentation for
    -    more details about this message type.
    -
    -    Keys of data and metadata can be any mime-type.
    -
    -    Parameters
    -    ----------
    -    data : dict
    -        A dictionary having keys that are valid MIME types (like
    -        'text/plain' or 'image/svg+xml') and values that are the data for
    -        that MIME type. The data itself must be a JSON'able data
    -        structure. Minimally all data should have the 'text/plain' data,
    -        which can be displayed by all frontends. If more than the plain
    -        text is given, it is up to the frontend to decide which
    -        representation to use.
    -    metadata : dict
    -        A dictionary for metadata related to the data. This can contain
    -        arbitrary key, value pairs that frontends can use to interpret
    -        the data. mime-type keys matching those in data can be used
    -        to specify metadata about particular representations.
    -    source : str, deprecated
    -        Unused.
    -    transient : dict, keyword-only
    -        A dictionary of transient data, such as display_id.
    -        """
    -    from IPython.core.interactiveshell import InteractiveShell
    -
    -    display_pub = InteractiveShell.instance().display_pub
    -
    -    # only pass transient if supplied,
    -    # to avoid errors with older ipykernel.
    -    # TODO: We could check for ipykernel version and provide a detailed upgrade message.
    -    if transient:
    -        kwargs['transient'] = transient
    -
    -    display_pub.publish(
    -        data=data,
    -        metadata=metadata,
    -        **kwargs
    -    )
    -
    -
    -def _new_id():
    -    """Generate a new random text id with urandom"""
    -    return b2a_hex(os.urandom(16)).decode('ascii')
    -
    -
    -
    [docs]def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): - """Display a Python object in all frontends. - - By default all representations will be computed and sent to the frontends. - Frontends can decide which representation is used and how. - - In terminal IPython this will be similar to using :func:`print`, for use in richer - frontends see Jupyter notebook examples with rich display logic. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display. - raw : bool, optional - Are the objects to be displayed already mimetype-keyed dicts of raw display data, - or Python objects that need to be formatted before display? [default: False] - include : list, tuple or set, optional - A list of format type strings (MIME types) to include in the - format data dict. If this is set *only* the format types included - in this list will be computed. - exclude : list, tuple or set, optional - A list of format type strings (MIME types) to exclude in the format - data dict. If this is set all format types will be computed, - except for those included in this argument. - metadata : dict, optional - A dictionary of metadata to associate with the output. - mime-type keys in this dictionary will be associated with the individual - representation formats, if they exist. - transient : dict, optional - A dictionary of transient data to associate with the output. - Data in this dict should not be persisted to files (e.g. notebooks). - display_id : str, bool optional - Set an id for the display. - This id can be used for updating this display area later via update_display. - If given as `True`, generate a new `display_id` - kwargs: additional keyword-args, optional - Additional keyword-arguments are passed through to the display publisher. - - Returns - ------- - - handle: DisplayHandle - Returns a handle on updatable displays for use with :func:`update_display`, - if `display_id` is given. Returns :any:`None` if no `display_id` is given - (default). - - Examples - -------- - - >>> class Json(object): - ... def __init__(self, json): - ... self.json = json - ... def _repr_pretty_(self, pp, cycle): - ... import json - ... pp.text(json.dumps(self.json, indent=2)) - ... def __repr__(self): - ... return str(self.json) - ... - - >>> d = Json({1:2, 3: {4:5}}) - - >>> print(d) - {1: 2, 3: {4: 5}} - - >>> display(d) - { - "1": 2, - "3": { - "4": 5 - } - } - - >>> def int_formatter(integer, pp, cycle): - ... pp.text('I'*integer) - - >>> plain = get_ipython().display_formatter.formatters['text/plain'] - >>> plain.for_type(int, int_formatter) - <function _repr_pprint at 0x...> - >>> display(7-5) - II - - >>> del plain.type_printers[int] - >>> display(7-5) - 2 - - See Also - -------- - - :func:`update_display` - - Notes - ----- - - In Python, objects can declare their textual representation using the - `__repr__` method. IPython expands on this idea and allows objects to declare - other, rich representations including: - - - HTML - - JSON - - PNG - - JPEG - - SVG - - LaTeX - - A single object can declare some or all of these representations; all are - handled by IPython's display system. - - The main idea of the first approach is that you have to implement special - display methods when you define your class, one for each representation you - want to use. Here is a list of the names of the special methods and the - values they must return: - - - `_repr_html_`: return raw HTML as a string, or a tuple (see below). - - `_repr_json_`: return a JSONable dict, or a tuple (see below). - - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). - - `_repr_png_`: return raw PNG data, or a tuple (see below). - - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). - - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", - or a tuple (see below). - - `_repr_mimebundle_`: return a full mimebundle containing the mapping - from all mimetypes to data. - Use this for any mime-type not listed above. - - The above functions may also return the object's metadata alonside the - data. If the metadata is available, the functions will return a tuple - containing the data and metadata, in that order. If there is no metadata - available, then the functions will return the data only. - - When you are directly writing your own classes, you can adapt them for - display in IPython by following the above approach. But in practice, you - often need to work with existing classes that you can't easily modify. - - You can refer to the documentation on integrating with the display system in - order to register custom formatters for already existing types - (:ref:`integrating_rich_display`). - - .. versionadded:: 5.4 display available without import - .. versionadded:: 6.1 display available without import - - Since IPython 5.4 and 6.1 :func:`display` is automatically made available to - the user without import. If you are using display in a document that might - be used in a pure python context or with older version of IPython, use the - following import at the top of your file:: - - from IPython.display import display - - """ - from IPython.core.interactiveshell import InteractiveShell - - if not InteractiveShell.initialized(): - # Directly print objects. - print(*objs) - return - - raw = kwargs.pop('raw', False) - if transient is None: - transient = {} - if metadata is None: - metadata={} - if display_id: - if display_id is True: - display_id = _new_id() - transient['display_id'] = display_id - if kwargs.get('update') and 'display_id' not in transient: - raise TypeError('display_id required for update_display') - if transient: - kwargs['transient'] = transient - - if not raw: - format = InteractiveShell.instance().display_formatter.format - - for obj in objs: - if raw: - publish_display_data(data=obj, metadata=metadata, **kwargs) - else: - format_dict, md_dict = format(obj, include=include, exclude=exclude) - if not format_dict: - # nothing to display (e.g. _ipython_display_ took over) - continue - if metadata: - # kwarg-specified metadata gets precedence - _merge(md_dict, metadata) - publish_display_data(data=format_dict, metadata=md_dict, **kwargs) - if display_id: - return DisplayHandle(display_id)
    - - -# use * for keyword-only display_id arg -def update_display(obj, *, display_id, **kwargs): - """Update an existing display by id - - Parameters - ---------- - - obj: - The object with which to update the display - display_id: keyword-only - The id of the display to update - - See Also - -------- - - :func:`display` - """ - kwargs['update'] = True - display(obj, display_id=display_id, **kwargs) - - -class DisplayHandle(object): - """A handle on an updatable display - - Call `.update(obj)` to display a new object. - - Call `.display(obj`) to add a new instance of this display, - and update existing instances. - - See Also - -------- - - :func:`display`, :func:`update_display` - - """ - - def __init__(self, display_id=None): - if display_id is None: - display_id = _new_id() - self.display_id = display_id - - def __repr__(self): - return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) - - def display(self, obj, **kwargs): - """Make a new display with my id, updating existing instances. - - Parameters - ---------- - - obj: - object to display - **kwargs: - additional keyword arguments passed to display - """ - display(obj, display_id=self.display_id, **kwargs) - - def update(self, obj, **kwargs): - """Update existing displays with my id - - Parameters - ---------- - - obj: - object to display - **kwargs: - additional keyword arguments passed to update_display - """ - update_display(obj, display_id=self.display_id, **kwargs) - - -def display_pretty(*objs, **kwargs): - """Display the pretty (default) representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw text data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('text/plain', objs, **kwargs) - - -def display_html(*objs, **kwargs): - """Display the HTML representation of an object. - - Note: If raw=False and the object does not have a HTML - representation, no HTML will be shown. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw HTML data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('text/html', objs, **kwargs) - - -def display_markdown(*objs, **kwargs): - """Displays the Markdown representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw markdown data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - - _display_mimetype('text/markdown', objs, **kwargs) - - -def display_svg(*objs, **kwargs): - """Display the SVG representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw svg data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('image/svg+xml', objs, **kwargs) - - -def display_png(*objs, **kwargs): - """Display the PNG representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw png data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('image/png', objs, **kwargs) - - -def display_jpeg(*objs, **kwargs): - """Display the JPEG representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw JPEG data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('image/jpeg', objs, **kwargs) - - -def display_latex(*objs, **kwargs): - """Display the LaTeX representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw latex data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('text/latex', objs, **kwargs) - - -def display_json(*objs, **kwargs): - """Display the JSON representation of an object. - - Note that not many frontends support displaying JSON. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw json data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('application/json', objs, **kwargs) - - -def display_javascript(*objs, **kwargs): - """Display the Javascript representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw javascript data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('application/javascript', objs, **kwargs) - - -def display_pdf(*objs, **kwargs): - """Display the PDF representation of an object. - - Parameters - ---------- - objs : tuple of objects - The Python objects to display, or if raw=True raw javascript data to - display. - raw : bool - Are the data objects raw data or Python objects that need to be - formatted before display? [default: False] - metadata : dict (optional) - Metadata to be associated with the specific mimetype output. - """ - _display_mimetype('application/pdf', objs, **kwargs) - - -#----------------------------------------------------------------------------- -# Smart classes -#----------------------------------------------------------------------------- - - -class DisplayObject(object): - """An object that wraps data to be displayed.""" - - _read_flags = 'r' - _show_mem_addr = False - metadata = None - - def __init__(self, data=None, url=None, filename=None, metadata=None): - """Create a display object given raw data. - - When this object is returned by an expression or passed to the - display function, it will result in the data being displayed - in the frontend. The MIME type of the data should match the - subclasses used, so the Png subclass should be used for 'image/png' - data. If the data is a URL, the data will first be downloaded - and then displayed. If - - Parameters - ---------- - data : unicode, str or bytes - The raw data or a URL or file to load the data from - url : unicode - A URL to download the data from. - filename : unicode - Path to a local file to load the data from. - metadata : dict - Dict of metadata associated to be the object when displayed - """ - if data is not None and isinstance(data, str): - if data.startswith('http') and url is None: - url = data - filename = None - data = None - elif _safe_exists(data) and filename is None: - url = None - filename = data - data = None - - self.data = data - self.url = url - self.filename = filename - - if metadata is not None: - self.metadata = metadata - elif self.metadata is None: - self.metadata = {} - - self.reload() - self._check_data() - - def __repr__(self): - if not self._show_mem_addr: - cls = self.__class__ - r = "<%s.%s object>" % (cls.__module__, cls.__name__) - else: - r = super(DisplayObject, self).__repr__() - return r - - def _check_data(self): - """Override in subclasses if there's something to check.""" - pass - - def _data_and_metadata(self): - """shortcut for returning metadata with shape information, if defined""" - if self.metadata: - return self.data, deepcopy(self.metadata) - else: - return self.data - - def reload(self): - """Reload the raw data from file or URL.""" - if self.filename is not None: - with open(self.filename, self._read_flags) as f: - self.data = f.read() - elif self.url is not None: - try: - # Deferred import - from urllib.request import urlopen - response = urlopen(self.url) - self.data = response.read() - # extract encoding from header, if there is one: - encoding = None - for sub in response.headers['content-type'].split(';'): - sub = sub.strip() - if sub.startswith('charset'): - encoding = sub.split('=')[-1].strip() - break - # decode data, if an encoding was specified - if encoding: - self.data = self.data.decode(encoding, 'replace') - except: - self.data = None - -class TextDisplayObject(DisplayObject): - """Validate that display data is text""" - def _check_data(self): - if self.data is not None and not isinstance(self.data, str): - raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) - -class Pretty(TextDisplayObject): - - def _repr_pretty_(self, pp, cycle): - return pp.text(self.data) - - -
    [docs]class HTML(TextDisplayObject): - - def __init__(self, data=None, url=None, filename=None, metadata=None): - def warn(): - if not data: - return False - - # - # Avoid calling lower() on the entire data, because it could be a - # long string and we're only interested in its beginning and end. - # - prefix = data[:10].lower() - suffix = data[-10:].lower() - return prefix.startswith("<iframe ") and suffix.endswith("</iframe>") - - if warn(): - warnings.warn("Consider using IPython.display.IFrame instead") - super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata) - - def _repr_html_(self): - return self._data_and_metadata() - - def __html__(self): - """ - This method exists to inform other HTML-using modules (e.g. Markupsafe, - htmltag, etc) that this object is HTML and does not need things like - special characters (<>&) escaped. - """ - return self._repr_html_()
    - - -class Markdown(TextDisplayObject): - - def _repr_markdown_(self): - return self._data_and_metadata() - - -class Math(TextDisplayObject): - - def _repr_latex_(self): - s = r"$\displaystyle %s$" % self.data.strip('$') - if self.metadata: - return s, deepcopy(self.metadata) - else: - return s - - -class Latex(TextDisplayObject): - - def _repr_latex_(self): - return self._data_and_metadata() - - -class SVG(DisplayObject): - - _read_flags = 'rb' - # wrap data in a property, which extracts the <svg> tag, discarding - # document headers - _data = None - - @property - def data(self): - return self._data - - @data.setter - def data(self, svg): - if svg is None: - self._data = None - return - # parse into dom object - from xml.dom import minidom - x = minidom.parseString(svg) - # get svg tag (should be 1) - found_svg = x.getElementsByTagName('svg') - if found_svg: - svg = found_svg[0].toxml() - else: - # fallback on the input, trust the user - # but this is probably an error. - pass - svg = cast_unicode(svg) - self._data = svg - - def _repr_svg_(self): - return self._data_and_metadata() - -class ProgressBar(DisplayObject): - """Progressbar supports displaying a progressbar like element - """ - def __init__(self, total): - """Creates a new progressbar - - Parameters - ---------- - total : int - maximum size of the progressbar - """ - self.total = total - self._progress = 0 - self.html_width = '60ex' - self.text_width = 60 - self._display_id = hexlify(os.urandom(8)).decode('ascii') - - def __repr__(self): - fraction = self.progress / self.total - filled = '=' * int(fraction * self.text_width) - rest = ' ' * (self.text_width - len(filled)) - return '[{}{}] {}/{}'.format( - filled, rest, - self.progress, self.total, - ) - - def _repr_html_(self): - return "<progress style='width:{}' max='{}' value='{}'></progress>".format( - self.html_width, self.total, self.progress) - - def display(self): - display(self, display_id=self._display_id) - - def update(self): - display(self, display_id=self._display_id, update=True) - - @property - def progress(self): - return self._progress - - @progress.setter - def progress(self, value): - self._progress = value - self.update() - - def __iter__(self): - self.display() - self._progress = -1 # First iteration is 0 - return self - - def __next__(self): - """Returns current value and increments display by one.""" - self.progress += 1 - if self.progress < self.total: - return self.progress - else: - raise StopIteration() - -class JSON(DisplayObject): - """JSON expects a JSON-able dict or list - - not an already-serialized JSON string. - - Scalar types (None, number, string) are not allowed, only dict or list containers. - """ - # wrap data in a property, which warns about passing already-serialized JSON - _data = None - def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs): - """Create a JSON display object given raw data. - - Parameters - ---------- - data : dict or list - JSON data to display. Not an already-serialized JSON string. - Scalar types (None, number, string) are not allowed, only dict - or list containers. - url : unicode - A URL to download the data from. - filename : unicode - Path to a local file to load the data from. - expanded : boolean - Metadata to control whether a JSON display component is expanded. - metadata: dict - Specify extra metadata to attach to the json display object. - root : str - The name of the root element of the JSON tree - """ - self.metadata = { - 'expanded': expanded, - 'root': root, - } - if metadata: - self.metadata.update(metadata) - if kwargs: - self.metadata.update(kwargs) - super(JSON, self).__init__(data=data, url=url, filename=filename) - - def _check_data(self): - if self.data is not None and not isinstance(self.data, (dict, list)): - raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) - - @property - def data(self): - return self._data - - @data.setter - def data(self, data): - if isinstance(data, str): - if getattr(self, 'filename', None) is None: - warnings.warn("JSON expects JSONable dict or list, not JSON strings") - data = json.loads(data) - self._data = data - - def _data_and_metadata(self): - return self.data, self.metadata - - def _repr_json_(self): - return self._data_and_metadata() - -_css_t = """var link = document.createElement("link"); - link.ref = "stylesheet"; - link.type = "text/css"; - link.href = "%s"; - document.head.appendChild(link); -""" - -_lib_t1 = """new Promise(function(resolve, reject) { - var script = document.createElement("script"); - script.onload = resolve; - script.onerror = reject; - script.src = "%s"; - document.head.appendChild(script); -}).then(() => { -""" - -_lib_t2 = """ -});""" - -class GeoJSON(JSON): - """GeoJSON expects JSON-able dict - - not an already-serialized JSON string. - - Scalar types (None, number, string) are not allowed, only dict containers. - """ - - def __init__(self, *args, **kwargs): - """Create a GeoJSON display object given raw data. - - Parameters - ---------- - data : dict or list - VegaLite data. Not an already-serialized JSON string. - Scalar types (None, number, string) are not allowed, only dict - or list containers. - url_template : string - Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template - layer_options : dict - Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options - url : unicode - A URL to download the data from. - filename : unicode - Path to a local file to load the data from. - metadata: dict - Specify extra metadata to attach to the json display object. - - Examples - -------- - - The following will display an interactive map of Mars with a point of - interest on frontend that do support GeoJSON display. - - >>> from IPython.display import GeoJSON - - >>> GeoJSON(data={ - ... "type": "Feature", - ... "geometry": { - ... "type": "Point", - ... "coordinates": [-81.327, 296.038] - ... } - ... }, - ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", - ... layer_options={ - ... "basemap_id": "celestia_mars-shaded-16k_global", - ... "attribution" : "Celestia/praesepe", - ... "minZoom" : 0, - ... "maxZoom" : 18, - ... }) - <IPython.core.display.GeoJSON object> - - In the terminal IPython, you will only see the text representation of - the GeoJSON object. - - """ - - super(GeoJSON, self).__init__(*args, **kwargs) - - - def _ipython_display_(self): - bundle = { - 'application/geo+json': self.data, - 'text/plain': '<IPython.display.GeoJSON object>' - } - metadata = { - 'application/geo+json': self.metadata - } - display(bundle, metadata=metadata, raw=True) - -class Javascript(TextDisplayObject): - - def __init__(self, data=None, url=None, filename=None, lib=None, css=None): - """Create a Javascript display object given raw data. - - When this object is returned by an expression or passed to the - display function, it will result in the data being displayed - in the frontend. If the data is a URL, the data will first be - downloaded and then displayed. - - In the Notebook, the containing element will be available as `element`, - and jQuery will be available. Content appended to `element` will be - visible in the output area. - - Parameters - ---------- - data : unicode, str or bytes - The Javascript source code or a URL to download it from. - url : unicode - A URL to download the data from. - filename : unicode - Path to a local file to load the data from. - lib : list or str - A sequence of Javascript library URLs to load asynchronously before - running the source code. The full URLs of the libraries should - be given. A single Javascript library URL can also be given as a - string. - css: : list or str - A sequence of css files to load before running the source code. - The full URLs of the css files should be given. A single css URL - can also be given as a string. - """ - if isinstance(lib, str): - lib = [lib] - elif lib is None: - lib = [] - if isinstance(css, str): - css = [css] - elif css is None: - css = [] - if not isinstance(lib, (list,tuple)): - raise TypeError('expected sequence, got: %r' % lib) - if not isinstance(css, (list,tuple)): - raise TypeError('expected sequence, got: %r' % css) - self.lib = lib - self.css = css - super(Javascript, self).__init__(data=data, url=url, filename=filename) - - def _repr_javascript_(self): - r = '' - for c in self.css: - r += _css_t % c - for l in self.lib: - r += _lib_t1 % l - r += self.data - r += _lib_t2*len(self.lib) - return r - -# constants for identifying png/jpeg data -_PNG = b'\x89PNG\r\n\x1a\n' -_JPEG = b'\xff\xd8' - -def _pngxy(data): - """read the (width, height) from a PNG header""" - ihdr = data.index(b'IHDR') - # next 8 bytes are width/height - return struct.unpack('>ii', data[ihdr+4:ihdr+12]) - -def _jpegxy(data): - """read the (width, height) from a JPEG header""" - # adapted from http://www.64lines.com/jpeg-width-height - - idx = 4 - while True: - block_size = struct.unpack('>H', data[idx:idx+2])[0] - idx = idx + block_size - if data[idx:idx+2] == b'\xFF\xC0': - # found Start of Frame - iSOF = idx - break - else: - # read another block - idx += 2 - - h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) - return w, h - -def _gifxy(data): - """read the (width, height) from a GIF header""" - return struct.unpack('<HH', data[6:10]) - - -class Image(DisplayObject): - - _read_flags = 'rb' - _FMT_JPEG = u'jpeg' - _FMT_PNG = u'png' - _FMT_GIF = u'gif' - _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF] - _MIMETYPES = { - _FMT_PNG: 'image/png', - _FMT_JPEG: 'image/jpeg', - _FMT_GIF: 'image/gif', - } - - def __init__(self, data=None, url=None, filename=None, format=None, - embed=None, width=None, height=None, retina=False, - unconfined=False, metadata=None): - """Create a PNG/JPEG/GIF image object given raw data. - - When this object is returned by an input cell or passed to the - display function, it will result in the image being displayed - in the frontend. - - Parameters - ---------- - data : unicode, str or bytes - The raw image data or a URL or filename to load the data from. - This always results in embedded image data. - url : unicode - A URL to download the data from. If you specify `url=`, - the image data will not be embedded unless you also specify `embed=True`. - filename : unicode - Path to a local file to load the data from. - Images from a file are always embedded. - format : unicode - The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given - for format will be inferred from the filename extension. - embed : bool - Should the image data be embedded using a data URI (True) or be - loaded using an <img> tag. Set this to True if you want the image - to be viewable later with no internet connection in the notebook. - - Default is `True`, unless the keyword argument `url` is set, then - default value is `False`. - - Note that QtConsole is not able to display images if `embed` is set to `False` - width : int - Width in pixels to which to constrain the image in html - height : int - Height in pixels to which to constrain the image in html - retina : bool - Automatically set the width and height to half of the measured - width and height. - This only works for embedded images because it reads the width/height - from image data. - For non-embedded images, you can just set the desired display width - and height directly. - unconfined: bool - Set unconfined=True to disable max-width confinement of the image. - metadata: dict - Specify extra metadata to attach to the image. - - Examples - -------- - # embedded image data, works in qtconsole and notebook - # when passed positionally, the first arg can be any of raw image data, - # a URL, or a filename from which to load image data. - # The result is always embedding image data for inline images. - Image('http://www.google.fr/images/srpr/logo3w.png') - Image('/path/to/image.jpg') - Image(b'RAW_PNG_DATA...') - - # Specifying Image(url=...) does not embed the image data, - # it only generates `<img>` tag with a link to the source. - # This will not work in the qtconsole or offline. - Image(url='http://www.google.fr/images/srpr/logo3w.png') - - """ - if filename is not None: - ext = self._find_ext(filename) - elif url is not None: - ext = self._find_ext(url) - elif data is None: - raise ValueError("No image data found. Expecting filename, url, or data.") - elif isinstance(data, str) and ( - data.startswith('http') or _safe_exists(data) - ): - ext = self._find_ext(data) - else: - ext = None - - if format is None: - if ext is not None: - if ext == u'jpg' or ext == u'jpeg': - format = self._FMT_JPEG - elif ext == u'png': - format = self._FMT_PNG - elif ext == u'gif': - format = self._FMT_GIF - else: - format = ext.lower() - elif isinstance(data, bytes): - # infer image type from image data header, - # only if format has not been specified. - if data[:2] == _JPEG: - format = self._FMT_JPEG - - # failed to detect format, default png - if format is None: - format = self._FMT_PNG - - if format.lower() == 'jpg': - # jpg->jpeg - format = self._FMT_JPEG - - self.format = format.lower() - self.embed = embed if embed is not None else (url is None) - - if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: - raise ValueError("Cannot embed the '%s' image format" % (self.format)) - if self.embed: - self._mimetype = self._MIMETYPES.get(self.format) - - self.width = width - self.height = height - self.retina = retina - self.unconfined = unconfined - super(Image, self).__init__(data=data, url=url, filename=filename, - metadata=metadata) - - if self.width is None and self.metadata.get('width', {}): - self.width = metadata['width'] - - if self.height is None and self.metadata.get('height', {}): - self.height = metadata['height'] - - if retina: - self._retina_shape() - - - def _retina_shape(self): - """load pixel-doubled width and height from image data""" - if not self.embed: - return - if self.format == self._FMT_PNG: - w, h = _pngxy(self.data) - elif self.format == self._FMT_JPEG: - w, h = _jpegxy(self.data) - elif self.format == self._FMT_GIF: - w, h = _gifxy(self.data) - else: - # retina only supports png - return - self.width = w // 2 - self.height = h // 2 - - def reload(self): - """Reload the raw data from file or URL.""" - if self.embed: - super(Image,self).reload() - if self.retina: - self._retina_shape() - - def _repr_html_(self): - if not self.embed: - width = height = klass = '' - if self.width: - width = ' width="%d"' % self.width - if self.height: - height = ' height="%d"' % self.height - if self.unconfined: - klass = ' class="unconfined"' - return u'<img src="{url}"{width}{height}{klass}/>'.format( - url=self.url, - width=width, - height=height, - klass=klass, - ) - - def _repr_mimebundle_(self, include=None, exclude=None): - """Return the image as a mimebundle - - Any new mimetype support should be implemented here. - """ - if self.embed: - mimetype = self._mimetype - data, metadata = self._data_and_metadata(always_both=True) - if metadata: - metadata = {mimetype: metadata} - return {mimetype: data}, metadata - else: - return {'text/html': self._repr_html_()} - - def _data_and_metadata(self, always_both=False): - """shortcut for returning metadata with shape information, if defined""" - try: - b64_data = b2a_base64(self.data).decode('ascii') - except TypeError: - raise FileNotFoundError( - "No such file or directory: '%s'" % (self.data)) - md = {} - if self.metadata: - md.update(self.metadata) - if self.width: - md['width'] = self.width - if self.height: - md['height'] = self.height - if self.unconfined: - md['unconfined'] = self.unconfined - if md or always_both: - return b64_data, md - else: - return b64_data - - def _repr_png_(self): - if self.embed and self.format == self._FMT_PNG: - return self._data_and_metadata() - - def _repr_jpeg_(self): - if self.embed and self.format == self._FMT_JPEG: - return self._data_and_metadata() - - def _find_ext(self, s): - return s.split('.')[-1].lower() - - -class Video(DisplayObject): - - def __init__(self, data=None, url=None, filename=None, embed=False, - mimetype=None, width=None, height=None): - """Create a video object given raw data or an URL. - - When this object is returned by an input cell or passed to the - display function, it will result in the video being displayed - in the frontend. - - Parameters - ---------- - data : unicode, str or bytes - The raw video data or a URL or filename to load the data from. - Raw data will require passing `embed=True`. - url : unicode - A URL for the video. If you specify `url=`, - the image data will not be embedded. - filename : unicode - Path to a local file containing the video. - Will be interpreted as a local URL unless `embed=True`. - embed : bool - Should the video be embedded using a data URI (True) or be - loaded using a <video> tag (False). - - Since videos are large, embedding them should be avoided, if possible. - You must confirm embedding as your intention by passing `embed=True`. - - Local files can be displayed with URLs without embedding the content, via:: - - Video('./video.mp4') - - mimetype: unicode - Specify the mimetype for embedded videos. - Default will be guessed from file extension, if available. - width : int - Width in pixels to which to constrain the video in HTML. - If not supplied, defaults to the width of the video. - height : int - Height in pixels to which to constrain the video in html. - If not supplied, defaults to the height of the video. - - Examples - -------- - - Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') - Video('path/to/video.mp4') - Video('path/to/video.mp4', embed=True) - Video(b'raw-videodata', embed=True) - """ - if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): - url = data - data = None - elif os.path.exists(data): - filename = data - data = None - - if data and not embed: - msg = ''.join([ - "To embed videos, you must pass embed=True ", - "(this may make your notebook files huge)\n", - "Consider passing Video(url='...')", - ]) - raise ValueError(msg) - - self.mimetype = mimetype - self.embed = embed - self.width = width - self.height = height - super(Video, self).__init__(data=data, url=url, filename=filename) - - def _repr_html_(self): - width = height = '' - if self.width: - width = ' width="%d"' % self.width - if self.height: - height = ' height="%d"' % self.height - - # External URLs and potentially local files are not embedded into the - # notebook output. - if not self.embed: - url = self.url if self.url is not None else self.filename - output = """<video src="{0}" controls {1} {2}> - Your browser does not support the <code>video</code> element. - </video>""".format(url, width, height) - return output - - # Embedded videos are base64-encoded. - mimetype = self.mimetype - if self.filename is not None: - if not mimetype: - mimetype, _ = mimetypes.guess_type(self.filename) - - with open(self.filename, 'rb') as f: - video = f.read() - else: - video = self.data - if isinstance(video, str): - # unicode input is already b64-encoded - b64_video = video - else: - b64_video = b2a_base64(video).decode('ascii').rstrip() - - output = """<video controls {0} {1}> - <source src="data:{2};base64,{3}" type="{2}"> - Your browser does not support the video tag. - </video>""".format(width, height, mimetype, b64_video) - return output - - def reload(self): - # TODO - pass - - -def clear_output(wait=False): - """Clear the output of the current cell receiving output. - - Parameters - ---------- - wait : bool [default: false] - Wait to clear the output until new output is available to replace it.""" - from IPython.core.interactiveshell import InteractiveShell - if InteractiveShell.initialized(): - InteractiveShell.instance().display_pub.clear_output(wait) - else: - print('\033[2K\r', end='') - sys.stdout.flush() - print('\033[2K\r', end='') - sys.stderr.flush() - - -@skip_doctest -def set_matplotlib_formats(*formats, **kwargs): - """Select figure formats for the inline backend. Optionally pass quality for JPEG. - - For example, this enables PNG and JPEG output with a JPEG quality of 90%:: - - In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) - - To set this in your config files use the following:: - - c.InlineBackend.figure_formats = {'png', 'jpeg'} - c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) - - Parameters - ---------- - *formats : strs - One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. - **kwargs : - Keyword args will be relayed to ``figure.canvas.print_figure``. - """ - from IPython.core.interactiveshell import InteractiveShell - from IPython.core.pylabtools import select_figure_formats - # build kwargs, starting with InlineBackend config - kw = {} - from ipykernel.pylab.config import InlineBackend - cfg = InlineBackend.instance() - kw.update(cfg.print_figure_kwargs) - kw.update(**kwargs) - shell = InteractiveShell.instance() - select_figure_formats(shell, formats, **kw) - -@skip_doctest -def set_matplotlib_close(close=True): - """Set whether the inline backend closes all figures automatically or not. - - By default, the inline backend used in the IPython Notebook will close all - matplotlib figures automatically after each cell is run. This means that - plots in different cells won't interfere. Sometimes, you may want to make - a plot in one cell and then refine it in later cells. This can be accomplished - by:: - - In [1]: set_matplotlib_close(False) - - To set this in your config files use the following:: - - c.InlineBackend.close_figures = False - - Parameters - ---------- - close : bool - Should all matplotlib figures be automatically closed after each cell is - run? - """ - from ipykernel.pylab.config import InlineBackend - cfg = InlineBackend.instance() - cfg.close_figures = close -
    - -
    -
    -
    - - - - - -
    -
    -
    - - -
    - - - - - \ No newline at end of file diff --git a/_modules/anypytools/abcutils.html b/_modules/anypytools/abcutils.html index 1d806aa..fec0c40 100644 --- a/_modules/anypytools/abcutils.html +++ b/_modules/anypytools/abcutils.html @@ -6,7 +6,7 @@ - anypytools.abcutils — AnyPyTools 1.2.0 documentation + anypytools.abcutils — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -259,9 +259,9 @@

    Source code for anypytools.abcutils

             os.path.realpath(anybodycon_path),
             "--macro=",
             macro_file.name,
    -        "/ni",
             "/deb",
             str(debug_mode),
    +        "/ni",
         ]
         if sys.platform.startswith("win"):
             # Don't display the Windows GPF dialog if the invoked program dies.
    @@ -1127,7 +1127,7 @@ 

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -1136,7 +1136,7 @@

    Navigation

    diff --git a/_modules/anypytools/datautils.html b/_modules/anypytools/datautils.html index 6570ef7..fb3f405 100644 --- a/_modules/anypytools/datautils.html +++ b/_modules/anypytools/datautils.html @@ -6,7 +6,7 @@ - anypytools.datautils — AnyPyTools 1.2.0 documentation + anypytools.datautils — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -312,7 +312,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -321,7 +321,7 @@

    Navigation

    diff --git a/_modules/anypytools/h5py_wrapper.html b/_modules/anypytools/h5py_wrapper.html index b2119c1..a4d2399 100644 --- a/_modules/anypytools/h5py_wrapper.html +++ b/_modules/anypytools/h5py_wrapper.html @@ -6,7 +6,7 @@ - anypytools.h5py_wrapper — AnyPyTools 1.2.0 documentation + anypytools.h5py_wrapper — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -270,7 +270,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -279,7 +279,7 @@

    Navigation

    diff --git a/_modules/anypytools/macroutils.html b/_modules/anypytools/macroutils.html index 93627f4..190aedb 100644 --- a/_modules/anypytools/macroutils.html +++ b/_modules/anypytools/macroutils.html @@ -6,7 +6,7 @@ - anypytools.macroutils — AnyPyTools 1.2.0 documentation + anypytools.macroutils — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -1030,7 +1030,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -1039,7 +1039,7 @@

    Navigation

    diff --git a/_modules/anypytools/pytest_plugin.html b/_modules/anypytools/pytest_plugin.html index 50f0a65..041dd7b 100644 --- a/_modules/anypytools/pytest_plugin.html +++ b/_modules/anypytools/pytest_plugin.html @@ -6,7 +6,7 @@ - anypytools.pytest_plugin — AnyPyTools 1.2.0 documentation + anypytools.pytest_plugin — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -602,7 +602,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -611,7 +611,7 @@

    Navigation

    diff --git a/_modules/anypytools/tools.html b/_modules/anypytools/tools.html index a9e0054..464f7f2 100644 --- a/_modules/anypytools/tools.html +++ b/_modules/anypytools/tools.html @@ -6,7 +6,7 @@ - anypytools.tools — AnyPyTools 1.2.0 documentation + anypytools.tools — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -901,7 +901,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -910,7 +910,7 @@

    Navigation

    diff --git a/_modules/index.html b/_modules/index.html index 176d3e8..edc1b8d 100644 --- a/_modules/index.html +++ b/_modules/index.html @@ -6,7 +6,7 @@ - Overview: module code — AnyPyTools 1.2.0 documentation + Overview: module code — AnyPyTools 1.2.1 documentation @@ -37,7 +37,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -50,14 +50,12 @@

    Navigation

    All modules for which code is available

    -
    @@ -113,7 +111,7 @@

    Navigation

  • toc    
  • -
  • AnyPyTools 1.2.0 documentation »
  • +
  • AnyPyTools 1.2.1 documentation »
  • @@ -121,7 +119,7 @@

    Navigation

    diff --git a/_modules/logging.html b/_modules/logging.html deleted file mode 100644 index d4e04ef..0000000 --- a/_modules/logging.html +++ /dev/null @@ -1,2143 +0,0 @@ - - - - - - - - - logging — AnyPyTools 1.2.0 documentation - - - - - - - - - - - - - - - - -
    - - -
    - - -
    -
    -
    -
    - -

    Source code for logging

    -# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
    -#
    -# Permission to use, copy, modify, and distribute this software and its
    -# documentation for any purpose and without fee is hereby granted,
    -# provided that the above copyright notice appear in all copies and that
    -# both that copyright notice and this permission notice appear in
    -# supporting documentation, and that the name of Vinay Sajip
    -# not be used in advertising or publicity pertaining to distribution
    -# of the software without specific, written prior permission.
    -# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
    -# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
    -# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
    -# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
    -# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
    -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    -
    -"""
    -Logging package for Python. Based on PEP 282 and comments thereto in
    -comp.lang.python.
    -
    -Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
    -
    -To use, simply 'import logging' and log away!
    -"""
    -
    -import sys, os, time, io, traceback, warnings, weakref, collections
    -
    -from string import Template
    -
    -__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
    -           'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
    -           'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
    -           'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
    -           'captureWarnings', 'critical', 'debug', 'disable', 'error',
    -           'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
    -           'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
    -           'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
    -           'lastResort', 'raiseExceptions']
    -
    -try:
    -    import threading
    -except ImportError: #pragma: no cover
    -    threading = None
    -
    -__author__  = "Vinay Sajip <vinay_sajip@red-dove.com>"
    -__status__  = "production"
    -# The following module attributes are no longer updated.
    -__version__ = "0.5.1.2"
    -__date__    = "07 February 2010"
    -
    -#---------------------------------------------------------------------------
    -#   Miscellaneous module data
    -#---------------------------------------------------------------------------
    -
    -#
    -#_startTime is used as the base when calculating the relative time of events
    -#
    -_startTime = time.time()
    -
    -#
    -#raiseExceptions is used to see if exceptions during handling should be
    -#propagated
    -#
    -raiseExceptions = True
    -
    -#
    -# If you don't want threading information in the log, set this to zero
    -#
    -logThreads = True
    -
    -#
    -# If you don't want multiprocessing information in the log, set this to zero
    -#
    -logMultiprocessing = True
    -
    -#
    -# If you don't want process information in the log, set this to zero
    -#
    -logProcesses = True
    -
    -#---------------------------------------------------------------------------
    -#   Level related stuff
    -#---------------------------------------------------------------------------
    -#
    -# Default levels and level names, these can be replaced with any positive set
    -# of values having corresponding names. There is a pseudo-level, NOTSET, which
    -# is only really there as a lower limit for user-defined levels. Handlers and
    -# loggers are initialized with NOTSET so that they will log all messages, even
    -# at user-defined levels.
    -#
    -
    -CRITICAL = 50
    -FATAL = CRITICAL
    -ERROR = 40
    -WARNING = 30
    -WARN = WARNING
    -INFO = 20
    -DEBUG = 10
    -NOTSET = 0
    -
    -_levelToName = {
    -    CRITICAL: 'CRITICAL',
    -    ERROR: 'ERROR',
    -    WARNING: 'WARNING',
    -    INFO: 'INFO',
    -    DEBUG: 'DEBUG',
    -    NOTSET: 'NOTSET',
    -}
    -_nameToLevel = {
    -    'CRITICAL': CRITICAL,
    -    'FATAL': FATAL,
    -    'ERROR': ERROR,
    -    'WARN': WARNING,
    -    'WARNING': WARNING,
    -    'INFO': INFO,
    -    'DEBUG': DEBUG,
    -    'NOTSET': NOTSET,
    -}
    -
    -def getLevelName(level):
    -    """
    -    Return the textual representation of logging level 'level'.
    -
    -    If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
    -    INFO, DEBUG) then you get the corresponding string. If you have
    -    associated levels with names using addLevelName then the name you have
    -    associated with 'level' is returned.
    -
    -    If a numeric value corresponding to one of the defined levels is passed
    -    in, the corresponding string representation is returned.
    -
    -    Otherwise, the string "Level %s" % level is returned.
    -    """
    -    # See Issues #22386, #27937 and #29220 for why it's this way
    -    result = _levelToName.get(level)
    -    if result is not None:
    -        return result
    -    result = _nameToLevel.get(level)
    -    if result is not None:
    -        return result
    -    return "Level %s" % level
    -
    -def addLevelName(level, levelName):
    -    """
    -    Associate 'levelName' with 'level'.
    -
    -    This is used when converting levels to text during message formatting.
    -    """
    -    _acquireLock()
    -    try:    #unlikely to cause an exception, but you never know...
    -        _levelToName[level] = levelName
    -        _nameToLevel[levelName] = level
    -    finally:
    -        _releaseLock()
    -
    -if hasattr(sys, '_getframe'):
    -    currentframe = lambda: sys._getframe(3)
    -else: #pragma: no cover
    -    def currentframe():
    -        """Return the frame object for the caller's stack frame."""
    -        try:
    -            raise Exception
    -        except Exception:
    -            return sys.exc_info()[2].tb_frame.f_back
    -
    -#
    -# _srcfile is used when walking the stack to check when we've got the first
    -# caller stack frame, by skipping frames whose filename is that of this
    -# module's source. It therefore should contain the filename of this module's
    -# source file.
    -#
    -# Ordinarily we would use __file__ for this, but frozen modules don't always
    -# have __file__ set, for some reason (see Issue #21736). Thus, we get the
    -# filename from a handy code object from a function defined in this module.
    -# (There's no particular reason for picking addLevelName.)
    -#
    -
    -_srcfile = os.path.normcase(addLevelName.__code__.co_filename)
    -
    -# _srcfile is only used in conjunction with sys._getframe().
    -# To provide compatibility with older versions of Python, set _srcfile
    -# to None if _getframe() is not available; this value will prevent
    -# findCaller() from being called. You can also do this if you want to avoid
    -# the overhead of fetching caller information, even when _getframe() is
    -# available.
    -#if not hasattr(sys, '_getframe'):
    -#    _srcfile = None
    -
    -
    -def _checkLevel(level):
    -    if isinstance(level, int):
    -        rv = level
    -    elif str(level) == level:
    -        if level not in _nameToLevel:
    -            raise ValueError("Unknown level: %r" % level)
    -        rv = _nameToLevel[level]
    -    else:
    -        raise TypeError("Level not an integer or a valid string: %r" % level)
    -    return rv
    -
    -#---------------------------------------------------------------------------
    -#   Thread-related stuff
    -#---------------------------------------------------------------------------
    -
    -#
    -#_lock is used to serialize access to shared data structures in this module.
    -#This needs to be an RLock because fileConfig() creates and configures
    -#Handlers, and so might arbitrary user threads. Since Handler code updates the
    -#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
    -#the lock would already have been acquired - so we need an RLock.
    -#The same argument applies to Loggers and Manager.loggerDict.
    -#
    -if threading:
    -    _lock = threading.RLock()
    -else: #pragma: no cover
    -    _lock = None
    -
    -
    -def _acquireLock():
    -    """
    -    Acquire the module-level lock for serializing access to shared data.
    -
    -    This should be released with _releaseLock().
    -    """
    -    if _lock:
    -        _lock.acquire()
    -
    -def _releaseLock():
    -    """
    -    Release the module-level lock acquired by calling _acquireLock().
    -    """
    -    if _lock:
    -        _lock.release()
    -
    -#---------------------------------------------------------------------------
    -#   The logging record
    -#---------------------------------------------------------------------------
    -
    -class LogRecord(object):
    -    """
    -    A LogRecord instance represents an event being logged.
    -
    -    LogRecord instances are created every time something is logged. They
    -    contain all the information pertinent to the event being logged. The
    -    main information passed in is in msg and args, which are combined
    -    using str(msg) % args to create the message field of the record. The
    -    record also includes information such as when the record was created,
    -    the source line where the logging call was made, and any exception
    -    information to be logged.
    -    """
    -    def __init__(self, name, level, pathname, lineno,
    -                 msg, args, exc_info, func=None, sinfo=None, **kwargs):
    -        """
    -        Initialize a logging record with interesting information.
    -        """
    -        ct = time.time()
    -        self.name = name
    -        self.msg = msg
    -        #
    -        # The following statement allows passing of a dictionary as a sole
    -        # argument, so that you can do something like
    -        #  logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
    -        # Suggested by Stefan Behnel.
    -        # Note that without the test for args[0], we get a problem because
    -        # during formatting, we test to see if the arg is present using
    -        # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
    -        # and if the passed arg fails 'if self.args:' then no formatting
    -        # is done. For example, logger.warning('Value is %d', 0) would log
    -        # 'Value is %d' instead of 'Value is 0'.
    -        # For the use case of passing a dictionary, this should not be a
    -        # problem.
    -        # Issue #21172: a request was made to relax the isinstance check
    -        # to hasattr(args[0], '__getitem__'). However, the docs on string
    -        # formatting still seem to suggest a mapping object is required.
    -        # Thus, while not removing the isinstance check, it does now look
    -        # for collections.Mapping rather than, as before, dict.
    -        if (args and len(args) == 1 and isinstance(args[0], collections.Mapping)
    -            and args[0]):
    -            args = args[0]
    -        self.args = args
    -        self.levelname = getLevelName(level)
    -        self.levelno = level
    -        self.pathname = pathname
    -        try:
    -            self.filename = os.path.basename(pathname)
    -            self.module = os.path.splitext(self.filename)[0]
    -        except (TypeError, ValueError, AttributeError):
    -            self.filename = pathname
    -            self.module = "Unknown module"
    -        self.exc_info = exc_info
    -        self.exc_text = None      # used to cache the traceback text
    -        self.stack_info = sinfo
    -        self.lineno = lineno
    -        self.funcName = func
    -        self.created = ct
    -        self.msecs = (ct - int(ct)) * 1000
    -        self.relativeCreated = (self.created - _startTime) * 1000
    -        if logThreads and threading:
    -            self.thread = threading.get_ident()
    -            self.threadName = threading.current_thread().name
    -        else: # pragma: no cover
    -            self.thread = None
    -            self.threadName = None
    -        if not logMultiprocessing: # pragma: no cover
    -            self.processName = None
    -        else:
    -            self.processName = 'MainProcess'
    -            mp = sys.modules.get('multiprocessing')
    -            if mp is not None:
    -                # Errors may occur if multiprocessing has not finished loading
    -                # yet - e.g. if a custom import hook causes third-party code
    -                # to run when multiprocessing calls import. See issue 8200
    -                # for an example
    -                try:
    -                    self.processName = mp.current_process().name
    -                except Exception: #pragma: no cover
    -                    pass
    -        if logProcesses and hasattr(os, 'getpid'):
    -            self.process = os.getpid()
    -        else:
    -            self.process = None
    -
    -    def __str__(self):
    -        return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
    -            self.pathname, self.lineno, self.msg)
    -
    -    __repr__ = __str__
    -
    -    def getMessage(self):
    -        """
    -        Return the message for this LogRecord.
    -
    -        Return the message for this LogRecord after merging any user-supplied
    -        arguments with the message.
    -        """
    -        msg = str(self.msg)
    -        if self.args:
    -            msg = msg % self.args
    -        return msg
    -
    -#
    -#   Determine which class to use when instantiating log records.
    -#
    -_logRecordFactory = LogRecord
    -
    -def setLogRecordFactory(factory):
    -    """
    -    Set the factory to be used when instantiating a log record.
    -
    -    :param factory: A callable which will be called to instantiate
    -    a log record.
    -    """
    -    global _logRecordFactory
    -    _logRecordFactory = factory
    -
    -def getLogRecordFactory():
    -    """
    -    Return the factory to be used when instantiating a log record.
    -    """
    -
    -    return _logRecordFactory
    -
    -def makeLogRecord(dict):
    -    """
    -    Make a LogRecord whose attributes are defined by the specified dictionary,
    -    This function is useful for converting a logging event received over
    -    a socket connection (which is sent as a dictionary) into a LogRecord
    -    instance.
    -    """
    -    rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
    -    rv.__dict__.update(dict)
    -    return rv
    -
    -#---------------------------------------------------------------------------
    -#   Formatter classes and functions
    -#---------------------------------------------------------------------------
    -
    -class PercentStyle(object):
    -
    -    default_format = '%(message)s'
    -    asctime_format = '%(asctime)s'
    -    asctime_search = '%(asctime)'
    -
    -    def __init__(self, fmt):
    -        self._fmt = fmt or self.default_format
    -
    -    def usesTime(self):
    -        return self._fmt.find(self.asctime_search) >= 0
    -
    -    def format(self, record):
    -        return self._fmt % record.__dict__
    -
    -class StrFormatStyle(PercentStyle):
    -    default_format = '{message}'
    -    asctime_format = '{asctime}'
    -    asctime_search = '{asctime'
    -
    -    def format(self, record):
    -        return self._fmt.format(**record.__dict__)
    -
    -
    -class StringTemplateStyle(PercentStyle):
    -    default_format = '${message}'
    -    asctime_format = '${asctime}'
    -    asctime_search = '${asctime}'
    -
    -    def __init__(self, fmt):
    -        self._fmt = fmt or self.default_format
    -        self._tpl = Template(self._fmt)
    -
    -    def usesTime(self):
    -        fmt = self._fmt
    -        return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0
    -
    -    def format(self, record):
    -        return self._tpl.substitute(**record.__dict__)
    -
    -BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
    -
    -_STYLES = {
    -    '%': (PercentStyle, BASIC_FORMAT),
    -    '{': (StrFormatStyle, '{levelname}:{name}:{message}'),
    -    '$': (StringTemplateStyle, '${levelname}:${name}:${message}'),
    -}
    -
    -class Formatter(object):
    -    """
    -    Formatter instances are used to convert a LogRecord to text.
    -
    -    Formatters need to know how a LogRecord is constructed. They are
    -    responsible for converting a LogRecord to (usually) a string which can
    -    be interpreted by either a human or an external system. The base Formatter
    -    allows a formatting string to be specified. If none is supplied, the
    -    the style-dependent default value, "%(message)s", "{message}", or
    -    "${message}", is used.
    -
    -    The Formatter can be initialized with a format string which makes use of
    -    knowledge of the LogRecord attributes - e.g. the default value mentioned
    -    above makes use of the fact that the user's message and arguments are pre-
    -    formatted into a LogRecord's message attribute. Currently, the useful
    -    attributes in a LogRecord are described by:
    -
    -    %(name)s            Name of the logger (logging channel)
    -    %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
    -                        WARNING, ERROR, CRITICAL)
    -    %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
    -                        "WARNING", "ERROR", "CRITICAL")
    -    %(pathname)s        Full pathname of the source file where the logging
    -                        call was issued (if available)
    -    %(filename)s        Filename portion of pathname
    -    %(module)s          Module (name portion of filename)
    -    %(lineno)d          Source line number where the logging call was issued
    -                        (if available)
    -    %(funcName)s        Function name
    -    %(created)f         Time when the LogRecord was created (time.time()
    -                        return value)
    -    %(asctime)s         Textual time when the LogRecord was created
    -    %(msecs)d           Millisecond portion of the creation time
    -    %(relativeCreated)d Time in milliseconds when the LogRecord was created,
    -                        relative to the time the logging module was loaded
    -                        (typically at application startup time)
    -    %(thread)d          Thread ID (if available)
    -    %(threadName)s      Thread name (if available)
    -    %(process)d         Process ID (if available)
    -    %(message)s         The result of record.getMessage(), computed just as
    -                        the record is emitted
    -    """
    -
    -    converter = time.localtime
    -
    -    def __init__(self, fmt=None, datefmt=None, style='%'):
    -        """
    -        Initialize the formatter with specified format strings.
    -
    -        Initialize the formatter either with the specified format string, or a
    -        default as described above. Allow for specialized date formatting with
    -        the optional datefmt argument. If datefmt is omitted, you get an
    -        ISO8601-like (or RFC 3339-like) format.
    -
    -        Use a style parameter of '%', '{' or '$' to specify that you want to
    -        use one of %-formatting, :meth:`str.format` (``{}``) formatting or
    -        :class:`string.Template` formatting in your format string.
    -
    -        .. versionchanged:: 3.2
    -           Added the ``style`` parameter.
    -        """
    -        if style not in _STYLES:
    -            raise ValueError('Style must be one of: %s' % ','.join(
    -                             _STYLES.keys()))
    -        self._style = _STYLES[style][0](fmt)
    -        self._fmt = self._style._fmt
    -        self.datefmt = datefmt
    -
    -    default_time_format = '%Y-%m-%d %H:%M:%S'
    -    default_msec_format = '%s,%03d'
    -
    -    def formatTime(self, record, datefmt=None):
    -        """
    -        Return the creation time of the specified LogRecord as formatted text.
    -
    -        This method should be called from format() by a formatter which
    -        wants to make use of a formatted time. This method can be overridden
    -        in formatters to provide for any specific requirement, but the
    -        basic behaviour is as follows: if datefmt (a string) is specified,
    -        it is used with time.strftime() to format the creation time of the
    -        record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used.
    -        The resulting string is returned. This function uses a user-configurable
    -        function to convert the creation time to a tuple. By default,
    -        time.localtime() is used; to change this for a particular formatter
    -        instance, set the 'converter' attribute to a function with the same
    -        signature as time.localtime() or time.gmtime(). To change it for all
    -        formatters, for example if you want all logging times to be shown in GMT,
    -        set the 'converter' attribute in the Formatter class.
    -        """
    -        ct = self.converter(record.created)
    -        if datefmt:
    -            s = time.strftime(datefmt, ct)
    -        else:
    -            t = time.strftime(self.default_time_format, ct)
    -            s = self.default_msec_format % (t, record.msecs)
    -        return s
    -
    -    def formatException(self, ei):
    -        """
    -        Format and return the specified exception information as a string.
    -
    -        This default implementation just uses
    -        traceback.print_exception()
    -        """
    -        sio = io.StringIO()
    -        tb = ei[2]
    -        # See issues #9427, #1553375. Commented out for now.
    -        #if getattr(self, 'fullstack', False):
    -        #    traceback.print_stack(tb.tb_frame.f_back, file=sio)
    -        traceback.print_exception(ei[0], ei[1], tb, None, sio)
    -        s = sio.getvalue()
    -        sio.close()
    -        if s[-1:] == "\n":
    -            s = s[:-1]
    -        return s
    -
    -    def usesTime(self):
    -        """
    -        Check if the format uses the creation time of the record.
    -        """
    -        return self._style.usesTime()
    -
    -    def formatMessage(self, record):
    -        return self._style.format(record)
    -
    -    def formatStack(self, stack_info):
    -        """
    -        This method is provided as an extension point for specialized
    -        formatting of stack information.
    -
    -        The input data is a string as returned from a call to
    -        :func:`traceback.print_stack`, but with the last trailing newline
    -        removed.
    -
    -        The base implementation just returns the value passed in.
    -        """
    -        return stack_info
    -
    -    def format(self, record):
    -        """
    -        Format the specified record as text.
    -
    -        The record's attribute dictionary is used as the operand to a
    -        string formatting operation which yields the returned string.
    -        Before formatting the dictionary, a couple of preparatory steps
    -        are carried out. The message attribute of the record is computed
    -        using LogRecord.getMessage(). If the formatting string uses the
    -        time (as determined by a call to usesTime(), formatTime() is
    -        called to format the event time. If there is exception information,
    -        it is formatted using formatException() and appended to the message.
    -        """
    -        record.message = record.getMessage()
    -        if self.usesTime():
    -            record.asctime = self.formatTime(record, self.datefmt)
    -        s = self.formatMessage(record)
    -        if record.exc_info:
    -            # Cache the traceback text to avoid converting it multiple times
    -            # (it's constant anyway)
    -            if not record.exc_text:
    -                record.exc_text = self.formatException(record.exc_info)
    -        if record.exc_text:
    -            if s[-1:] != "\n":
    -                s = s + "\n"
    -            s = s + record.exc_text
    -        if record.stack_info:
    -            if s[-1:] != "\n":
    -                s = s + "\n"
    -            s = s + self.formatStack(record.stack_info)
    -        return s
    -
    -#
    -#   The default formatter to use when no other is specified
    -#
    -_defaultFormatter = Formatter()
    -
    -class BufferingFormatter(object):
    -    """
    -    A formatter suitable for formatting a number of records.
    -    """
    -    def __init__(self, linefmt=None):
    -        """
    -        Optionally specify a formatter which will be used to format each
    -        individual record.
    -        """
    -        if linefmt:
    -            self.linefmt = linefmt
    -        else:
    -            self.linefmt = _defaultFormatter
    -
    -    def formatHeader(self, records):
    -        """
    -        Return the header string for the specified records.
    -        """
    -        return ""
    -
    -    def formatFooter(self, records):
    -        """
    -        Return the footer string for the specified records.
    -        """
    -        return ""
    -
    -    def format(self, records):
    -        """
    -        Format the specified records and return the result as a string.
    -        """
    -        rv = ""
    -        if len(records) > 0:
    -            rv = rv + self.formatHeader(records)
    -            for record in records:
    -                rv = rv + self.linefmt.format(record)
    -            rv = rv + self.formatFooter(records)
    -        return rv
    -
    -#---------------------------------------------------------------------------
    -#   Filter classes and functions
    -#---------------------------------------------------------------------------
    -
    -class Filter(object):
    -    """
    -    Filter instances are used to perform arbitrary filtering of LogRecords.
    -
    -    Loggers and Handlers can optionally use Filter instances to filter
    -    records as desired. The base filter class only allows events which are
    -    below a certain point in the logger hierarchy. For example, a filter
    -    initialized with "A.B" will allow events logged by loggers "A.B",
    -    "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
    -    initialized with the empty string, all events are passed.
    -    """
    -    def __init__(self, name=''):
    -        """
    -        Initialize a filter.
    -
    -        Initialize with the name of the logger which, together with its
    -        children, will have its events allowed through the filter. If no
    -        name is specified, allow every event.
    -        """
    -        self.name = name
    -        self.nlen = len(name)
    -
    -    def filter(self, record):
    -        """
    -        Determine if the specified record is to be logged.
    -
    -        Is the specified record to be logged? Returns 0 for no, nonzero for
    -        yes. If deemed appropriate, the record may be modified in-place.
    -        """
    -        if self.nlen == 0:
    -            return True
    -        elif self.name == record.name:
    -            return True
    -        elif record.name.find(self.name, 0, self.nlen) != 0:
    -            return False
    -        return (record.name[self.nlen] == ".")
    -
    -class Filterer(object):
    -    """
    -    A base class for loggers and handlers which allows them to share
    -    common code.
    -    """
    -    def __init__(self):
    -        """
    -        Initialize the list of filters to be an empty list.
    -        """
    -        self.filters = []
    -
    -    def addFilter(self, filter):
    -        """
    -        Add the specified filter to this handler.
    -        """
    -        if not (filter in self.filters):
    -            self.filters.append(filter)
    -
    -    def removeFilter(self, filter):
    -        """
    -        Remove the specified filter from this handler.
    -        """
    -        if filter in self.filters:
    -            self.filters.remove(filter)
    -
    -    def filter(self, record):
    -        """
    -        Determine if a record is loggable by consulting all the filters.
    -
    -        The default is to allow the record to be logged; any filter can veto
    -        this and the record is then dropped. Returns a zero value if a record
    -        is to be dropped, else non-zero.
    -
    -        .. versionchanged:: 3.2
    -
    -           Allow filters to be just callables.
    -        """
    -        rv = True
    -        for f in self.filters:
    -            if hasattr(f, 'filter'):
    -                result = f.filter(record)
    -            else:
    -                result = f(record) # assume callable - will raise if not
    -            if not result:
    -                rv = False
    -                break
    -        return rv
    -
    -#---------------------------------------------------------------------------
    -#   Handler classes and functions
    -#---------------------------------------------------------------------------
    -
    -_handlers = weakref.WeakValueDictionary()  #map of handler names to handlers
    -_handlerList = [] # added to allow handlers to be removed in reverse of order initialized
    -
    -def _removeHandlerRef(wr):
    -    """
    -    Remove a handler reference from the internal cleanup list.
    -    """
    -    # This function can be called during module teardown, when globals are
    -    # set to None. It can also be called from another thread. So we need to
    -    # pre-emptively grab the necessary globals and check if they're None,
    -    # to prevent race conditions and failures during interpreter shutdown.
    -    acquire, release, handlers = _acquireLock, _releaseLock, _handlerList
    -    if acquire and release and handlers:
    -        acquire()
    -        try:
    -            if wr in handlers:
    -                handlers.remove(wr)
    -        finally:
    -            release()
    -
    -def _addHandlerRef(handler):
    -    """
    -    Add a handler to the internal cleanup list using a weak reference.
    -    """
    -    _acquireLock()
    -    try:
    -        _handlerList.append(weakref.ref(handler, _removeHandlerRef))
    -    finally:
    -        _releaseLock()
    -
    -class Handler(Filterer):
    -    """
    -    Handler instances dispatch logging events to specific destinations.
    -
    -    The base handler class. Acts as a placeholder which defines the Handler
    -    interface. Handlers can optionally use Formatter instances to format
    -    records as desired. By default, no formatter is specified; in this case,
    -    the 'raw' message as determined by record.message is logged.
    -    """
    -    def __init__(self, level=NOTSET):
    -        """
    -        Initializes the instance - basically setting the formatter to None
    -        and the filter list to empty.
    -        """
    -        Filterer.__init__(self)
    -        self._name = None
    -        self.level = _checkLevel(level)
    -        self.formatter = None
    -        # Add the handler to the global _handlerList (for cleanup on shutdown)
    -        _addHandlerRef(self)
    -        self.createLock()
    -
    -    def get_name(self):
    -        return self._name
    -
    -    def set_name(self, name):
    -        _acquireLock()
    -        try:
    -            if self._name in _handlers:
    -                del _handlers[self._name]
    -            self._name = name
    -            if name:
    -                _handlers[name] = self
    -        finally:
    -            _releaseLock()
    -
    -    name = property(get_name, set_name)
    -
    -    def createLock(self):
    -        """
    -        Acquire a thread lock for serializing access to the underlying I/O.
    -        """
    -        if threading:
    -            self.lock = threading.RLock()
    -        else: #pragma: no cover
    -            self.lock = None
    -
    -    def acquire(self):
    -        """
    -        Acquire the I/O thread lock.
    -        """
    -        if self.lock:
    -            self.lock.acquire()
    -
    -    def release(self):
    -        """
    -        Release the I/O thread lock.
    -        """
    -        if self.lock:
    -            self.lock.release()
    -
    -    def setLevel(self, level):
    -        """
    -        Set the logging level of this handler.  level must be an int or a str.
    -        """
    -        self.level = _checkLevel(level)
    -
    -    def format(self, record):
    -        """
    -        Format the specified record.
    -
    -        If a formatter is set, use it. Otherwise, use the default formatter
    -        for the module.
    -        """
    -        if self.formatter:
    -            fmt = self.formatter
    -        else:
    -            fmt = _defaultFormatter
    -        return fmt.format(record)
    -
    -    def emit(self, record):
    -        """
    -        Do whatever it takes to actually log the specified logging record.
    -
    -        This version is intended to be implemented by subclasses and so
    -        raises a NotImplementedError.
    -        """
    -        raise NotImplementedError('emit must be implemented '
    -                                  'by Handler subclasses')
    -
    -    def handle(self, record):
    -        """
    -        Conditionally emit the specified logging record.
    -
    -        Emission depends on filters which may have been added to the handler.
    -        Wrap the actual emission of the record with acquisition/release of
    -        the I/O thread lock. Returns whether the filter passed the record for
    -        emission.
    -        """
    -        rv = self.filter(record)
    -        if rv:
    -            self.acquire()
    -            try:
    -                self.emit(record)
    -            finally:
    -                self.release()
    -        return rv
    -
    -    def setFormatter(self, fmt):
    -        """
    -        Set the formatter for this handler.
    -        """
    -        self.formatter = fmt
    -
    -    def flush(self):
    -        """
    -        Ensure all logging output has been flushed.
    -
    -        This version does nothing and is intended to be implemented by
    -        subclasses.
    -        """
    -        pass
    -
    -    def close(self):
    -        """
    -        Tidy up any resources used by the handler.
    -
    -        This version removes the handler from an internal map of handlers,
    -        _handlers, which is used for handler lookup by name. Subclasses
    -        should ensure that this gets called from overridden close()
    -        methods.
    -        """
    -        #get the module data lock, as we're updating a shared structure.
    -        _acquireLock()
    -        try:    #unlikely to raise an exception, but you never know...
    -            if self._name and self._name in _handlers:
    -                del _handlers[self._name]
    -        finally:
    -            _releaseLock()
    -
    -    def handleError(self, record):
    -        """
    -        Handle errors which occur during an emit() call.
    -
    -        This method should be called from handlers when an exception is
    -        encountered during an emit() call. If raiseExceptions is false,
    -        exceptions get silently ignored. This is what is mostly wanted
    -        for a logging system - most users will not care about errors in
    -        the logging system, they are more interested in application errors.
    -        You could, however, replace this with a custom handler if you wish.
    -        The record which was being processed is passed in to this method.
    -        """
    -        if raiseExceptions and sys.stderr:  # see issue 13807
    -            t, v, tb = sys.exc_info()
    -            try:
    -                sys.stderr.write('--- Logging error ---\n')
    -                traceback.print_exception(t, v, tb, None, sys.stderr)
    -                sys.stderr.write('Call stack:\n')
    -                # Walk the stack frame up until we're out of logging,
    -                # so as to print the calling context.
    -                frame = tb.tb_frame
    -                while (frame and os.path.dirname(frame.f_code.co_filename) ==
    -                       __path__[0]):
    -                    frame = frame.f_back
    -                if frame:
    -                    traceback.print_stack(frame, file=sys.stderr)
    -                else:
    -                    # couldn't find the right stack frame, for some reason
    -                    sys.stderr.write('Logged from file %s, line %s\n' % (
    -                                     record.filename, record.lineno))
    -                # Issue 18671: output logging message and arguments
    -                try:
    -                    sys.stderr.write('Message: %r\n'
    -                                     'Arguments: %s\n' % (record.msg,
    -                                                          record.args))
    -                except Exception:
    -                    sys.stderr.write('Unable to print the message and arguments'
    -                                     ' - possible formatting error.\nUse the'
    -                                     ' traceback above to help find the error.\n'
    -                                    )
    -            except OSError: #pragma: no cover
    -                pass    # see issue 5971
    -            finally:
    -                del t, v, tb
    -
    -    def __repr__(self):
    -        level = getLevelName(self.level)
    -        return '<%s (%s)>' % (self.__class__.__name__, level)
    -
    -class StreamHandler(Handler):
    -    """
    -    A handler class which writes logging records, appropriately formatted,
    -    to a stream. Note that this class does not close the stream, as
    -    sys.stdout or sys.stderr may be used.
    -    """
    -
    -    terminator = '\n'
    -
    -    def __init__(self, stream=None):
    -        """
    -        Initialize the handler.
    -
    -        If stream is not specified, sys.stderr is used.
    -        """
    -        Handler.__init__(self)
    -        if stream is None:
    -            stream = sys.stderr
    -        self.stream = stream
    -
    -    def flush(self):
    -        """
    -        Flushes the stream.
    -        """
    -        self.acquire()
    -        try:
    -            if self.stream and hasattr(self.stream, "flush"):
    -                self.stream.flush()
    -        finally:
    -            self.release()
    -
    -    def emit(self, record):
    -        """
    -        Emit a record.
    -
    -        If a formatter is specified, it is used to format the record.
    -        The record is then written to the stream with a trailing newline.  If
    -        exception information is present, it is formatted using
    -        traceback.print_exception and appended to the stream.  If the stream
    -        has an 'encoding' attribute, it is used to determine how to do the
    -        output to the stream.
    -        """
    -        try:
    -            msg = self.format(record)
    -            stream = self.stream
    -            stream.write(msg)
    -            stream.write(self.terminator)
    -            self.flush()
    -        except Exception:
    -            self.handleError(record)
    -
    -    def __repr__(self):
    -        level = getLevelName(self.level)
    -        name = getattr(self.stream, 'name', '')
    -        if name:
    -            name += ' '
    -        return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
    -
    -
    -class FileHandler(StreamHandler):
    -    """
    -    A handler class which writes formatted logging records to disk files.
    -    """
    -    def __init__(self, filename, mode='a', encoding=None, delay=False):
    -        """
    -        Open the specified file and use it as the stream for logging.
    -        """
    -        # Issue #27493: add support for Path objects to be passed in
    -        filename = os.fspath(filename)
    -        #keep the absolute path, otherwise derived classes which use this
    -        #may come a cropper when the current directory changes
    -        self.baseFilename = os.path.abspath(filename)
    -        self.mode = mode
    -        self.encoding = encoding
    -        self.delay = delay
    -        if delay:
    -            #We don't open the stream, but we still need to call the
    -            #Handler constructor to set level, formatter, lock etc.
    -            Handler.__init__(self)
    -            self.stream = None
    -        else:
    -            StreamHandler.__init__(self, self._open())
    -
    -    def close(self):
    -        """
    -        Closes the stream.
    -        """
    -        self.acquire()
    -        try:
    -            try:
    -                if self.stream:
    -                    try:
    -                        self.flush()
    -                    finally:
    -                        stream = self.stream
    -                        self.stream = None
    -                        if hasattr(stream, "close"):
    -                            stream.close()
    -            finally:
    -                # Issue #19523: call unconditionally to
    -                # prevent a handler leak when delay is set
    -                StreamHandler.close(self)
    -        finally:
    -            self.release()
    -
    -    def _open(self):
    -        """
    -        Open the current base file with the (original) mode and encoding.
    -        Return the resulting stream.
    -        """
    -        return open(self.baseFilename, self.mode, encoding=self.encoding)
    -
    -    def emit(self, record):
    -        """
    -        Emit a record.
    -
    -        If the stream was not opened because 'delay' was specified in the
    -        constructor, open it before calling the superclass's emit.
    -        """
    -        if self.stream is None:
    -            self.stream = self._open()
    -        StreamHandler.emit(self, record)
    -
    -    def __repr__(self):
    -        level = getLevelName(self.level)
    -        return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level)
    -
    -
    -class _StderrHandler(StreamHandler):
    -    """
    -    This class is like a StreamHandler using sys.stderr, but always uses
    -    whatever sys.stderr is currently set to rather than the value of
    -    sys.stderr at handler construction time.
    -    """
    -    def __init__(self, level=NOTSET):
    -        """
    -        Initialize the handler.
    -        """
    -        Handler.__init__(self, level)
    -
    -    @property
    -    def stream(self):
    -        return sys.stderr
    -
    -
    -_defaultLastResort = _StderrHandler(WARNING)
    -lastResort = _defaultLastResort
    -
    -#---------------------------------------------------------------------------
    -#   Manager classes and functions
    -#---------------------------------------------------------------------------
    -
    -class PlaceHolder(object):
    -    """
    -    PlaceHolder instances are used in the Manager logger hierarchy to take
    -    the place of nodes for which no loggers have been defined. This class is
    -    intended for internal use only and not as part of the public API.
    -    """
    -    def __init__(self, alogger):
    -        """
    -        Initialize with the specified logger being a child of this placeholder.
    -        """
    -        self.loggerMap = { alogger : None }
    -
    -    def append(self, alogger):
    -        """
    -        Add the specified logger as a child of this placeholder.
    -        """
    -        if alogger not in self.loggerMap:
    -            self.loggerMap[alogger] = None
    -
    -#
    -#   Determine which class to use when instantiating loggers.
    -#
    -
    -def setLoggerClass(klass):
    -    """
    -    Set the class to be used when instantiating a logger. The class should
    -    define __init__() such that only a name argument is required, and the
    -    __init__() should call Logger.__init__()
    -    """
    -    if klass != Logger:
    -        if not issubclass(klass, Logger):
    -            raise TypeError("logger not derived from logging.Logger: "
    -                            + klass.__name__)
    -    global _loggerClass
    -    _loggerClass = klass
    -
    -def getLoggerClass():
    -    """
    -    Return the class to be used when instantiating a logger.
    -    """
    -    return _loggerClass
    -
    -class Manager(object):
    -    """
    -    There is [under normal circumstances] just one Manager instance, which
    -    holds the hierarchy of loggers.
    -    """
    -    def __init__(self, rootnode):
    -        """
    -        Initialize the manager with the root node of the logger hierarchy.
    -        """
    -        self.root = rootnode
    -        self.disable = 0
    -        self.emittedNoHandlerWarning = False
    -        self.loggerDict = {}
    -        self.loggerClass = None
    -        self.logRecordFactory = None
    -
    -    def getLogger(self, name):
    -        """
    -        Get a logger with the specified name (channel name), creating it
    -        if it doesn't yet exist. This name is a dot-separated hierarchical
    -        name, such as "a", "a.b", "a.b.c" or similar.
    -
    -        If a PlaceHolder existed for the specified name [i.e. the logger
    -        didn't exist but a child of it did], replace it with the created
    -        logger and fix up the parent/child references which pointed to the
    -        placeholder to now point to the logger.
    -        """
    -        rv = None
    -        if not isinstance(name, str):
    -            raise TypeError('A logger name must be a string')
    -        _acquireLock()
    -        try:
    -            if name in self.loggerDict:
    -                rv = self.loggerDict[name]
    -                if isinstance(rv, PlaceHolder):
    -                    ph = rv
    -                    rv = (self.loggerClass or _loggerClass)(name)
    -                    rv.manager = self
    -                    self.loggerDict[name] = rv
    -                    self._fixupChildren(ph, rv)
    -                    self._fixupParents(rv)
    -            else:
    -                rv = (self.loggerClass or _loggerClass)(name)
    -                rv.manager = self
    -                self.loggerDict[name] = rv
    -                self._fixupParents(rv)
    -        finally:
    -            _releaseLock()
    -        return rv
    -
    -    def setLoggerClass(self, klass):
    -        """
    -        Set the class to be used when instantiating a logger with this Manager.
    -        """
    -        if klass != Logger:
    -            if not issubclass(klass, Logger):
    -                raise TypeError("logger not derived from logging.Logger: "
    -                                + klass.__name__)
    -        self.loggerClass = klass
    -
    -    def setLogRecordFactory(self, factory):
    -        """
    -        Set the factory to be used when instantiating a log record with this
    -        Manager.
    -        """
    -        self.logRecordFactory = factory
    -
    -    def _fixupParents(self, alogger):
    -        """
    -        Ensure that there are either loggers or placeholders all the way
    -        from the specified logger to the root of the logger hierarchy.
    -        """
    -        name = alogger.name
    -        i = name.rfind(".")
    -        rv = None
    -        while (i > 0) and not rv:
    -            substr = name[:i]
    -            if substr not in self.loggerDict:
    -                self.loggerDict[substr] = PlaceHolder(alogger)
    -            else:
    -                obj = self.loggerDict[substr]
    -                if isinstance(obj, Logger):
    -                    rv = obj
    -                else:
    -                    assert isinstance(obj, PlaceHolder)
    -                    obj.append(alogger)
    -            i = name.rfind(".", 0, i - 1)
    -        if not rv:
    -            rv = self.root
    -        alogger.parent = rv
    -
    -    def _fixupChildren(self, ph, alogger):
    -        """
    -        Ensure that children of the placeholder ph are connected to the
    -        specified logger.
    -        """
    -        name = alogger.name
    -        namelen = len(name)
    -        for c in ph.loggerMap.keys():
    -            #The if means ... if not c.parent.name.startswith(nm)
    -            if c.parent.name[:namelen] != name:
    -                alogger.parent = c.parent
    -                c.parent = alogger
    -
    -#---------------------------------------------------------------------------
    -#   Logger classes and functions
    -#---------------------------------------------------------------------------
    -
    -class Logger(Filterer):
    -    """
    -    Instances of the Logger class represent a single logging channel. A
    -    "logging channel" indicates an area of an application. Exactly how an
    -    "area" is defined is up to the application developer. Since an
    -    application can have any number of areas, logging channels are identified
    -    by a unique string. Application areas can be nested (e.g. an area
    -    of "input processing" might include sub-areas "read CSV files", "read
    -    XLS files" and "read Gnumeric files"). To cater for this natural nesting,
    -    channel names are organized into a namespace hierarchy where levels are
    -    separated by periods, much like the Java or Python package namespace. So
    -    in the instance given above, channel names might be "input" for the upper
    -    level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
    -    There is no arbitrary limit to the depth of nesting.
    -    """
    -    def __init__(self, name, level=NOTSET):
    -        """
    -        Initialize the logger with a name and an optional level.
    -        """
    -        Filterer.__init__(self)
    -        self.name = name
    -        self.level = _checkLevel(level)
    -        self.parent = None
    -        self.propagate = True
    -        self.handlers = []
    -        self.disabled = False
    -
    -    def setLevel(self, level):
    -        """
    -        Set the logging level of this logger.  level must be an int or a str.
    -        """
    -        self.level = _checkLevel(level)
    -
    -    def debug(self, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with severity 'DEBUG'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
    -        """
    -        if self.isEnabledFor(DEBUG):
    -            self._log(DEBUG, msg, args, **kwargs)
    -
    -    def info(self, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with severity 'INFO'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
    -        """
    -        if self.isEnabledFor(INFO):
    -            self._log(INFO, msg, args, **kwargs)
    -
    -    def warning(self, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with severity 'WARNING'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
    -        """
    -        if self.isEnabledFor(WARNING):
    -            self._log(WARNING, msg, args, **kwargs)
    -
    -    def warn(self, msg, *args, **kwargs):
    -        warnings.warn("The 'warn' method is deprecated, "
    -            "use 'warning' instead", DeprecationWarning, 2)
    -        self.warning(msg, *args, **kwargs)
    -
    -    def error(self, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with severity 'ERROR'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.error("Houston, we have a %s", "major problem", exc_info=1)
    -        """
    -        if self.isEnabledFor(ERROR):
    -            self._log(ERROR, msg, args, **kwargs)
    -
    -    def exception(self, msg, *args, exc_info=True, **kwargs):
    -        """
    -        Convenience method for logging an ERROR with exception information.
    -        """
    -        self.error(msg, *args, exc_info=exc_info, **kwargs)
    -
    -    def critical(self, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with severity 'CRITICAL'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
    -        """
    -        if self.isEnabledFor(CRITICAL):
    -            self._log(CRITICAL, msg, args, **kwargs)
    -
    -    fatal = critical
    -
    -    def log(self, level, msg, *args, **kwargs):
    -        """
    -        Log 'msg % args' with the integer severity 'level'.
    -
    -        To pass exception information, use the keyword argument exc_info with
    -        a true value, e.g.
    -
    -        logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
    -        """
    -        if not isinstance(level, int):
    -            if raiseExceptions:
    -                raise TypeError("level must be an integer")
    -            else:
    -                return
    -        if self.isEnabledFor(level):
    -            self._log(level, msg, args, **kwargs)
    -
    -    def findCaller(self, stack_info=False):
    -        """
    -        Find the stack frame of the caller so that we can note the source
    -        file name, line number and function name.
    -        """
    -        f = currentframe()
    -        #On some versions of IronPython, currentframe() returns None if
    -        #IronPython isn't run with -X:Frames.
    -        if f is not None:
    -            f = f.f_back
    -        rv = "(unknown file)", 0, "(unknown function)", None
    -        while hasattr(f, "f_code"):
    -            co = f.f_code
    -            filename = os.path.normcase(co.co_filename)
    -            if filename == _srcfile:
    -                f = f.f_back
    -                continue
    -            sinfo = None
    -            if stack_info:
    -                sio = io.StringIO()
    -                sio.write('Stack (most recent call last):\n')
    -                traceback.print_stack(f, file=sio)
    -                sinfo = sio.getvalue()
    -                if sinfo[-1] == '\n':
    -                    sinfo = sinfo[:-1]
    -                sio.close()
    -            rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
    -            break
    -        return rv
    -
    -    def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
    -                   func=None, extra=None, sinfo=None):
    -        """
    -        A factory method which can be overridden in subclasses to create
    -        specialized LogRecords.
    -        """
    -        rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
    -                             sinfo)
    -        if extra is not None:
    -            for key in extra:
    -                if (key in ["message", "asctime"]) or (key in rv.__dict__):
    -                    raise KeyError("Attempt to overwrite %r in LogRecord" % key)
    -                rv.__dict__[key] = extra[key]
    -        return rv
    -
    -    def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
    -        """
    -        Low-level logging routine which creates a LogRecord and then calls
    -        all the handlers of this logger to handle the record.
    -        """
    -        sinfo = None
    -        if _srcfile:
    -            #IronPython doesn't track Python frames, so findCaller raises an
    -            #exception on some versions of IronPython. We trap it here so that
    -            #IronPython can use logging.
    -            try:
    -                fn, lno, func, sinfo = self.findCaller(stack_info)
    -            except ValueError: # pragma: no cover
    -                fn, lno, func = "(unknown file)", 0, "(unknown function)"
    -        else: # pragma: no cover
    -            fn, lno, func = "(unknown file)", 0, "(unknown function)"
    -        if exc_info:
    -            if isinstance(exc_info, BaseException):
    -                exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
    -            elif not isinstance(exc_info, tuple):
    -                exc_info = sys.exc_info()
    -        record = self.makeRecord(self.name, level, fn, lno, msg, args,
    -                                 exc_info, func, extra, sinfo)
    -        self.handle(record)
    -
    -    def handle(self, record):
    -        """
    -        Call the handlers for the specified record.
    -
    -        This method is used for unpickled records received from a socket, as
    -        well as those created locally. Logger-level filtering is applied.
    -        """
    -        if (not self.disabled) and self.filter(record):
    -            self.callHandlers(record)
    -
    -    def addHandler(self, hdlr):
    -        """
    -        Add the specified handler to this logger.
    -        """
    -        _acquireLock()
    -        try:
    -            if not (hdlr in self.handlers):
    -                self.handlers.append(hdlr)
    -        finally:
    -            _releaseLock()
    -
    -    def removeHandler(self, hdlr):
    -        """
    -        Remove the specified handler from this logger.
    -        """
    -        _acquireLock()
    -        try:
    -            if hdlr in self.handlers:
    -                self.handlers.remove(hdlr)
    -        finally:
    -            _releaseLock()
    -
    -    def hasHandlers(self):
    -        """
    -        See if this logger has any handlers configured.
    -
    -        Loop through all handlers for this logger and its parents in the
    -        logger hierarchy. Return True if a handler was found, else False.
    -        Stop searching up the hierarchy whenever a logger with the "propagate"
    -        attribute set to zero is found - that will be the last logger which
    -        is checked for the existence of handlers.
    -        """
    -        c = self
    -        rv = False
    -        while c:
    -            if c.handlers:
    -                rv = True
    -                break
    -            if not c.propagate:
    -                break
    -            else:
    -                c = c.parent
    -        return rv
    -
    -    def callHandlers(self, record):
    -        """
    -        Pass a record to all relevant handlers.
    -
    -        Loop through all handlers for this logger and its parents in the
    -        logger hierarchy. If no handler was found, output a one-off error
    -        message to sys.stderr. Stop searching up the hierarchy whenever a
    -        logger with the "propagate" attribute set to zero is found - that
    -        will be the last logger whose handlers are called.
    -        """
    -        c = self
    -        found = 0
    -        while c:
    -            for hdlr in c.handlers:
    -                found = found + 1
    -                if record.levelno >= hdlr.level:
    -                    hdlr.handle(record)
    -            if not c.propagate:
    -                c = None    #break out
    -            else:
    -                c = c.parent
    -        if (found == 0):
    -            if lastResort:
    -                if record.levelno >= lastResort.level:
    -                    lastResort.handle(record)
    -            elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
    -                sys.stderr.write("No handlers could be found for logger"
    -                                 " \"%s\"\n" % self.name)
    -                self.manager.emittedNoHandlerWarning = True
    -
    -    def getEffectiveLevel(self):
    -        """
    -        Get the effective level for this logger.
    -
    -        Loop through this logger and its parents in the logger hierarchy,
    -        looking for a non-zero logging level. Return the first one found.
    -        """
    -        logger = self
    -        while logger:
    -            if logger.level:
    -                return logger.level
    -            logger = logger.parent
    -        return NOTSET
    -
    -    def isEnabledFor(self, level):
    -        """
    -        Is this logger enabled for level 'level'?
    -        """
    -        if self.manager.disable >= level:
    -            return False
    -        return level >= self.getEffectiveLevel()
    -
    -    def getChild(self, suffix):
    -        """
    -        Get a logger which is a descendant to this one.
    -
    -        This is a convenience method, such that
    -
    -        logging.getLogger('abc').getChild('def.ghi')
    -
    -        is the same as
    -
    -        logging.getLogger('abc.def.ghi')
    -
    -        It's useful, for example, when the parent logger is named using
    -        __name__ rather than a literal string.
    -        """
    -        if self.root is not self:
    -            suffix = '.'.join((self.name, suffix))
    -        return self.manager.getLogger(suffix)
    -
    -    def __repr__(self):
    -        level = getLevelName(self.getEffectiveLevel())
    -        return '<%s %s (%s)>' % (self.__class__.__name__, self.name, level)
    -
    -
    -class RootLogger(Logger):
    -    """
    -    A root logger is not that different to any other logger, except that
    -    it must have a logging level and there is only one instance of it in
    -    the hierarchy.
    -    """
    -    def __init__(self, level):
    -        """
    -        Initialize the logger with the name "root".
    -        """
    -        Logger.__init__(self, "root", level)
    -
    -_loggerClass = Logger
    -
    -class LoggerAdapter(object):
    -    """
    -    An adapter for loggers which makes it easier to specify contextual
    -    information in logging output.
    -    """
    -
    -    def __init__(self, logger, extra):
    -        """
    -        Initialize the adapter with a logger and a dict-like object which
    -        provides contextual information. This constructor signature allows
    -        easy stacking of LoggerAdapters, if so desired.
    -
    -        You can effectively pass keyword arguments as shown in the
    -        following example:
    -
    -        adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
    -        """
    -        self.logger = logger
    -        self.extra = extra
    -
    -    def process(self, msg, kwargs):
    -        """
    -        Process the logging message and keyword arguments passed in to
    -        a logging call to insert contextual information. You can either
    -        manipulate the message itself, the keyword args or both. Return
    -        the message and kwargs modified (or not) to suit your needs.
    -
    -        Normally, you'll only need to override this one method in a
    -        LoggerAdapter subclass for your specific needs.
    -        """
    -        kwargs["extra"] = self.extra
    -        return msg, kwargs
    -
    -    #
    -    # Boilerplate convenience methods
    -    #
    -    def debug(self, msg, *args, **kwargs):
    -        """
    -        Delegate a debug call to the underlying logger.
    -        """
    -        self.log(DEBUG, msg, *args, **kwargs)
    -
    -    def info(self, msg, *args, **kwargs):
    -        """
    -        Delegate an info call to the underlying logger.
    -        """
    -        self.log(INFO, msg, *args, **kwargs)
    -
    -    def warning(self, msg, *args, **kwargs):
    -        """
    -        Delegate a warning call to the underlying logger.
    -        """
    -        self.log(WARNING, msg, *args, **kwargs)
    -
    -    def warn(self, msg, *args, **kwargs):
    -        warnings.warn("The 'warn' method is deprecated, "
    -            "use 'warning' instead", DeprecationWarning, 2)
    -        self.warning(msg, *args, **kwargs)
    -
    -    def error(self, msg, *args, **kwargs):
    -        """
    -        Delegate an error call to the underlying logger.
    -        """
    -        self.log(ERROR, msg, *args, **kwargs)
    -
    -    def exception(self, msg, *args, exc_info=True, **kwargs):
    -        """
    -        Delegate an exception call to the underlying logger.
    -        """
    -        self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
    -
    -    def critical(self, msg, *args, **kwargs):
    -        """
    -        Delegate a critical call to the underlying logger.
    -        """
    -        self.log(CRITICAL, msg, *args, **kwargs)
    -
    -    def log(self, level, msg, *args, **kwargs):
    -        """
    -        Delegate a log call to the underlying logger, after adding
    -        contextual information from this adapter instance.
    -        """
    -        if self.isEnabledFor(level):
    -            msg, kwargs = self.process(msg, kwargs)
    -            self.logger.log(level, msg, *args, **kwargs)
    -
    -    def isEnabledFor(self, level):
    -        """
    -        Is this logger enabled for level 'level'?
    -        """
    -        if self.logger.manager.disable >= level:
    -            return False
    -        return level >= self.getEffectiveLevel()
    -
    -    def setLevel(self, level):
    -        """
    -        Set the specified level on the underlying logger.
    -        """
    -        self.logger.setLevel(level)
    -
    -    def getEffectiveLevel(self):
    -        """
    -        Get the effective level for the underlying logger.
    -        """
    -        return self.logger.getEffectiveLevel()
    -
    -    def hasHandlers(self):
    -        """
    -        See if the underlying logger has any handlers.
    -        """
    -        return self.logger.hasHandlers()
    -
    -    def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
    -        """
    -        Low-level log implementation, proxied to allow nested logger adapters.
    -        """
    -        return self.logger._log(
    -            level,
    -            msg,
    -            args,
    -            exc_info=exc_info,
    -            extra=extra,
    -            stack_info=stack_info,
    -        )
    -
    -    @property
    -    def manager(self):
    -        return self.logger.manager
    -
    -    @manager.setter
    -    def manager(self, value):
    -        self.logger.manager = value
    -
    -    @property
    -    def name(self):
    -        return self.logger.name
    -
    -    def __repr__(self):
    -        logger = self.logger
    -        level = getLevelName(logger.getEffectiveLevel())
    -        return '<%s %s (%s)>' % (self.__class__.__name__, logger.name, level)
    -
    -root = RootLogger(WARNING)
    -Logger.root = root
    -Logger.manager = Manager(Logger.root)
    -
    -#---------------------------------------------------------------------------
    -# Configuration classes and functions
    -#---------------------------------------------------------------------------
    -
    -def basicConfig(**kwargs):
    -    """
    -    Do basic configuration for the logging system.
    -
    -    This function does nothing if the root logger already has handlers
    -    configured. It is a convenience method intended for use by simple scripts
    -    to do one-shot configuration of the logging package.
    -
    -    The default behaviour is to create a StreamHandler which writes to
    -    sys.stderr, set a formatter using the BASIC_FORMAT format string, and
    -    add the handler to the root logger.
    -
    -    A number of optional keyword arguments may be specified, which can alter
    -    the default behaviour.
    -
    -    filename  Specifies that a FileHandler be created, using the specified
    -              filename, rather than a StreamHandler.
    -    filemode  Specifies the mode to open the file, if filename is specified
    -              (if filemode is unspecified, it defaults to 'a').
    -    format    Use the specified format string for the handler.
    -    datefmt   Use the specified date/time format.
    -    style     If a format string is specified, use this to specify the
    -              type of format string (possible values '%', '{', '$', for
    -              %-formatting, :meth:`str.format` and :class:`string.Template`
    -              - defaults to '%').
    -    level     Set the root logger level to the specified level.
    -    stream    Use the specified stream to initialize the StreamHandler. Note
    -              that this argument is incompatible with 'filename' - if both
    -              are present, 'stream' is ignored.
    -    handlers  If specified, this should be an iterable of already created
    -              handlers, which will be added to the root handler. Any handler
    -              in the list which does not have a formatter assigned will be
    -              assigned the formatter created in this function.
    -
    -    Note that you could specify a stream created using open(filename, mode)
    -    rather than passing the filename and mode in. However, it should be
    -    remembered that StreamHandler does not close its stream (since it may be
    -    using sys.stdout or sys.stderr), whereas FileHandler closes its stream
    -    when the handler is closed.
    -
    -    .. versionchanged:: 3.2
    -       Added the ``style`` parameter.
    -
    -    .. versionchanged:: 3.3
    -       Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
    -       incompatible arguments (e.g. ``handlers`` specified together with
    -       ``filename``/``filemode``, or ``filename``/``filemode`` specified
    -       together with ``stream``, or ``handlers`` specified together with
    -       ``stream``.
    -    """
    -    # Add thread safety in case someone mistakenly calls
    -    # basicConfig() from multiple threads
    -    _acquireLock()
    -    try:
    -        if len(root.handlers) == 0:
    -            handlers = kwargs.pop("handlers", None)
    -            if handlers is None:
    -                if "stream" in kwargs and "filename" in kwargs:
    -                    raise ValueError("'stream' and 'filename' should not be "
    -                                     "specified together")
    -            else:
    -                if "stream" in kwargs or "filename" in kwargs:
    -                    raise ValueError("'stream' or 'filename' should not be "
    -                                     "specified together with 'handlers'")
    -            if handlers is None:
    -                filename = kwargs.pop("filename", None)
    -                mode = kwargs.pop("filemode", 'a')
    -                if filename:
    -                    h = FileHandler(filename, mode)
    -                else:
    -                    stream = kwargs.pop("stream", None)
    -                    h = StreamHandler(stream)
    -                handlers = [h]
    -            dfs = kwargs.pop("datefmt", None)
    -            style = kwargs.pop("style", '%')
    -            if style not in _STYLES:
    -                raise ValueError('Style must be one of: %s' % ','.join(
    -                                 _STYLES.keys()))
    -            fs = kwargs.pop("format", _STYLES[style][1])
    -            fmt = Formatter(fs, dfs, style)
    -            for h in handlers:
    -                if h.formatter is None:
    -                    h.setFormatter(fmt)
    -                root.addHandler(h)
    -            level = kwargs.pop("level", None)
    -            if level is not None:
    -                root.setLevel(level)
    -            if kwargs:
    -                keys = ', '.join(kwargs.keys())
    -                raise ValueError('Unrecognised argument(s): %s' % keys)
    -    finally:
    -        _releaseLock()
    -
    -#---------------------------------------------------------------------------
    -# Utility functions at module level.
    -# Basically delegate everything to the root logger.
    -#---------------------------------------------------------------------------
    -
    -def getLogger(name=None):
    -    """
    -    Return a logger with the specified name, creating it if necessary.
    -
    -    If no name is specified, return the root logger.
    -    """
    -    if name:
    -        return Logger.manager.getLogger(name)
    -    else:
    -        return root
    -
    -def critical(msg, *args, **kwargs):
    -    """
    -    Log a message with severity 'CRITICAL' on the root logger. If the logger
    -    has no handlers, call basicConfig() to add a console handler with a
    -    pre-defined format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.critical(msg, *args, **kwargs)
    -
    -fatal = critical
    -
    -def error(msg, *args, **kwargs):
    -    """
    -    Log a message with severity 'ERROR' on the root logger. If the logger has
    -    no handlers, call basicConfig() to add a console handler with a pre-defined
    -    format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.error(msg, *args, **kwargs)
    -
    -def exception(msg, *args, exc_info=True, **kwargs):
    -    """
    -    Log a message with severity 'ERROR' on the root logger, with exception
    -    information. If the logger has no handlers, basicConfig() is called to add
    -    a console handler with a pre-defined format.
    -    """
    -    error(msg, *args, exc_info=exc_info, **kwargs)
    -
    -def warning(msg, *args, **kwargs):
    -    """
    -    Log a message with severity 'WARNING' on the root logger. If the logger has
    -    no handlers, call basicConfig() to add a console handler with a pre-defined
    -    format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.warning(msg, *args, **kwargs)
    -
    -def warn(msg, *args, **kwargs):
    -    warnings.warn("The 'warn' function is deprecated, "
    -        "use 'warning' instead", DeprecationWarning, 2)
    -    warning(msg, *args, **kwargs)
    -
    -def info(msg, *args, **kwargs):
    -    """
    -    Log a message with severity 'INFO' on the root logger. If the logger has
    -    no handlers, call basicConfig() to add a console handler with a pre-defined
    -    format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.info(msg, *args, **kwargs)
    -
    -def debug(msg, *args, **kwargs):
    -    """
    -    Log a message with severity 'DEBUG' on the root logger. If the logger has
    -    no handlers, call basicConfig() to add a console handler with a pre-defined
    -    format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.debug(msg, *args, **kwargs)
    -
    -def log(level, msg, *args, **kwargs):
    -    """
    -    Log 'msg % args' with the integer severity 'level' on the root logger. If
    -    the logger has no handlers, call basicConfig() to add a console handler
    -    with a pre-defined format.
    -    """
    -    if len(root.handlers) == 0:
    -        basicConfig()
    -    root.log(level, msg, *args, **kwargs)
    -
    -def disable(level):
    -    """
    -    Disable all logging calls of severity 'level' and below.
    -    """
    -    root.manager.disable = level
    -
    -def shutdown(handlerList=_handlerList):
    -    """
    -    Perform any cleanup actions in the logging system (e.g. flushing
    -    buffers).
    -
    -    Should be called at application exit.
    -    """
    -    for wr in reversed(handlerList[:]):
    -        #errors might occur, for example, if files are locked
    -        #we just ignore them if raiseExceptions is not set
    -        try:
    -            h = wr()
    -            if h:
    -                try:
    -                    h.acquire()
    -                    h.flush()
    -                    h.close()
    -                except (OSError, ValueError):
    -                    # Ignore errors which might be caused
    -                    # because handlers have been closed but
    -                    # references to them are still around at
    -                    # application exit.
    -                    pass
    -                finally:
    -                    h.release()
    -        except: # ignore everything, as we're shutting down
    -            if raiseExceptions:
    -                raise
    -            #else, swallow
    -
    -#Let's try and shutdown automatically on application exit...
    -import atexit
    -atexit.register(shutdown)
    -
    -# Null handler
    -
    -class NullHandler(Handler):
    -    """
    -    This handler does nothing. It's intended to be used to avoid the
    -    "No handlers could be found for logger XXX" one-off warning. This is
    -    important for library code, which may contain code to log events. If a user
    -    of the library does not configure logging, the one-off warning might be
    -    produced; to avoid this, the library developer simply needs to instantiate
    -    a NullHandler and add it to the top-level logger of the library module or
    -    package.
    -    """
    -    def handle(self, record):
    -        """Stub."""
    -
    -    def emit(self, record):
    -        """Stub."""
    -
    -    def createLock(self):
    -        self.lock = None
    -
    -# Warnings integration
    -
    -_warnings_showwarning = None
    -
    -def _showwarning(message, category, filename, lineno, file=None, line=None):
    -    """
    -    Implementation of showwarnings which redirects to logging, which will first
    -    check to see if the file parameter is None. If a file is specified, it will
    -    delegate to the original warnings implementation of showwarning. Otherwise,
    -    it will call warnings.formatwarning and will log the resulting string to a
    -    warnings logger named "py.warnings" with level logging.WARNING.
    -    """
    -    if file is not None:
    -        if _warnings_showwarning is not None:
    -            _warnings_showwarning(message, category, filename, lineno, file, line)
    -    else:
    -        s = warnings.formatwarning(message, category, filename, lineno, line)
    -        logger = getLogger("py.warnings")
    -        if not logger.handlers:
    -            logger.addHandler(NullHandler())
    -        logger.warning("%s", s)
    -
    -def captureWarnings(capture):
    -    """
    -    If capture is true, redirect all warnings to the logging package.
    -    If capture is False, ensure that warnings are not redirected to logging
    -    but to their original destinations.
    -    """
    -    global _warnings_showwarning
    -    if capture:
    -        if _warnings_showwarning is None:
    -            _warnings_showwarning = warnings.showwarning
    -            warnings.showwarning = _showwarning
    -    else:
    -        if _warnings_showwarning is not None:
    -            warnings.showwarning = _warnings_showwarning
    -            _warnings_showwarning = None
    -
    - -
    -
    -
    - - - - - -
    -
    -
    - - -
    - - - - - \ No newline at end of file diff --git a/_static/basic.css b/_static/basic.css index 692c210..d2fbce1 100644 --- a/_static/basic.css +++ b/_static/basic.css @@ -520,14 +520,15 @@ dl.citation > dd:after { } dl.field-list { - display: flex; - flex-wrap: wrap; + display: grid; + grid-template-columns: fit-content(30%) auto; } dl.field-list > dt { - flex-basis: 20%; font-weight: bold; word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; } dl.field-list > dt:after { @@ -535,8 +536,8 @@ dl.field-list > dt:after { } dl.field-list > dd { - flex-basis: 70%; - padding-left: 1em; + padding-left: 0.5em; + margin-top: 0em; margin-left: 0em; margin-bottom: 0em; } diff --git a/_static/documentation_options.js b/_static/documentation_options.js index 252ed6b..dd10fcd 100644 --- a/_static/documentation_options.js +++ b/_static/documentation_options.js @@ -1,6 +1,6 @@ var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), - VERSION: '1.2.0', + VERSION: '1.2.1', LANGUAGE: 'None', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', diff --git a/_static/jquery-3.2.1.js b/_static/jquery-3.4.1.js similarity index 89% rename from _static/jquery-3.2.1.js rename to _static/jquery-3.4.1.js index d2d8ca4..773ad95 100644 --- a/_static/jquery-3.2.1.js +++ b/_static/jquery-3.4.1.js @@ -1,5 +1,5 @@ /*! - * jQuery JavaScript Library v3.2.1 + * jQuery JavaScript Library v3.4.1 * https://jquery.com/ * * Includes Sizzle.js @@ -9,7 +9,7 @@ * Released under the MIT license * https://jquery.org/license * - * Date: 2017-03-20T18:59Z + * Date: 2019-05-01T21:04Z */ ( function( global, factory ) { @@ -71,16 +71,70 @@ 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"; + }; - function DOMEval( code, doc ) { + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { doc = doc || document; - var script = doc.createElement( "script" ); + 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 @@ -88,7 +142,7 @@ var support = {}; var - version = "3.2.1", + version = "3.4.1", // Define a local copy of jQuery jQuery = function( selector, context ) { @@ -100,16 +154,7 @@ var // Support: Android <=4.0 only // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }; + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; jQuery.fn = jQuery.prototype = { @@ -209,7 +254,7 @@ jQuery.extend = jQuery.fn.extend = function() { } // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } @@ -226,25 +271,28 @@ jQuery.extend = jQuery.fn.extend = function() { // Extend the base object for ( name in options ) { - src = target[ name ]; copy = options[ name ]; + // Prevent Object.prototype pollution // Prevent never-ending loop - if ( target === copy ) { + 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 ]; - if ( copyIsArray ) { - copyIsArray = false; - clone = src && Array.isArray( src ) ? src : []; - + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; } else { - clone = src && jQuery.isPlainObject( src ) ? src : {}; + clone = src; } + copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); @@ -275,28 +323,6 @@ jQuery.extend( { noop: function() {}, - isFunction: function( obj ) { - return jQuery.type( obj ) === "function"; - }, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - - // As of jQuery 3.0, isNumeric is limited to - // strings and numbers (primitives or objects) - // that can be coerced to finite numbers (gh-2662) - var type = jQuery.type( obj ); - return ( type === "number" || type === "string" ) && - - // parseFloat NaNs numeric-cast false positives ("") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - !isNaN( obj - parseFloat( obj ) ); - }, - isPlainObject: function( obj ) { var proto, Ctor; @@ -319,9 +345,6 @@ jQuery.extend( { }, isEmptyObject: function( obj ) { - - /* eslint-disable no-unused-vars */ - // See https://github.com/eslint/eslint/issues/6125 var name; for ( name in obj ) { @@ -330,27 +353,9 @@ jQuery.extend( { return true; }, - type: function( 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; - }, - // Evaluates a script in a global context - globalEval: function( code ) { - DOMEval( code ); - }, - - // Convert dashed to camelCase; used by the css and data modules - // Support: IE <=9 - 11, Edge 12 - 13 - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + globalEval: function( code, options ) { + DOMEval( code, { nonce: options && options.nonce } ); }, each: function( obj, callback ) { @@ -473,37 +478,6 @@ jQuery.extend( { // A global GUID counter for objects guid: 1, - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var tmp, args, proxy; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - now: Date.now, - // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support @@ -526,9 +500,9 @@ function isArrayLike( obj ) { // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, - type = jQuery.type( obj ); + type = toType( obj ); - if ( type === "function" || jQuery.isWindow( obj ) ) { + if ( isFunction( obj ) || isWindow( obj ) ) { return false; } @@ -537,14 +511,14 @@ function isArrayLike( obj ) { } var Sizzle = /*! - * Sizzle CSS Selector Engine v2.3.3 + * Sizzle CSS Selector Engine v2.3.4 * https://sizzlejs.com/ * - * Copyright jQuery Foundation and other contributors + * Copyright JS Foundation and other contributors * Released under the MIT license - * http://jquery.org/license + * https://js.foundation/ * - * Date: 2016-08-08 + * Date: 2019-04-08 */ (function( window ) { @@ -578,6 +552,7 @@ var i, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), + nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; @@ -639,8 +614,7 @@ var i, rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), @@ -661,6 +635,7 @@ var i, whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, + rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, @@ -715,9 +690,9 @@ var i, setDocument(); }, - disabledAncestor = addCombinator( + inDisabledFieldset = addCombinator( function( elem ) { - return elem.disabled === true && ("form" in elem || "label" in elem); + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); @@ -830,18 +805,22 @@ function Sizzle( selector, context, results, seed ) { // Take advantage of querySelectorAll if ( support.qsa && - !compilerCache[ selector + " " ] && - (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - - if ( nodeType !== 1 ) { - newContext = context; - newSelector = selector; + !nonnativeSelectorCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) && - // qSA looks outside Element context, which is not what we want - // Thanks to Andrew Dupont for this workaround technique - // Support: IE <=8 + // Support: IE 8 only // Exclude object elements - } else if ( context.nodeName.toLowerCase() !== "object" ) { + (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. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { @@ -863,17 +842,16 @@ function Sizzle( selector, context, results, seed ) { context; } - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); } } } @@ -1037,7 +1015,7 @@ function createDisabledPseudo( disabled ) { // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && - disabledAncestor( elem ) === disabled; + inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; @@ -1094,10 +1072,13 @@ support = Sizzle.support = {}; * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; + 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" ); }; /** @@ -1519,11 +1500,8 @@ Sizzle.matchesSelector = function( elem, expr ) { setDocument( elem ); } - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - if ( support.matchesSelector && documentIsHTML && - !compilerCache[ expr + " " ] && + !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { @@ -1537,7 +1515,9 @@ Sizzle.matchesSelector = function( elem, expr ) { elem.document && elem.document.nodeType !== 11 ) { return ret; } - } catch (e) {} + } catch (e) { + nonnativeSelectorCache( expr, true ); + } } return Sizzle( expr, document, null, [ elem ] ).length > 0; @@ -1996,7 +1976,7 @@ Expr = Sizzle.selectors = { "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; }), @@ -2135,7 +2115,11 @@ Expr = Sizzle.selectors = { }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; + var i = argument < 0 ? + argument + length : + argument > length ? + length : + argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } @@ -2848,11 +2832,9 @@ var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>| -var risSimple = /^.[^:#\[\.,]*$/; - // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { + if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); @@ -2872,16 +2854,8 @@ function winnow( elements, qualifier, not ) { } ); } - // Simple selector that can be filtered directly, removing non-Elements - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - // Complex selector, compare the two sets, removing non-Elements - qualifier = jQuery.filter( qualifier, elements ); - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; - } ); + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { @@ -3002,7 +2976,7 @@ var rootjQuery, for ( match in context ) { // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { + if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes @@ -3045,7 +3019,7 @@ var rootjQuery, // HANDLE: $(function) // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { + } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : @@ -3195,18 +3169,18 @@ jQuery.each( { return siblings( elem.firstChild ); }, contents: function( elem ) { - if ( nodeName( elem, "iframe" ) ) { - return elem.contentDocument; - } + if ( typeof elem.contentDocument !== "undefined" ) { + 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; - } + // 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 ); + return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { @@ -3360,11 +3334,11 @@ jQuery.Callbacks = function( options ) { ( function add( args ) { jQuery.each( args, function( _, arg ) { - if ( jQuery.isFunction( arg ) ) { + if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } - } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); @@ -3479,11 +3453,11 @@ function adoptValue( value, resolve, reject, noValue ) { try { // Check for promise aspect first to privilege synchronous behavior - if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { + if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables - } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { + } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables @@ -3541,14 +3515,14 @@ jQuery.extend( { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + 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 && jQuery.isFunction( returned.promise ) ) { + if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) @@ -3602,7 +3576,7 @@ jQuery.extend( { returned.then; // Handle a returned thenable - if ( jQuery.isFunction( then ) ) { + if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { @@ -3698,7 +3672,7 @@ jQuery.extend( { resolve( 0, newDefer, - jQuery.isFunction( onProgress ) ? + isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith @@ -3710,7 +3684,7 @@ jQuery.extend( { resolve( 0, newDefer, - jQuery.isFunction( onFulfilled ) ? + isFunction( onFulfilled ) ? onFulfilled : Identity ) @@ -3721,7 +3695,7 @@ jQuery.extend( { resolve( 0, newDefer, - jQuery.isFunction( onRejected ) ? + isFunction( onRejected ) ? onRejected : Thrower ) @@ -3761,8 +3735,15 @@ jQuery.extend( { // 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 + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock ); } @@ -3832,7 +3813,7 @@ jQuery.extend( { // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || - jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } @@ -3960,7 +3941,7 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { bulk = key == null; // Sets many values - if ( jQuery.type( key ) === "object" ) { + if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); @@ -3970,7 +3951,7 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { } else if ( value !== undefined ) { chainable = true; - if ( !jQuery.isFunction( value ) ) { + if ( !isFunction( value ) ) { raw = true; } @@ -4012,6 +3993,23 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { 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: @@ -4074,14 +4072,14 @@ Data.prototype = { // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { - cache[ jQuery.camelCase( data ) ] = value; + cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { - cache[ jQuery.camelCase( prop ) ] = data[ prop ]; + cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; @@ -4091,7 +4089,7 @@ Data.prototype = { this.cache( owner ) : // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { @@ -4139,9 +4137,9 @@ Data.prototype = { // If key is an array of keys... // We always set camelCase keys, so remove that. - key = key.map( jQuery.camelCase ); + key = key.map( camelCase ); } else { - key = jQuery.camelCase( key ); + key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace @@ -4287,7 +4285,7 @@ jQuery.fn.extend( { if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice( 5 ) ); + name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } @@ -4491,6 +4489,26 @@ 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; @@ -4505,7 +4523,7 @@ var isHiddenWithinTree = function( elem, el ) { // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. - jQuery.contains( elem.ownerDocument, elem ) && + isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; @@ -4534,8 +4552,7 @@ var swap = function( elem, options, callback, args ) { function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, - scale = 1, + var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { @@ -4548,35 +4565,39 @@ function adjustCSS( elem, prop, valueParts, tween ) { unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches - initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + 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 ]; - // Make sure we update the tween properties later on - valueParts = valueParts || []; - // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; - do { - - // If previous iteration zeroed out, double until we get *something*. - // Use string for doubling so we don't accidentally see scale as unchanged below - scale = scale || ".5"; + while ( maxIterations-- ) { - // Adjust and apply - initialInUnit = initialInUnit / scale; + // 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; - // Update scale, tolerating zero or NaN from tween.cur() - // Break the loop if scale is unchanged or perfect, or if we've just had enough. - } while ( - scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations - ); + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; } if ( valueParts ) { @@ -4692,9 +4713,9 @@ jQuery.fn.extend( { } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); -var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); -var rscriptType = ( /^$|\/(?:java|ecma)script/i ); +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); @@ -4764,7 +4785,7 @@ function setGlobalEval( elems, refElements ) { var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, contains, j, + var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, @@ -4776,7 +4797,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) { if ( elem || elem === 0 ) { // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { + if ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit @@ -4828,13 +4849,13 @@ function buildFragment( elems, context, scripts, selection, ignored ) { continue; } - contains = jQuery.contains( elem.ownerDocument, elem ); + attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history - if ( contains ) { + if ( attached ) { setGlobalEval( tmp ); } @@ -4877,8 +4898,6 @@ function buildFragment( elems, context, scripts, selection, ignored ) { div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); -var documentElement = document.documentElement; - var @@ -4894,8 +4913,19 @@ 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 -// See #13393 for more info +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; @@ -5195,9 +5225,10 @@ jQuery.event = { while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + // 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; @@ -5286,7 +5317,7 @@ jQuery.event = { enumerable: true, configurable: true, - get: jQuery.isFunction( hook ) ? + get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); @@ -5321,39 +5352,51 @@ jQuery.event = { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, - focus: { + click: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; + // 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; }, - delegateType: "focusout" - }, - click: { + trigger: function( data ) { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { - this.click(); - return false; + // 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, don't fire native .click() on links + // 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 ) { - return nodeName( event.target, "a" ); + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); } }, @@ -5370,6 +5413,93 @@ jQuery.event = { } }; +// 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 @@ -5421,7 +5551,7 @@ jQuery.Event = function( src, props ) { } // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); + this.timeStamp = src && src.timeStamp || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; @@ -5482,6 +5612,7 @@ jQuery.each( { shiftKey: true, view: true, "char": true, + code: true, charCode: true, key: true, keyCode: true, @@ -5528,6 +5659,33 @@ jQuery.each( { } }, 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 @@ -5620,14 +5778,13 @@ var /* eslint-enable */ - // Support: IE <=10 - 11, Edge 12 - 13 + // 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 @@ -5635,7 +5792,7 @@ function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - return jQuery( ">tbody", elem )[ 0 ] || elem; + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; @@ -5647,10 +5804,8 @@ function disableScript( elem ) { return elem; } function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } @@ -5716,15 +5871,15 @@ function domManip( collection, args, callback, ignored ) { l = collection.length, iNoClone = l - 1, value = args[ 0 ], - isFunction = jQuery.isFunction( value ); + valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || + if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); - if ( isFunction ) { + if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); @@ -5778,14 +5933,16 @@ function domManip( collection, args, callback, ignored ) { !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - if ( node.src ) { + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + } ); } } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } @@ -5807,7 +5964,7 @@ function remove( elem, selector, keepData ) { } if ( node.parentNode ) { - if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); @@ -5825,7 +5982,7 @@ jQuery.extend( { clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); + inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && @@ -6065,8 +6222,6 @@ jQuery.each( { return this.pushStack( ret ); }; } ); -var rmargin = ( /^margin/ ); - var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { @@ -6083,6 +6238,8 @@ var getStyles = function( elem ) { return view.getComputedStyle( elem ); }; +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + ( function() { @@ -6096,25 +6253,35 @@ var getStyles = function( elem ) { return; } + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; div.style.cssText = - "box-sizing:border-box;" + - "position:relative;display:block;" + + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + - "top:1%;width:50%"; - div.innerHTML = ""; - documentElement.appendChild( container ); + "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 = divStyle.marginLeft === "2px"; - boxSizingReliableVal = divStyle.width === "4px"; + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - // Support: Android 4.0 - 4.3 only + // 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.marginRight = "50%"; - pixelMarginRightVal = divStyle.marginRight === "4px"; + 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 ); @@ -6123,7 +6290,12 @@ var getStyles = function( elem ) { div = null; } - var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); @@ -6138,26 +6310,26 @@ var getStyles = function( elem ) { div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; - container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + - "padding:0;margin-top:1px;position:absolute"; - container.appendChild( div ); - jQuery.extend( support, { - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, - pixelMarginRight: function() { + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { computeStyleTests(); - return pixelMarginRightVal; + return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; } } ); } )(); @@ -6180,7 +6352,7 @@ function curCSS( elem, name, computed ) { if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } @@ -6189,7 +6361,7 @@ function curCSS( elem, name, computed ) { // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { // Remember the original values width = style.width; @@ -6236,30 +6408,13 @@ function addGetHookIf( conditionFn, hookFn ) { } -var +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; - // 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" - }, - - cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style; - -// Return a css property mapped to a potentially vendor prefixed property +// Return a vendor-prefixed property or undefined function vendorPropName( name ) { - // Shortcut for names that are not vendor prefixed - if ( name in emptyStyle ) { - return name; - } - // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; @@ -6272,16 +6427,33 @@ function vendorPropName( name ) { } } -// Return a property mapped along what jQuery.cssProps suggests or to -// a vendor prefixed property. +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property function finalPropName( name ) { - var ret = jQuery.cssProps[ name ]; - if ( !ret ) { - ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; } - return ret; + 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 @@ -6294,87 +6466,137 @@ function setPositiveNumber( elem, value, subtract ) { value; } -function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { - var i, - val = 0; - - // If we already have the right measurement, avoid augmentation - if ( extra === ( isBorderBox ? "border" : "content" ) ) { - i = 4; +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; - // Otherwise initialize for horizontal or vertical properties - } else { - i = name === "width" ? 1 : 0; + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; } for ( ; i < 4; i += 2 ) { - // Both box models exclude margin, so add it if we want it - if ( extra === "margin" ) { - val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } - if ( isBorderBox ) { + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { - // border-box includes padding, so remove it if we want content - if ( extra === "content" ) { - val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } + // 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 ); - // At this point, extra isn't border nor margin, so remove border - if ( extra !== "margin" ) { - val -= 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 { - // At this point, extra isn't content, so add padding - val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } - // At this point, extra isn't content nor padding, so add border - if ( extra !== "padding" ) { - val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } - return val; + // 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, name, extra ) { +function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style - var valueIsBorderBox, - styles = getStyles( elem ), - val = curCSS( elem, name, styles ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + 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 ); - // Computed unit is not pixels. Stop here and return. + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { - return val; + if ( !extra ) { + return val; + } + val = "auto"; } - // Check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = isBorderBox && - ( support.boxSizingReliable() || val === elem.style[ name ] ); - // Fall back to offsetWidth/Height when value is "auto" + // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) - if ( val === "auto" ) { - val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + // Support: IE 9-11 only + // Also use offsetWidth/offsetHeight for when box sizing is unreliable + // We use getClientRects() to check for hidden/disconnected. + // In those cases, the computed value can be trusted to be border-box + if ( ( !support.boxSizingReliable() && isBorderBox || + val === "auto" || + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + 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 "", auto, and prepare for extra + // Normalize "" and auto val = parseFloat( val ) || 0; - // Use the active box-sizing model to add/subtract irrelevant styles + // Adjust for the element's box model return ( val + - augmentWidthOrHeight( + boxModelAdjustment( elem, - name, + dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, - styles + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val ) ) + "px"; } @@ -6404,6 +6626,13 @@ jQuery.extend( { "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, @@ -6415,9 +6644,7 @@ jQuery.extend( { // Add in properties whose names you wish to fix before // setting or getting the value - cssProps: { - "float": "cssFloat" - }, + cssProps: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { @@ -6429,7 +6656,7 @@ jQuery.extend( { // Make sure that we're working with the right name var ret, type, hooks, - origName = jQuery.camelCase( name ), + origName = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; @@ -6461,7 +6688,9 @@ jQuery.extend( { } // If a number was passed in, add the unit (except for certain CSS properties) - if ( type === "number" ) { + // 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" ); } @@ -6497,7 +6726,7 @@ jQuery.extend( { css: function( elem, name, extra, styles ) { var val, num, hooks, - origName = jQuery.camelCase( name ), + origName = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't @@ -6535,8 +6764,8 @@ jQuery.extend( { } } ); -jQuery.each( [ "height", "width" ], function( i, name ) { - jQuery.cssHooks[ name ] = { +jQuery.each( [ "height", "width" ], function( i, dimension ) { + jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { @@ -6552,29 +6781,52 @@ jQuery.each( [ "height", "width" ], function( i, name ) { // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { - return getWidthOrHeight( elem, name, extra ); + return getWidthOrHeight( elem, dimension, extra ); } ) : - getWidthOrHeight( elem, name, extra ); + getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, - styles = extra && getStyles( elem ), - subtract = extra && augmentWidthOrHeight( - elem, - name, - extra, + 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", - styles + 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[ name ] = value; - value = jQuery.css( elem, name ); + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); @@ -6618,7 +6870,7 @@ jQuery.each( { } }; - if ( !rmargin.test( prefix ) ) { + if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); @@ -6728,9 +6980,9 @@ Tween.propHooks = { // 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 && - ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || - jQuery.cssHooks[ tween.prop ] ) ) { + } 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; @@ -6789,7 +7041,7 @@ function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); - return ( fxNow = jQuery.now() ); + return ( fxNow = Date.now() ); } // Generate parameters to create a standard animation @@ -6893,9 +7145,10 @@ function defaultPrefilter( elem, props, opts ) { // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { - // Support: IE <=9 - 11, Edge 12 - 13 + // 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 + // 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 @@ -7003,7 +7256,7 @@ function propFilter( props, specialEasing ) { // camelCase, specialEasing and expand cssHook pass for ( index in props ) { - name = jQuery.camelCase( index ); + name = camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { @@ -7128,9 +7381,9 @@ function Animation( elem, properties, options ) { for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { - if ( jQuery.isFunction( result.stop ) ) { + if ( isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - jQuery.proxy( result.stop, result ); + result.stop.bind( result ); } return result; } @@ -7138,7 +7391,7 @@ function Animation( elem, properties, options ) { jQuery.map( props, createTween, animation ); - if ( jQuery.isFunction( animation.opts.start ) ) { + if ( isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } @@ -7171,7 +7424,7 @@ jQuery.Animation = jQuery.extend( Animation, { }, tweener: function( props, callback ) { - if ( jQuery.isFunction( props ) ) { + if ( isFunction( props ) ) { callback = props; props = [ "*" ]; } else { @@ -7203,9 +7456,9 @@ jQuery.Animation = jQuery.extend( Animation, { jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || - jQuery.isFunction( speed ) && speed, + isFunction( speed ) && speed, duration: speed, - easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + easing: fn && easing || easing && !isFunction( easing ) && easing }; // Go to the end state if fx are off @@ -7232,7 +7485,7 @@ jQuery.speed = function( speed, easing, fn ) { opt.old = opt.complete; opt.complete = function() { - if ( jQuery.isFunction( opt.old ) ) { + if ( isFunction( opt.old ) ) { opt.old.call( this ); } @@ -7396,7 +7649,7 @@ jQuery.fx.tick = function() { i = 0, timers = jQuery.timers; - fxNow = jQuery.now(); + fxNow = Date.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; @@ -7749,7 +8002,7 @@ jQuery.each( [ // Strip and collapse whitespace according to HTML spec - // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); @@ -7760,20 +8013,30 @@ 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 ( jQuery.isFunction( value ) ) { + if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; + classes = classesToArray( value ); + if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); @@ -7802,7 +8065,7 @@ jQuery.fn.extend( { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; - if ( jQuery.isFunction( value ) ) { + if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); @@ -7812,9 +8075,9 @@ jQuery.fn.extend( { return this.attr( "class", "" ); } - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; + classes = classesToArray( value ); + if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); @@ -7844,13 +8107,14 @@ jQuery.fn.extend( { }, toggleClass: function( value, stateVal ) { - var type = typeof value; + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); - if ( typeof stateVal === "boolean" && type === "string" ) { + if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } - if ( jQuery.isFunction( value ) ) { + if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), @@ -7862,12 +8126,12 @@ jQuery.fn.extend( { return this.each( function() { var className, i, self, classNames; - if ( type === "string" ) { + if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); - classNames = value.match( rnothtmlwhite ) || []; + classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { @@ -7926,7 +8190,7 @@ var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { - var hooks, ret, isFunction, + var hooks, ret, valueIsFunction, elem = this[ 0 ]; if ( !arguments.length ) { @@ -7955,7 +8219,7 @@ jQuery.fn.extend( { return; } - isFunction = jQuery.isFunction( value ); + valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; @@ -7964,7 +8228,7 @@ jQuery.fn.extend( { return; } - if ( isFunction ) { + if ( valueIsFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; @@ -8106,18 +8370,24 @@ jQuery.each( [ "radio", "checkbox" ], function() { // Return jQuery for attributes-only inclusion -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; +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, + 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 = tmp = elem = elem || document; + cur = lastElement = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { @@ -8169,7 +8439,7 @@ jQuery.extend( jQuery.event, { // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { @@ -8189,7 +8459,7 @@ jQuery.extend( jQuery.event, { // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - + lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; @@ -8221,7 +8491,7 @@ jQuery.extend( jQuery.event, { // 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 && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; @@ -8232,7 +8502,17 @@ jQuery.extend( jQuery.event, { // 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 ) { @@ -8278,31 +8558,6 @@ jQuery.fn.extend( { } ); -jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup contextmenu" ).split( " " ), - function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; -} ); - -jQuery.fn.extend( { - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -} ); - - - - -support.focusin = "onfocusin" in window; - - // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 @@ -8346,7 +8601,7 @@ if ( !support.focusin ) { } var location = window.location; -var nonce = jQuery.now(); +var nonce = Date.now(); var rquery = ( /\?/ ); @@ -8404,7 +8659,7 @@ function buildParams( prefix, obj, traditional, add ) { } } ); - } else if ( !traditional && jQuery.type( obj ) === "object" ) { + } else if ( !traditional && toType( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { @@ -8426,7 +8681,7 @@ jQuery.param = function( a, traditional ) { add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value - var value = jQuery.isFunction( valueOrFunction ) ? + var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; @@ -8434,6 +8689,10 @@ jQuery.param = function( a, traditional ) { 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 ) ) ) { @@ -8544,7 +8803,7 @@ function addToPrefiltersOrTransports( structure ) { i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - if ( jQuery.isFunction( func ) ) { + if ( isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { @@ -8936,12 +9195,14 @@ jQuery.extend( { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); } } - match = responseHeaders[ key.toLowerCase() ]; + match = responseHeaders[ key.toLowerCase() + " " ]; } - return match == null ? null : match; + return match == null ? null : match.join( ", " ); }, // Raw string @@ -9016,7 +9277,7 @@ jQuery.extend( { if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); - // Support: IE <=8 - 11, Edge 12 - 13 + // 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 { @@ -9074,8 +9335,8 @@ jQuery.extend( { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); - // If data is available, append data to url - if ( s.data ) { + // 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 @@ -9312,7 +9573,7 @@ jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted - if ( jQuery.isFunction( data ) ) { + if ( isFunction( data ) ) { type = type || callback; callback = data; data = undefined; @@ -9330,7 +9591,7 @@ jQuery.each( [ "get", "post" ], function( i, method ) { } ); -jQuery._evalUrl = function( url ) { +jQuery._evalUrl = function( url, options ) { return jQuery.ajax( { url: url, @@ -9340,7 +9601,16 @@ jQuery._evalUrl = function( url ) { cache: true, async: false, global: false, - "throws": true + + // 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 ); + } } ); }; @@ -9350,7 +9620,7 @@ jQuery.fn.extend( { var wrap; if ( this[ 0 ] ) { - if ( jQuery.isFunction( html ) ) { + if ( isFunction( html ) ) { html = html.call( this[ 0 ] ); } @@ -9376,7 +9646,7 @@ jQuery.fn.extend( { }, wrapInner: function( html ) { - if ( jQuery.isFunction( html ) ) { + if ( isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); @@ -9396,10 +9666,10 @@ jQuery.fn.extend( { }, wrap: function( html ) { - var isFunction = jQuery.isFunction( html ); + var htmlIsFunction = isFunction( html ); return this.each( function( i ) { - jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, @@ -9491,7 +9761,8 @@ jQuery.ajaxTransport( function( options ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); @@ -9531,7 +9802,7 @@ jQuery.ajaxTransport( function( options ) { // Listen to events xhr.onload = callback(); - errorCallback = xhr.onerror = callback( "error" ); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort @@ -9622,24 +9893,21 @@ jQuery.ajaxPrefilter( "script", function( s ) { // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { - // This transport only deals with cross domain requests - if ( s.crossDomain ) { + // 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( "