diff --git a/.buildinfo b/.buildinfo new file mode 100644 index 00000000..f4b8801b --- /dev/null +++ b/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 4c0ac0660cdd42b8acbddd695a2e685a +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png b/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png new file mode 100644 index 00000000..e8f9d8c8 Binary files /dev/null and b/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png differ diff --git a/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png.map b/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png.map new file mode 100644 index 00000000..1efeb65c --- /dev/null +++ b/_images/graphviz-019d1949f1c9a290f30e505fcdce056c16aeb472.png.map @@ -0,0 +1,2 @@ + + diff --git a/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png b/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png new file mode 100644 index 00000000..4fbf8cc4 Binary files /dev/null and b/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png differ diff --git a/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png.map b/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png.map new file mode 100644 index 00000000..4f7a46b5 --- /dev/null +++ b/_images/graphviz-22af22e7c09fd95f8bc28d79fa6666749aacf8ce.png.map @@ -0,0 +1,2 @@ + + diff --git a/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png b/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png new file mode 100644 index 00000000..fd09362c Binary files /dev/null and b/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png differ diff --git a/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png.map b/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png.map new file mode 100644 index 00000000..26adf723 --- /dev/null +++ b/_images/graphviz-4dcebfccd2ce68d5093108f3f5eab93483966240.png.map @@ -0,0 +1,2 @@ + + diff --git a/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png b/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png new file mode 100644 index 00000000..aa5c9160 Binary files /dev/null and b/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png differ diff --git a/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png.map b/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png.map new file mode 100644 index 00000000..2c22b3de --- /dev/null +++ b/_images/graphviz-b66706818f80f09045248e99cee994119fb0a213.png.map @@ -0,0 +1,2 @@ + + diff --git a/_modules/index.html b/_modules/index.html new file mode 100644 index 00000000..445b488b --- /dev/null +++ b/_modules/index.html @@ -0,0 +1,125 @@ + + + + + + + + Overview: module code — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/client/raw.html b/_modules/p4p/client/raw.html new file mode 100644 index 00000000..bd15e43a --- /dev/null +++ b/_modules/p4p/client/raw.html @@ -0,0 +1,390 @@ + + + + + + + + p4p.client.raw — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.client.raw

+
+from __future__ import print_function
+
+import logging
+_log = logging.getLogger(__name__)
+
+import warnings
+import sys
+
+try:
+    from Queue import Queue, Full, Empty
+except ImportError:
+    from queue import Queue, Full, Empty
+
+from .. import _p4p
+from .._p4p import Cancelled, Disconnected, Finished, RemoteError
+
+from ..wrapper import Value, Type
+from ..nt import buildNT
+
+if sys.version_info >= (3, 0):
+    unicode = str
+
+__all__ = (
+    'Subscription',
+    'Context',
+    'RemoteError',
+)
+
+
+def unwrapHandler(handler, nt):
+    """Wrap get/rpc handler to unwrap Value
+    """
+    def dounwrap(code, msg, val, handler=handler):
+        _log.debug("Handler (%s, %s, %r) -> %s", code, msg, val, handler)
+        try:
+            if code == 0:
+                handler(RemoteError(msg))
+            elif code == 1:
+                handler(Cancelled())
+            elif code == 2: # exception during builder callback
+                A, B, C = val
+                if unicode is str:
+                    E = A(B).with_traceback(C) # py 3
+                else:
+                    E = A(B) # py 2 (bye bye traceback...)
+                handler(E)
+            else:
+                if val is not None:
+                    val = nt.unwrap(val)
+                handler(val)
+        except:
+            _log.exception("Exception in Operation handler")
+    return dounwrap
+
+
+def monHandler(handler):
+    def cb(handler=handler):
+        _log.debug("Update %s", handler)
+        try:
+            handler()
+        except:
+            _log.exception("Exception in Monitor handler")
+    return cb
+
+
+def defaultBuilder(value, nt):
+    """Reasonably sensible default handling of put builder
+    """
+    if callable(value):
+        return value
+
+    def builder(V):
+        if isinstance(value, Value):
+            V[None] = value
+        elif isinstance(value, dict):
+            for k, v in value.items():
+                V[k] = v
+        else:
+            nt.assign(V, value)
+    return builder
+
+
+def wrapRequest(request):
+    if request is None or isinstance(request, Value):
+        return request
+    return Context.makeRequest(request)
+
+
+
[docs]class Subscription(_p4p.ClientMonitor): + + """Interface to monitor subscription FIFO + + Use method poll() to try to pop an item from the FIFO. + None indicates the FIFO is empty, must wait for another Data event before + calling poll() again. + + complete()==True after poll()==False indicates that no more updates will + ever be forthcoming. This is normal (not error) completion. + + cancel() aborts the subscription. + """ + + def __init__(self, context, name, nt, **kws): + _log.debug("Subscription(%s)", kws) + super(Subscription, self).__init__(context, name, **kws) + self.context = context + self._nt = nt + self.done = False + + def pop(self): + val = super(Subscription, self).pop() + assert val is None or isinstance(val, (Value, Exception)), val + if isinstance(val, Value): + val = self._nt.unwrap(val) + elif isinstance(val, Finished): + self.done = True + _log.debug("poll() -> %r", val) + return val + + def complete(self): + return self.done + + def __enter__(self): + return self + + def __exit__(self, A, B, C): + self.close() + + if unicode is str: + def __del__(self): + self.close()
+ +
[docs]class Context(object): + + """ + :param str provider: A Provider name. Try "pva" or run :py:meth:`Context.providers` for a complete list. + :param conf dict: Configuration to pass to provider. Depends on provider selected. + :param bool useenv: Allow the provider to use configuration from the process environment. + :param dict nt: Controls :ref:`unwrap`. None uses defaults. Set False to disable + :param dict unwrap: Legacy :ref:`unwrap`. + """ + + def __init__(self, provider='pva', conf=None, useenv=None, + unwrap=None, nt=None, + **kws): + self.name = provider + super(Context, self).__init__(**kws) + + self._nt = buildNT(nt, unwrap) + + self._ctxt = None + + self._ctxt = _ClientProvider(provider, conf=conf, useenv=useenv) + self.conf = self._ctxt.conf + self.hurryUp = self._ctxt.hurryUp + + makeRequest = _p4p.ClientProvider.makeRequest + + def close(self): + if self._ctxt is None: + return + + self._ctxt.close() + self._ctxt = None + + def __enter__(self): + return self + + def __exit__(self, A, B, C): + self.close() + +
[docs] def disconnect(self, name=None): + """Clear internal Channel cache, allowing currently unused channels to be implictly closed. + + :param str name: None, to clear the entire cache, or a name string to clear only a certain entry. + """ + self._ctxt.disconnect(name)
+ + def _request(self, process=None, wait=None): + """helper for building pvRequests + + :param str process: Control remote processing. May be 'true', 'false', 'passive', or None. + :param bool wait: Wait for all server processing to complete. + """ + opts = [] + if process is not None: + opts.append('process=%s' % process) + if wait is not None: + if wait: + opts.append('wait=true') + else: + opts.append('wait=false') + return 'field()record[%s]' % (','.join(opts)) + +
[docs] def get(self, name, handler, request=None): + """Begin Fetch of current value of a PV + + :param name: A single name string or list of name strings + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param callable handler: Completion notification. Called with a Value, RemoteError, or Cancelled + + :returns: A object with a method cancel() which may be used to abort the operation. + """ + return _ClientOperation(self._ctxt, name, handler=unwrapHandler(handler, self._nt), + pvRequest=wrapRequest(request), get=True, put=False)
+ +
[docs] def put(self, name, handler, builder=None, request=None, get=True): + """Write a new value to a PV. + + :param name: A single name string or list of name strings + :param callable handler: Completion notification. Called with None (success), RemoteError, or Cancelled + :param callable builder: Called when the PV Put type is known. A builder is responsible + for filling in the Value to be sent. builder(value) + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param bool get: Whether to do a Get before the Put. If True then the value passed to the builder callable + will be initialized with recent PV values. eg. use this with NTEnum to find the enumeration list. + + :returns: A object with a method cancel() which may be used to abort the operation. + """ + return _ClientOperation(self._ctxt, name, handler=unwrapHandler(handler, self._nt), + builder=defaultBuilder(builder, self._nt), + pvRequest=wrapRequest(request), get=get, put=True)
+ +
[docs] def rpc(self, name, handler, value, request=None): + """Perform RPC operation on PV + + :param name: A single name string or list of name strings + :param callable handler: Completion notification. Called with a Value, RemoteError, or Cancelled + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + + :returns: A object with a method cancel() which may be used to abort the operation. + """ + if value is None: + value = Value(Type([])) + return _ClientOperation(self._ctxt, name, handler=unwrapHandler(handler, self._nt), + value=value, pvRequest=wrapRequest(request), rpc=True)
+ +
[docs] def monitor(self, name, handler, request=None, **kws): + """Begin subscription to named PV + + :param str name: PV name string + :param callable handler: Completion notification. Called with None (FIFO not empty), RemoteError, Cancelled, or Disconnected + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param bool notify_disconnect: Whether disconnect (and done) notifications are delivered to the callback (as None). + + :returns: A Subscription + """ + return Subscription(self._ctxt, name, + nt=self._nt, + handler=monHandler(handler), pvRequest=wrapRequest(request), + **kws)
+ +
[docs] @staticmethod + def providers(): + return ["pva"]
+ +
[docs] @staticmethod + def set_debug(lvl): + _p4p.set_debug(lvl)
+ +set_debug = _p4p.logger_level_set + +def _cleanup_contexts(): + contexts = list(_p4p.all_providers) + _log.debug("Closing %d Client contexts", len(contexts)) + for ctxt in contexts: + ctxt.close() + +class _ClientOperation(_p4p.ClientOperation): + if unicode is str: + def __del__(self): + self.close() + +class _ClientProvider(_p4p.ClientProvider): + if unicode is str: + def __del__(self): + self.close() +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/client/thread.html b/_modules/p4p/client/thread.html new file mode 100644 index 00000000..27e3a6f9 --- /dev/null +++ b/_modules/p4p/client/thread.html @@ -0,0 +1,548 @@ + + + + + + + + p4p.client.thread — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.client.thread

+
+from __future__ import print_function
+
+import logging
+import sys
+_log = logging.getLogger(__name__)
+
+try:
+    from itertools import izip
+except ImportError:
+    izip = zip
+from functools import partial
+import json
+import threading
+
+try:
+    from Queue import Queue, Full, Empty
+except ImportError:
+    from queue import Queue, Full, Empty
+
+from . import raw
+from .raw import Disconnected, RemoteError, Cancelled, Finished
+from ..util import _defaultWorkQueue
+from ..wrapper import Value, Type
+from ..rpc import WorkQueue
+from .._p4p import (logLevelAll, logLevelTrace, logLevelDebug,
+                    logLevelInfo, logLevelWarn, logLevelError,
+                    logLevelFatal, logLevelOff)
+
+__all__ = [
+    'Context',
+    'Value',
+    'Type',
+    'RemoteError',
+    'TimeoutError',
+]
+
+if sys.version_info >= (3, 0):
+    unicode = str
+    TimeoutError = TimeoutError
+
+else:
+    class TimeoutError(RuntimeError):
+        "Local timeout has expired"
+        def __init__(self):
+            RuntimeError.__init__(self, 'Timeout')
+
+
+
[docs]class Subscription(object): + """An active subscription. + + Returned by `Context.monitor`. + """ + + def __init__(self, ctxt, name, cb, notify_disconnect=False, queue=None): + self.name, self._S, self._cb = name, None, cb + self._notify_disconnect = notify_disconnect + self._Q = queue or ctxt._Q or _defaultWorkQueue() + if notify_disconnect: + # all subscriptions are inittially disconnected + self._Q.push_wait(partial(cb, Disconnected())) + +
[docs] def close(self): + """Close subscription. + """ + if self._S is not None: + # after .close() self._event should never be called + self._S.close() + self._S = None
+ + def __enter__(self): + return self + + def __exit__(self, A, B, C): + self.close() + + @property + def done(self): + 'Has all data for this subscription been received?' + return self._S is None or self._S.done() + + @property + def empty(self): + 'Is data pending in event queue?' + return self._S is None or self._S.empty() + + def _event(self): + try: + assert self._S is not None, self._S + _log.debug('Subscription wakeup for %s', self.name) + self._Q.push(self._handle) + except: + _log.exception("Lost Subscription update for %s", self.name) + + def _handle(self): + try: + S = self._S + if S is None: # already close()'d + return + + for n in range(4): + E = S.pop() + if E is None: + break # monitor queue empty + + elif isinstance(E, Exception): + _log.debug('Subscription notify for %s with %s', self.name, E) + if self._notify_disconnect: + self._cb(E) + + elif isinstance(E, RemoteError): + _log.error("Subscription Error %s", E) + + if isinstance(E, Finished): + _log.debug('Subscription complete %s', self.name) + self._S = None + S.close() + + else: + self._cb(E) + + if E is not None: + # removed 4 elements without emptying queue + # re-schedule to mux with others + self._Q.push(self._handle) + + except: + _log.exception("Error processing Subscription event for %s", self.name) + if self._S is not None: + self._S.close() + self._S = None
+ + +
[docs]class Context(raw.Context): + + """Context(provider, conf=None, useenv=True) + + :param str provider: A Provider name. Try "pva" or run :py:meth:`Context.providers` for a complete list. + :param dict conf: Configuration to pass to provider. Depends on provider selected. + :param bool useenv: Allow the provider to use configuration from the process environment. + :param int workers: Size of thread pool in which monitor callbacks are run. Default is 4 + :param int maxsize: Size of internal work queue used for monitor callbacks. Default is unlimited + :param dict nt: Controls :ref:`unwrap`. None uses defaults. Set False to disable + :param dict unwrap: Legacy :ref:`unwrap`. + :param WorkQueue queue: A work queue through which monitor callbacks are dispatched. + + The methods of this Context will block the calling thread until completion or timeout + + The meaning, and allowed keys, of the configuration dictionary depend on the provider. + conf= will override values taken from the process environment. Pass useenv=False to + ensure that environment variables are completely ignored. + + The "pva" provider understands the following keys: + + * EPICS_PVA_ADDR_LIST + * EPICS_PVA_AUTO_ADDR_LIST + * EPICS_PVA_SERVER_PORT + * EPICS_PVA_BROADCAST_PORT + """ + Value = Value + + name = '' + "Provider name string" + + def __init__(self, provider='pva', conf=None, useenv=True, nt=None, unwrap=None, + maxsize=0, queue=None): + self._channel_lock = threading.Lock() + + super(Context, self).__init__(provider, conf=conf, useenv=useenv, nt=nt, unwrap=unwrap) + + # lazy start threaded WorkQueue + self._Q = self._T = None + + self._Q = queue + + def _channel(self, name): + with self._channel_lock: + return super(Context, self)._channel(name) + +
[docs] def disconnect(self, *args, **kws): + with self._channel_lock: + super(Context, self).disconnect(*args, **kws)
+ + def _queue(self): + if self._Q is None: + Q = WorkQueue(maxsize=self._Qmax) + Ts = [] + for n in range(self._Wcnt): + T = threading.Thread(name='p4p Context worker', target=Q.handle) + T.daemon = True + Ts.append(T) + for T in Ts: + T.start() + _log.debug('Started %d Context worker', self._Wcnt) + self._Q, self._T = Q, Ts + return self._Q + +
[docs] def close(self): + """Force close all Channels and cancel all Operations + """ + if self._Q is not None: + for T in self._T: + self._Q.interrupt() + for n, T in enumerate(self._T): + _log.debug('Join Context worker %d', n) + T.join() + _log.debug('Joined Context workers') + self._Q, self._T = None, None + if not Context: + # Python 2.7 GC removes Context from scope during destruction of objects. + return + super(Context, self).close()
+ +
[docs] def get(self, name, request=None, timeout=5.0, throw=True): + """Fetch current value of some number of PVs. + + :param name: A single name string or list of name strings + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param float timeout: Operation timeout in seconds + :param bool throw: When true, operation error throws an exception. If False then the Exception is returned instead of the Value + + :returns: A p4p.Value or Exception, or list of same. Subject to :py:ref:`unwrap`. + + When invoked with a single name then returns is a single value. + When invoked with a list of name, then returns a list of values + + >>> ctxt = Context('pva') + >>> V = ctxt.get('pv:name') + >>> A, B = ctxt.get(['pv:1', 'pv:2']) + >>> + """ + singlepv = isinstance(name, (bytes, unicode)) + if singlepv: + name = [name] + request = [request] + + elif request is None: + request = [None] * len(name) + + assert len(name) == len(request), (name, request) + + # use Queue instead of Event to allow KeyboardInterrupt + done = Queue() + result = [TimeoutError()] * len(name) + ops = [None] * len(name) + + raw_get = super(Context, self).get + + try: + for i, (N, req) in enumerate(izip(name, request)): + def cb(value, i=i): + try: + if not isinstance(value, Cancelled): + done.put_nowait((value, i)) + _log.debug('get %s Q %r', N, value) + except: + _log.exception("Error queuing get result %s", value) + + _log.debug('get %s w/ %s', N, req) + ops[i] = raw_get(N, cb, request=req) + + for _n in range(len(name)): + try: + value, i = done.get(timeout=timeout) + except Empty: + if throw: + _log.debug('timeout %s after %s', name[i], timeout) + raise TimeoutError() + break + _log.debug('got %s %r', name[i], value) + if throw and isinstance(value, Exception): + raise value + result[i] = value + + finally: + [op and op.close() for op in ops] + + if singlepv: + return result[0] + else: + return result
+ +
[docs] def put(self, name, values, request=None, timeout=5.0, throw=True, + process=None, wait=None, get=True): + """Write a new value of some number of PVs. + + :param name: A single name string or list of name strings + :param values: A single value, a list of values, a dict, a `Value`. May be modified by the constructor nt= argument. + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param float timeout: Operation timeout in seconds + :param bool throw: When true, operation error throws an exception. + If False then the Exception is returned instead of the Value + :param str process: Control remote processing. May be 'true', 'false', 'passive', or None. + :param bool wait: Wait for all server processing to complete. + :param bool get: Whether to do a Get before the Put. If True then the value passed to the builder callable + will be initialized with recent PV values. eg. use this with NTEnum to find the enumeration list. + + :returns: A None or Exception, or list of same + + When invoked with a single name then returns is a single value. + When invoked with a list of name, then returns a list of values + + If 'wait' or 'process' is specified, then 'request' must be omitted or None. + + >>> ctxt = Context('pva') + >>> ctxt.put('pv:name', 5.0) + >>> ctxt.put(['pv:1', 'pv:2'], [1.0, 2.0]) + >>> ctxt.put('pv:name', {'value':5}) + >>> + + The provided value(s) will be automatically coerced to the target type. + If this is not possible then an Exception is raised/returned. + + Unless the provided value is a dict, it is assumed to be a plain value + and an attempt is made to store it in '.value' field. + """ + singlepv = isinstance(name, (bytes, unicode)) + if request and (process or wait is not None): + raise ValueError("request= is mutually exclusive to process= or wait=") + elif process or wait is not None: + request = 'field()record[block=%s,process=%s]' % ('true' if wait else 'false', process or 'passive') + if not singlepv: + request = [request]*len(name) + + if singlepv: + name = [name] + values = [values] + request = [request] + + elif request is None: + request = [None] * len(name) + + assert len(name) == len(request), (name, request) + assert len(name) == len(values), (name, values) + + # use Queue instead of Event to allow KeyboardInterrupt + done = Queue() + result = [TimeoutError()] * len(name) + ops = [None] * len(name) + + raw_put = super(Context, self).put + + try: + for i, (n, value, req) in enumerate(izip(name, values, request)): + if isinstance(value, (bytes, unicode)) and value[:1] == '{': + try: + value = json.loads(value) + except ValueError: + raise ValueError("Unable to interpret '%s' as json" % value) + + # completion callback + def cb(value, i=i): + try: + done.put_nowait((value, i)) + except: + _log.exception("Error queuing put result %r", value) + + ops[i] = raw_put(n, cb, builder=value, request=req, get=get) + + for _n in range(len(name)): + try: + value, i = done.get(timeout=timeout) + except Empty: + if throw: + raise TimeoutError() + break + if throw and isinstance(value, Exception): + raise value + result[i] = value + + if singlepv: + return result[0] + else: + return result + finally: + [op and op.close() for op in ops]
+ +
[docs] def rpc(self, name, value, request=None, timeout=5.0, throw=True): + """Perform a Remote Procedure Call (RPC) operation + + :param str name: PV name string + :param Value value: Arguments. Must be Value instance + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param float timeout: Operation timeout in seconds + :param bool throw: When true, operation error throws an exception. + If False then the Exception is returned instead of the Value + + :returns: A Value or Exception. Subject to :py:ref:`unwrap`. + + >>> ctxt = Context('pva') + >>> ctxt.rpc('pv:name:add', {'A':5, 'B'; 6}) + >>> + + The provided value(s) will be automatically coerced to the target type. + If this is not possible then an Exception is raised/returned. + + Unless the provided value is a dict, it is assumed to be a plain value + and an attempt is made to store it in '.value' field. + """ + done = Queue() + + op = super(Context, self).rpc(name, done.put_nowait, value, request=request) + + try: + try: + result = done.get(timeout=timeout) + except Empty: + result = TimeoutError() + if throw and isinstance(result, Exception): + raise result + + return result + except: + op.close() + raise
+ +
[docs] def monitor(self, name, cb, request=None, notify_disconnect=False, queue=None): + """Create a subscription. + + :param str name: PV name string + :param callable cb: Processing callback + :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default. + :param bool notify_disconnect: In additional to Values, the callback may also be call with instances of Exception. + Specifically: Disconnected , RemoteError, or Cancelled + :param WorkQueue queue: A work queue through which monitor callbacks are dispatched. + :returns: a :py:class:`Subscription` instance + + The callable will be invoked with one argument which is either. + + * A p4p.Value (Subject to :py:ref:`unwrap`) + * A sub-class of Exception (Disconnected , RemoteError, or Cancelled) + """ + R = Subscription(self, name, cb, notify_disconnect=notify_disconnect, queue=queue) + + R._S = super(Context, self).monitor(name, R._event, request) + return R
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/nt.html b/_modules/p4p/nt.html new file mode 100644 index 00000000..59ddd930 --- /dev/null +++ b/_modules/p4p/nt.html @@ -0,0 +1,401 @@ + + + + + + + + p4p.nt — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.nt

+
+import logging
+_log = logging.getLogger(__name__)
+
+try:
+    from itertools import izip
+except ImportError:
+    izip = zip
+
+from collections import OrderedDict
+from ..wrapper import Type, Value
+from .common import timeStamp, alarm, NTBase
+from .scalar import NTScalar
+from .ndarray import NTNDArray
+from .enum import NTEnum
+
+__all__ = [
+    'NTScalar',
+    'NTEnum',
+    'NTMultiChannel',
+    'NTTable',
+    'NTNDArray',
+    'defaultNT',
+]
+
+_default_nt = {
+    "epics:nt/NTScalar:1.0": NTScalar,
+    "epics:nt/NTScalarArray:1.0": NTScalar,
+    "epics:nt/NTEnum:1.0": NTEnum,
+    "epics:nt/NTNDArray:1.0": NTNDArray,
+}
+
+
[docs]def defaultNT(): + """Returns a copy of the default NT helper mappings. + + :since: 3.1.0 + """ + return _default_nt.copy()
+ +class UnwrapOnly(object): + def __init__(self, unwrap): + self.unwrap = unwrap + def __call__(self): + return self # we are state-less + def wrap(self, V): + return V + +def buildNT(nt=None, unwrap=None): + if unwrap is False or nt is False: + return ClientUnwrapper({}) # disable use of wrappers + + if unwrap is not None: + # legacy + ret = {} # ignore new style + for ID,fn in (unwrap or {}).items(): + ret[ID] = UnwrapOnly(fn) + + else: + ret = dict(_default_nt) + ret.update(nt or {}) + + return ClientUnwrapper(ret) + +class ClientUnwrapper(object): + def __init__(self, nt=None): + self.nt = nt + self.id = None + self._wrap = self._unwrap = lambda x:x + self._assign = self._default_assign + def wrap(self, val, **kws): + """Pack a arbitrary python object into a Value + """ + return self._wrap(val, **kws) + def unwrap(self, val): + """Unpack a Value as some other python type + """ + if val.getID()!=self.id: + self._update(val) + return self._unwrap(val) + + def assign(self, V, value): + if V.getID()!=self.id: + self._update(V) + self._assign(V, value) + + def _update(self, val): + # type change + nt = self.nt.get(val.getID()) + if nt is not None: + nt = nt() # instancate + self._wrap, self._unwrap = nt.wrap, nt.unwrap + self._assign = nt.assign + self.id = val.getID() + else: + # reset + self._wrap = self._unwrap = lambda x:x + self._assign = self._default_assign + + def _default_assign(self, V, value): + V.value = value # assume NTScalar-like + + def __repr__(self): + return '%s(%s)'%(self.__class__.__name__, repr(self.nt)) + __str__ = __repr__ + +
[docs]class NTMultiChannel(NTBase): + + """Describes a structure holding the equivalent of a number of NTScalar + """ + Value = Value + +
[docs] @staticmethod + def buildType(valtype, extra=[]): + """Build a Type + + :param str valtype: A type code to be used with the 'value' field. Must be an array + :param list extra: A list of tuples describing additional non-standard fields + :returns: A :py:class:`Type` + """ + assert valtype[:1] == 'a', 'valtype must be an array' + return Type(id="epics:nt/NTMultiChannel:1.0", + spec=[ + ('value', valtype), + ('channelName', 'as'), + ('descriptor', 's'), + ('alarm', alarm), + ('timeStamp', timeStamp), + ('severity', 'ai'), + ('status', 'ai'), + ('message', 'as'), + ('secondsPastEpoch', 'al'), + ('nanoseconds', 'ai'), + ('userTag', 'ai'), + ('isConnected', 'a?'), + ] + extra)
+ + +
[docs]class NTTable(NTBase): + + """A generic table + + >>> table = NTTable.buildType(columns=[ + ('columnA', 'ai'), + ('columnB', 'as'), + ]) + """ + Value = Value + +
[docs] @staticmethod + def buildType(columns=[], extra=[]): + """Build a table + + :param list columns: List of column names and types. eg [('colA', 'd')] + :param list extra: A list of tuples describing additional non-standard fields + :returns: A :py:class:`Type` + """ + return Type(id="epics:nt/NTTable:1.0", + spec=[ + ('labels', 'as'), + ('value', ('S', None, columns)), + ('descriptor', 's'), + ('alarm', alarm), + ('timeStamp', timeStamp), + ] + extra)
+ + def __init__(self, columns=[], extra=[]): + self.labels = [] + C = [] + for col, type in columns: + if type[0] == 'a': + raise ValueError("NTTable column types may not be array") + C.append((col, 'a' + type)) + self.labels.append(col) + self.type = self.buildType(C, extra=extra) + +
[docs] def wrap(self, values, **kws): + """Pack an iterable of dict into a Value + + >>> T=NTTable([('A', 'ai'), ('B', 'as')]) + >>> V = T.wrap([ + {'A':42, 'B':'one'}, + {'A':43, 'B':'two'}, + ]) + """ + if isinstance(values, Value): + return values + else: + cols = dict([(L, []) for L in self.labels]) + try: + # unzip list of dict + for V in values: + for L in self.labels: + try: + cols[L].append(V[L]) + except (IndexError, KeyError): + pass + # allow omit empty columns + for L in self.labels: + V = cols[L] + if len(V) == 0: + del cols[L] + + try: + values = self.Value(self.type, { + 'labels': self.labels, + 'value': cols, + }) + except: + _log.error("Failed to encode '%s' with %s", cols, self.labels) + raise + except: + _log.exception("Failed to wrap: %s", values) + raise + return self._annotate(values, **kws)
+ +
[docs] @staticmethod + def unwrap(value): + """Iterate an NTTable + + :returns: An iterator yielding an OrderedDict for each column + """ + ret = [] + + # build lists of column names, and value + lbl, cols = [], [] + for cname, cval in value.value.items(): + lbl.append(cname) + cols.append(cval) + + # zip together column arrays to iterate over rows + for rval in izip(*cols): + # zip together column names and row values + ret.append(OrderedDict(zip(lbl, rval))) + + return ret
+ +
[docs]class NTURI(object): + +
[docs] @staticmethod + def buildType(args): + """Build NTURI + + :param list args: A list of tuples of query argument name and PVD type code. + + >>> I = NTURI([ + ('arg_a', 'I'), + ('arg_two', 's'), + ]) + """ + try: + return Type(id="epics:nt/NTURI:1.0", spec=[ + ('scheme', 's'), + ('authority', 's'), + ('path', 's'), + ('query', ('S', None, args)), + ]) + except Exception as e: + raise ValueError('Unable to build NTURI compatible type from %s' % args)
+ + def __init__(self, args): + self._args = list(args) + self.type = self.buildType(args) + +
[docs] def wrap(self, path, args=(), kws={}, scheme='', authority=''): + """Wrap argument values (tuple/list with optional dict) into Value + + :param str path: The PV name to which this call is made + :param tuple args: Ordered arguments + :param dict kws: Keyword arguments + :rtype: Value + """ + # build dict of argument name+value + AV = {} + AV.update([A for A in kws.items() if A[1] is not None]) + AV.update([(N, V) for (N, _T), V in zip(self._args, args)]) + + # list of argument name+type tuples for which a value was provided + AT = [A for A in self._args if A[0] in AV] + + T = self.buildType(AT) + try: + return Value(T, { + 'scheme': scheme, + 'authority': authority, + 'path': path, + 'query': AV, + }) + except Exception as e: + raise ValueError('Unable to initialize NTURI %s from %s using %s' % (AT, AV, self._args))
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/nt/ndarray.html b/_modules/p4p/nt/ndarray.html new file mode 100644 index 00000000..5f12df99 --- /dev/null +++ b/_modules/p4p/nt/ndarray.html @@ -0,0 +1,324 @@ + + + + + + + + p4p.nt.ndarray — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.nt.ndarray

+"""Helper for handling NTNDArray a la. areaDetector.
+
+Known attributes
+
+"ColorMode"   (inner-most left, as given in NDArray.cpp, numpy.ndarray.shape is reversed from this)
+ 0 - Mono   [Nx, Ny]
+ 1 - Bayer  [Nx, Ny]
+ 2 - RGB1   [3, Nx, Ny]
+ 3 - RGB2   [Nx, 3, Ny]
+ 4 - RGB3   [Nx, Ny, 3]
+ 5 - YUV444 ?
+ 6 - YUV422 ??
+ 7 - YUV411 ???
+"""
+
+import logging
+_log = logging.getLogger(__name__)
+
+import time
+import numpy
+
+from ..wrapper import Type, Value
+from .common import alarm, timeStamp, NTBase
+
+from .scalar import ntwrappercommon
+
+
+
[docs]class ntndarray(ntwrappercommon, numpy.ndarray): + """ + Augmented numpy.ndarray with additional attributes + + * .attrib - dictionary + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + + Keys in the ``attrib`` dictionary may be any python which may be stored in a PVA field, + including an arbitrary ``Value``. + However, special handling is attempted if the provided ``Value`` appears to be an NTScalar + or similar, in which case the .value, .alarm and .timeStamp are unpacked to the NTAttribute + and other fields are discarded. + """ + + def __init__(self, *args, **kws): + super(ntndarray, self).__init__(*args, **kws) + self.attrib = {} + + def _store(self, value): + ntwrappercommon._store(self, value) + self.attrib = {} + for elem in value.get('attribute', []): + self.attrib[elem.name] = elem.value + + # we will fail if dimension[] contains None s, or if + # the advertised shape isn't consistent with the pixel array length. + shape = [D.size for D in value.dimension] + shape.reverse() + + # in-place reshape! Isn't numpy fun + self.shape = shape or [0] # can't reshape if 0-d, so treat as 1-d if no dimensions provided + + return self
+ + +
[docs]class NTNDArray(NTBase): + """Representation of an N-dimensional array with meta-data + + Translates into `ntndarray` + """ + Value = Value + ntndarray = ntndarray + + # map numpy.dtype.char to .value union member name + _code2u = { + '?':'booleanValue', + 'b':'byteValue', + 'h':'shortValue', + 'i':'intValue', + 'l':'longValue', + 'B':'ubyteValue', + 'H':'ushortValue', + 'I':'uintValue', + 'L':'ulongValue', + 'f':'floatValue', + 'd':'doubleValue', + } + +
[docs] @classmethod + def buildType(klass, extra=[]): + """Build type + """ + ret = klass._default_type + if extra: + L = ret.aspy() + L.extend(extra) + ret = Type(L, ret.getID()) + return ret
+ + _default_type = Type([ + ('value', ('U', None, [ + ('booleanValue', 'a?'), + ('byteValue', 'ab'), + ('shortValue', 'ah'), + ('intValue', 'ai'), + ('longValue', 'al'), + ('ubyteValue', 'aB'), + ('ushortValue', 'aH'), + ('uintValue', 'aI'), + ('ulongValue', 'aL'), + ('floatValue', 'af'), + ('doubleValue', 'ad'), + ])), + ('codec', ('S', 'codec_t', [ + ('name', 's'), + ('parameters', 'v'), + ])), + ('compressedSize', 'l'), + ('uncompressedSize', 'l'), + ('uniqueId', 'i'), + ('dataTimeStamp', timeStamp), + ('alarm', alarm), + ('timeStamp', timeStamp), + ('dimension', ('aS', 'dimension_t', [ + ('size', 'i'), + ('offset', 'i'), + ('fullSize', 'i'), + ('binning', 'i'), + ('reverse', '?'), + ])), + ('attribute', ('aS', 'epics:nt/NTAttribute:1.0', [ + ('name', 's'), + ('value', 'v'), + ('tags', 'as'), + ('descriptor', 's'), + ('alarm', alarm), + ('timeStamp', timeStamp), + ('sourceType', 'i'), + ('source', 's'), + ])), + ], id='epics:nt/NTNDArray:1.0') + + def __init__(self, **kws): + self.type = self.buildType(**kws) + +
[docs] def wrap(self, value, **kws): + """Wrap numpy.ndarray as Value + """ + attrib = getattr(value, 'attrib', None) or kws.pop('attrib', None) or {} + + value = numpy.asarray(value) # loses any special/augmented attributes + dims = value.shape + + if 'ColorMode' not in attrib: + # attempt to infer color mode from shape + if value.ndim==2: + attrib['ColorMode'] = 0 # gray + + elif value.ndim==3: + for idx,dim in enumerate(reversed(dims)): # inner-most sent as left + if dim==3: # assume it's a color + attrib['ColorMode'] = 2 + idx # 2 - RGB1, 3 - RGB2, 4 - RGB3 + break # assume that the first is color, and any subsequent dim=3 is a thin ROI + else: + raise ValueError("Unable to deduce color dimension from shape %r"%dims) + + dataSize = value.nbytes + + return self._annotate(Value(self.type, { + 'value': (self._code2u[value.dtype.char], value.flatten()), + 'compressedSize': dataSize, + 'uncompressedSize': dataSize, + 'uniqueId': 0, + 'attribute': [translateNDAttribute(K,V) for K, V in attrib.items()], + 'dimension': [{'size': N, + 'offset': 0, + 'fullSize': N, + 'binning': 1, + 'reverse': False} for N in reversed(dims)], + }), **kws)
+ +
[docs] @classmethod + def unwrap(klass, value): + """Unwrap Value as NTNDArray + """ + V = value.value + if V is None: + # Union empty. treat as zero-length char array + V = numpy.zeros((0,), dtype=numpy.uint8) + return V.view(klass.ntndarray)._store(value)
+ +
[docs] def assign(self, V, py): + """Store python value in Value + """ + V[None] = self.wrap(py)
+ +def translateNDAttribute(name, value): + if isinstance(value, Value) and 'value' in value: # assume to be NT-like + V = { + 'name': name, + 'value': value['value'], + } + if 'alarm' in value: + V['alarm'] = value['alarm'] + if 'timeStamp' in value: + V['timeStamp'] = value['timeStamp'] + return V + + return {'name': name, 'value': value} +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/nt/scalar.html b/_modules/p4p/nt/scalar.html new file mode 100644 index 00000000..b2df5f92 --- /dev/null +++ b/_modules/p4p/nt/scalar.html @@ -0,0 +1,389 @@ + + + + + + + + p4p.nt.scalar — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.nt.scalar

+
+import time
+import sys
+import numpy
+
+from ..wrapper import Type, Value
+from .common import alarm, timeStamp, NTBase
+
+if sys.version_info >= (3, 0):
+    unicode = str
+
+
+class ntwrappercommon(object):
+    raw = timestamp = None
+
+    def _store(self, value):
+        assert isinstance(value, Value), value
+        self.raw = value
+        self.severity = value.get('alarm.severity', 0)
+        self.status = value.get('alarm.status', 0)
+        S, NS = value.get('timeStamp.secondsPastEpoch', 0), value.get('timeStamp.nanoseconds', 0)
+        self.raw_stamp = S, NS
+        self.timestamp = S + NS * 1e-9
+        # TODO: unpack display/control
+        return self
+
+    def __str__(self):
+        return '%s %s' % (time.ctime(self.timestamp), self.__repr__())
+
+    tostr = __str__
+
+
[docs]class ntfloat(ntwrappercommon, float): + """ + Augmented float with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """
+ + +
[docs]class ntint(ntwrappercommon, int): + """ + Augmented integer with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """
+ + +class ntbool(ntwrappercommon, int): + """ + Augmented boolean with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """ + def __new__(cls, value): + return int.__new__(cls, bool(value)) + + def __repr__(self): + return bool(self).__repr__().lower() + + +
[docs]class ntstr(ntwrappercommon, unicode): + """ + Augmented string with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """
+ + +
[docs]class ntnumericarray(ntwrappercommon, numpy.ndarray): + """ + Augmented numpy.ndarray with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """ + + @classmethod + def build(klass, val): + assert len(val.shape) == 1, val.shape + # clone + return klass(shape=val.shape, dtype=val.dtype, buffer=val.data, + strides=val.strides)
+ + +
[docs]class ntstringarray(ntwrappercommon, list): + """ + Augmented list of strings with additional attributes + + * .severity + * .status + * .timestamp - Seconds since 1 Jan 1970 UTC as a float + * .raw_stamp - A tuple (seconds, nanoseconds) + * .raw - The underlying :py:class:`p4p.Value`. + """
+ +def _metaHelper(F, valtype, display=False, control=False, valueAlarm=False, form=False): + isnumeric = valtype[-1:] not in '?su' + if display and isnumeric: + F.extend([ + ('display', ('S', None, [ + ('limitLow', valtype[-1:]), + ('limitHigh', valtype[-1:]), + ('description', 's'), + ('precision', 'i'), + ('form', ('S', 'enum_t', [ + ('index', 'i'), + ('choices', 'as'), + ])), + ('units', 's'), + ] if form else [ + ('limitLow', valtype[-1:]), + ('limitHigh', valtype[-1:]), + ('description', 's'), + ('format', 's'), + ('units', 's'), + ])), + ]) + elif display and not isnumeric: + F.extend([ + ('display', ('S', None, [ + ('description', 's'), + ('units', 's'), + ])), + ]) + if control and isnumeric: + F.extend([ + ('control', ('S', None, [ + ('limitLow', valtype[-1:]), + ('limitHigh', valtype[-1:]), + ('minStep', valtype[-1:]), + ])), + ]) + if valueAlarm and isnumeric: + F.extend([ + ('valueAlarm', ('S', None, [ + ('active', '?'), + ('lowAlarmLimit', valtype[-1:]), + ('lowWarningLimit', valtype[-1:]), + ('highWarningLimit', valtype[-1:]), + ('highAlarmLimit', valtype[-1:]), + ('lowAlarmSeverity', 'i'), + ('lowWarningSeverity', 'i'), + ('highWarningSeverity', 'i'), + ('highAlarmSeverity', 'i'), + ('hysteresis', 'd'), + ])), + ]) + +
[docs]class NTScalar(NTBase): + + """Describes a single scalar or array of scalar values and associated meta-data + + >>> stype = NTScalar('d') # scalar double + >>> V = stype.wrap(4.2) + >>> assert isinstance(V, Value) + + >>> stype = NTScalar.buildType('ad') # vector double + >>> V = Value(stype, {'value': [4.2, 4.3]}) + + The result of `wrap()` is an augmented value object combining + `ntwrappercommon` and a python value type (`str`, `int`, `float`, `numpy.ndarray`). + + Agumented values have some additional attributes including: + + * .timestamp - The update timestamp is a float representing seconds since 1 jan 1970 UTC. + * .raw_stamp - A tuple of (seconds, nanoseconds) + * .severity - An integer in the range [0, 3] + * .raw - The complete underlying :class:`~p4p.Value` + + :param str valtype: A type code to be used with the 'value' field. See :ref:`valuecodes` + :param list extra: A list of tuples describing additional non-standard fields + :param bool display: Include optional fields for display meta-data + :param bool control: Include optional fields for control meta-data + :param bool valueAlarm: Include optional fields for alarm level meta-data + :param bool form: Include ``display.form`` instead of the deprecated ``display.format``. + """ + Value = Value + +
[docs] @staticmethod + def buildType(valtype, extra=[], *args, **kws): + """Build a Type + + :param str valtype: A type code to be used with the 'value' field. See :ref:`valuecodes` + :param list extra: A list of tuples describing additional non-standard fields + :param bool display: Include optional fields for display meta-data + :param bool control: Include optional fields for control meta-data + :param bool valueAlarm: Include optional fields for alarm level meta-data + :param bool form: Include ``display.form`` instead of the deprecated ``display.format``. + :returns: A :py:class:`Type` + """ + isarray = valtype[:1] == 'a' + F = [ + ('value', valtype), + ('alarm', alarm), + ('timeStamp', timeStamp), + ] + _metaHelper(F, valtype, *args, **kws) + F.extend(extra) + return Type(id="epics:nt/NTScalarArray:1.0" if isarray else "epics:nt/NTScalar:1.0", + spec=F)
+ + def __init__(self, valtype='d', **kws): + self.type = self.buildType(valtype, **kws) + +
[docs] def wrap(self, value, **kws): + """Pack python value into Value + + Accepts dict to explicitly initialize fields by name. + Any other type is assigned to the 'value' field. + """ + if isinstance(value, Value): + pass + elif isinstance(value, ntwrappercommon): + kws.setdefault('timestamp', value.timestamp) + value = value.raw + elif isinstance(value, dict): + value = self.Value(self.type, value) + else: + value = self.Value(self.type, {'value': value}) + + return self._annotate(value, **kws)
+ + typeMap = { + bool: ntbool, + int: ntint, + float: ntfloat, + unicode: ntstr, + numpy.ndarray: ntnumericarray.build, + list: ntstringarray, + } + +
[docs] @classmethod + def unwrap(klass, value): + """Unpack a Value into an augmented python type (selected from the 'value' field) + """ + assert isinstance(value, Value), value + V = value.value + try: + T = klass.typeMap[type(V)] + except KeyError: + raise ValueError("Can't unwrap value of type %s" % type(V)) + try: + return T(value.value)._store(value) + except Exception as e: + raise ValueError("Can't construct %s around %s (%s): %s" % (T, value, type(value), e))
+ +
[docs] def assign(self, V, py): + """Store python value in Value + """ + V.value = py
+ +if sys.version_info < (3, 0): + class ntlong(ntwrappercommon, long): + pass + + NTScalar.typeMap[long] = ntlong +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/rpc.html b/_modules/p4p/rpc.html new file mode 100644 index 00000000..9fac25df --- /dev/null +++ b/_modules/p4p/rpc.html @@ -0,0 +1,431 @@ + + + + + + + + p4p.rpc — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.rpc

+
+import sys
+import logging
+import inspect
+from functools import wraps, partial
+_log = logging.getLogger(__name__)
+
+from .wrapper import Value, Type
+from .nt import NTURI
+from .client.raw import RemoteError
+from .server import DynamicProvider
+from .server.raw import SharedPV
+from .util import ThreadedWorkQueue, WorkQueue, Full, Empty
+
+__all__ = [
+    'rpc',
+    'rpccall',
+    'rpcproxy',
+    'RemoteError',
+    'WorkQueue',
+    'NTURIDispatcher',
+]
+
+
+
[docs]def rpc(rtype=None): + """Decorator marks a method for export. + + :param type: Specifies which :py:class:`Type` this method will return. + + The return type (rtype) must be one of: + + - An instance of :py:class:`p4p.Type` + - None, in which case the method must return a :py:class:`p4p.Value` + - One of the NT helper classes (eg :py:class:`p4p.nt.NTScalar`). + - A list or tuple used to construct a :py:class:`p4p.Type`. + + Exported methods raise an :py:class:`Exception` to indicate an error to the remote caller. + :py:class:`RemoteError` may be raised to send a specific message describing the error condition. + + >>> class Example(object): + @rpc(NTScalar.buildType('d')) + def add(self, lhs, rhs): + return {'value':float(lhs)+flost(rhs)} + """ + wrap = None + if rtype is None or isinstance(rtype, Type): + pass + elif isinstance(type, (list, tuple)): + rtype = Type(rtype) + elif hasattr(rtype, 'type'): # eg. one of the NT* helper classes + wrap = rtype.wrap + rtype = rtype.type + else: + raise TypeError("Not supported") + + def wrapper(fn): + if wrap is not None: + orig = fn + + @wraps(orig) + def wrapper2(*args, **kws): + return wrap(orig(*args, **kws)) + fn = wrapper2 + + fn._reply_Type = rtype + return fn + return wrapper
+ + +
[docs]def rpccall(pvname, request=None, rtype=None): + """Decorator marks a client proxy method. + + :param str pvname: The PV name, which will be formated using the 'format' argument of the proxy class constructor. + :param request: A pvRequest string or :py:class:`p4p.Value` passed to eg. :py:meth:`p4p.client.thread.Context.rpc`. + + The method to be decorated must have all keyword arguments, + where the keywords are type code strings or :class:`~p4p.Type`. + + """ + def wrapper(fn): + fn._call_PV = pvname + fn._call_Request = request + fn._reply_Type = rtype + return fn + return wrapper
+ + +class RPCDispatcherBase(DynamicProvider): + def __init__(self, queue, target=None, channels=set(), name=None): + DynamicProvider.__init__(self, name, self) # we are our own Handler + self.queue = queue + self.target = target + self.channels = set(channels) + self.name = name + self.__pv = SharedPV( + handler=self, # no per-channel state, and only RPC used, so only need on PV + initial=Value(Type([])), # we don't support get/put/monitor, so use empty struct + ) + M = self.methods = {} + for name, mem in inspect.getmembers(target): + if not hasattr(mem, '_reply_Type'): + continue + M[name] = mem + + def getMethodNameArgs(self, request): + raise NotImplementedError("Sub-class must implement getMethodName") + # sub-class needs to extract method name from request + # return 'name', {'var':'val'} + + def testChannel(self, name): + _log.debug("Test RPC channel %s = %s", name, name in self.channels) + return name in self.channels + + def makeChannel(self, name, src): + if self.testChannel(name): + _log.debug("Open RPC channel %s", name) + return self.__pv # no per-channel tracking needed + else: + _log.warn("Ignore RPC channel %s", name) + + def rpc(self, pv, op): + _log.debug("RPC call %s", op) + try: + self.queue.push(partial(self._handle, op)) + except Full: + _log.warn("RPC call queue overflow") + op.done(error="Too many concurrent RPC calls") + + def _handle(self, op): + try: + request = op.value() + name, args = self.getMethodNameArgs(request) + fn = self.methods[name] + rtype = fn._reply_Type + + R = fn(**args) + + if not isinstance(R, Value): + try: + R = Value(rtype, R) + except: + _log.exception("Error encoding %s as %s", R, rtype) + op.done(error="Error encoding reply") + return + _log.debug("RPC reply %s -> %r", request, R) + op.done(R) + + except RemoteError as e: + _log.debug("RPC reply %s -> error: %s", request, e) + op.done(error=str(e)) + + except: + _log.exception("Error handling RPC %s", request) + op.done(error="Error handling RPC") + + +
[docs]class NTURIDispatcher(RPCDispatcherBase): + + """RPC dispatcher using NTURI (a al. eget) + + Method names are prefixed with a fixed string. + + >>> queue = WorkQueue() + >>> class Summer(object): + @rpc([('result', 'i')]) + def add(self, a=None, b=None): + return {'result': int(a)+int(b)} + >>> installProvider("arbitrary", NTURIDispatcher(queue, target=Summer(), prefix="pv:prefix:")) + + Making a call with the CLI 'eget' utility:: + + $ eget -s pv:prefix:add -a a=1 -a b=2 + .... + int result 3 + + :param queue WorkQueue: A WorkQueue to which RPC calls will be added + :param prefix str: PV name prefix used by RPC methods + :param target: The object which has the RPC calls + """ + + def __init__(self, queue, prefix=None, **kws): + RPCDispatcherBase.__init__(self, queue, **kws) + self.prefix = prefix + self.methods = dict([(prefix + meth, fn) for meth, fn in self.methods.items()]) + self.channels = set(self.methods.keys()) + _log.debug('NTURI methods: %s', ', '.join(self.channels)) + + def getMethodNameArgs(self, request): + # {'schema':'pva', 'path':'pvname', 'query':{'var':'val', ...}} + return request.path, dict(request.query.items())
+ +# legecy for MASAR only +# do not use in new code + + +class MASARDispatcher(RPCDispatcherBase): + + def __init__(self, queue, **kws): + RPCDispatcherBase.__init__(self, queue, **kws) + _log.debug("MASAR pv %s methods %s", self.channels, self.methods) + + def getMethodNameArgs(self, request): + # all through a single PV, method name in request + # {'function':'rpcname', 'name':['name', ...], 'value':['val', ...]} + return request.function, dict(zip(request.get('name', []), request.get('value', []))) + + +
[docs]def quickRPCServer(provider, prefix, target, + maxsize=20, + workers=1, + useenv=True, conf=None, isolate=False): + """Run an RPC server in the current thread + + Calls are handled sequentially, and always in the current thread, if workers=1 (the default). + If workers>1 then calls are handled concurrently by a pool of worker threads. + Requires NTURI style argument encoding. + + :param str provider: A provider name. Must be unique in this process. + :param str prefix: PV name prefix. Along with method names, must be globally unique. + :param target: The object which is exporting methods. (use the :func:`rpc` decorator) + :param int maxsize: Number of pending RPC calls to be queued. + :param int workers: Number of worker threads (default 1) + :param useenv: Passed to :class:`~p4p.server.Server` + :param conf: Passed to :class:`~p4p.server.Server` + :param isolate: Passed to :class:`~p4p.server.Server` + """ + from p4p.server import Server + import time + queue = ThreadedWorkQueue(maxsize=maxsize, workers=workers) + provider = NTURIDispatcher(queue, target=target, prefix=prefix, name=provider) + threads = [] + server = Server(providers=[provider], useenv=useenv, conf=conf, isolate=isolate) + with server, queue: + while True: + time.sleep(10.0)
+ + +
[docs]class RPCProxyBase(object): + + """Base class for automatically generated proxy classes + """ + context = None + "The Context provided on construction" + format = None + "The tuple/dict used to format ('%' operator) PV name strings." + timeout = 3.0 + "Timeout of RPC calls in seconds" + authority = '' + "Authority string sent with NTURI requests" + throw = True + "Whether call errors raise an exception, or return it" + scheme = None # set to override automatic
+ + +def _wrapMethod(K, V): + pv, req = V._call_PV, V._call_Request + if sys.version_info >= (3, 0): + S = inspect.getfullargspec(V) + keywords = S.varkw + else: + S = inspect.getargspec(V) + keywords = S.keywords + + if S.varargs is not None or keywords is not None: + raise TypeError("vararg not supported for proxy method %s" % K) + + if len(S.args) != len(S.defaults): + raise TypeError("proxy method %s must specify types for all arguments" % K) + + try: + NT = NTURI(zip(S.args, S.defaults)) + except Exception as e: + raise TypeError("%s : failed to build method from %s, %s" % (e, S.args, S.defaults)) + + @wraps(V) + def mcall(self, *args, **kws): + pvname = pv % self.format + try: + uri = NT.wrap(pvname, args, kws, scheme=self.scheme or self.context.name, authority=self.authority) + except Exception as e: + raise ValueError("Unable to wrap %s %s as %s (%s)" % (args, kws, NT, e)) + return self.context.rpc(pvname, uri, request=req, timeout=self.timeout, throw=self.throw) + + return mcall + + +
[docs]def rpcproxy(spec): + """Decorator to enable this class to proxy RPC client calls + + The decorated class constructor takes two additional arguments, + `context=` is required to be a :class:`~p4p.client.thread.Context`. + `format`= can be a string, tuple, or dictionary and is applied + to PV name strings given to :py:func:`rpcall`. + Other arguments are passed to the user class constructor. :: + + @rpcproxy + class MyProxy(object): + @rpccall("%s:add") + def add(lhs='d', rhs='d'): + pass + + ctxt = Context('pva') + proxy = MyProxy(context=ctxt, format="tst:") # evaluates "%s:add"%"tst:" + + The decorated class will be a sub-class of the provided class and :class:`RPCProxyBase`. + """ + # inject our ctor first so we don't have to worry about super() non-sense. + + def _proxyinit(self, context=None, format={}, **kws): + assert context is not None, context + self.context = context + self.format = format + spec.__init__(self, **kws) + obj = {'__init__': _proxyinit} + + for K, V in inspect.getmembers(spec, lambda M: hasattr(M, '_call_PV')): + obj[K] = _wrapMethod(K, V) + + return type(spec.__name__, (RPCProxyBase, spec), obj)
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/server.html b/_modules/p4p/server.html new file mode 100644 index 00000000..e9478dd1 --- /dev/null +++ b/_modules/p4p/server.html @@ -0,0 +1,357 @@ + + + + + + + + p4p.server — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.server

+import sys
+import logging
+import warnings
+import re
+import time
+import uuid
+from weakref import ref
+
+from weakref import WeakSet
+
+from .. import _p4p
+from .._p4p import (Server as _Server,
+                    StaticProvider as _StaticProvider,
+                    DynamicProvider as _DynamicProvider,
+                    ServerOperation,
+                    )
+
+if sys.version_info >= (3, 0):
+    unicode = str
+
+_log = logging.getLogger(__name__)
+
+__all__ = (
+    'Server',
+        'installProvider',
+        'removeProvider',
+        'StaticProvider',
+        'DynamicProvider',
+        'ServerOperation',
+)
+
+
[docs]def installProvider(name, provider): + _p4p._providers[name] = ref(provider)
+
[docs]def removeProvider(name): + _p4p._providers.pop(name, None)
+def clearProviders(): + _p4p._providers.clear() + +
[docs]class Server(object): + + """Server(conf=None, useenv=True, providers=[""]) + + :param providers: A list of provider names or instances. See below. + :param dict conf: Configuration keys for the server. Uses same names as environment variables (aka. EPICS_PVAS_*) + :param bool useenv: Whether to use process environment in addition to provided config. + :param bool isolate: If True, override conf= and useenv= to select a configuration suitable for isolated testing. + eg. listening only on localhost with a randomly chosen port number. Use `conf()` to determine + which port is being used. + + Run a PVAccess server serving Channels from the listed providers. + The server is running after construction, until stop(). :: + + S = Server(providers=["example"]) + # do something else + S.stop() + + As a convenience, a Server may be used as a context manager to automatically `stop()`. :: + + with Server(providers=["example"]) as S: + # do something else + + When configuring a Server, conf keys provided to the constructor have the same name as the environment variables. + If both are given, then the provided conf dict is used. + + Call Server.conf() to see a list of valid server (EPICS_PVAS_*) key names and the actual values. + + The providers list may contain: name strings (cf. installProvider()), + `StaticProvider` or `DynamicProvider` instances, or a dict "{'pv:name':`SharedPV`}" to implicitly creat a `StaticProvider`. + Each entry may also be a tuple "(provider, order)" where "provider" is any of the allowed types, + and "order" is an integer used to resolve ambiguity if more than one provider may claim a PV name. + (lower numbers are queried first, the default order is 0) + """ + + def __init__(self, providers, isolate=False, **kws): + self.__keep_alive = [] # ick... + + if isinstance(providers, (bytes, unicode)): + providers = providers.split() # split on space + warnings.warn("Server providers list should be a list", DeprecationWarning) + + Ps = [] + for provider in providers: + if isinstance(provider, tuple): + provider, order = provider + elif hasattr(provider, 'order'): + order = provider.order + else: + order = 0 + + if isinstance(provider, (bytes, unicode)): + if not re.match(r'^[^ \t\n\r]+$', provider): + raise ValueError("Invalid provider name: '%s'"%provider) + Ps.append((provider, order)) + + elif isinstance(provider, (_StaticProvider, _DynamicProvider, _p4p.Source)): + Ps.append((provider, order)) + + elif hasattr(provider, 'items'): + P = StaticProvider() + for name, pv in provider.items(): + P.add(name, pv) + Ps.append((P, order)) + # Normally user code is responsible for keeping the StaticProvider alive. + # Not possible in this case though. + self.__keep_alive.append(P) + + else: + raise ValueError("providers=[] must be a list of string, SharedPV, or dict. Not %s"%provider) + + if isolate: + assert 'useenv' not in kws and 'conf' not in kws, kws + kws['useenv'] = False + kws['conf'] = { + 'EPICS_PVAS_INTF_ADDR_LIST': '127.0.0.1', + 'EPICS_PVA_ADDR_LIST': '127.0.0.1', + 'EPICS_PVA_AUTO_ADDR_LIST': '0', + 'EPICS_PVA_SERVER_PORT': '0', + 'EPICS_PVA_BROADCAST_PORT': '0', + } + + + _log.debug("Starting Server isolated=%s, %s", isolate, kws) + self._S = _Server(providers=Ps, **kws) + + self.tostr = self._S.tostr + + self._S.start() + try: + if _log.isEnabledFor(logging.DEBUG): + _log.debug("New Server: %s", self.tostr(5)) + except: + self._S.stop() + raise + + def __enter__(self): + return self + + def __exit__(self, A, B, C): + self.stop() + +
[docs] def conf(self): + """Return a dict() with the effective configuration this server is using. + + Suitable to pass to another Server to duplicate this configuration, + or to a client Context to allow it to connect to this server. :: + + with Server(providers=["..."], isolate=True) as S: + with p4p.client.thread.Context('pva', conf=S.conf(), useenv=False) as C: + print(C.get("pv:name")) + """ + return self._S.conf()
+ +
[docs] def stop(self): + """Force server to stop serving, and close connections to existing clients. + """ + _log.debug("Stopping Server") + self._S.stop() + self.__keep_alive = []
+ + @classmethod + def forever(klass, *args, **kws): + """Create a server and block the calling thread until KeyboardInterrupt. + Shorthand for: :: + + with Server(*args, **kws): + try; + time.sleep(99999999) + except KeyboardInterrupt: + pass + """ + with klass(*args, **kws): + _log.info("Running server") + try: + while True: + time.sleep(100) + except KeyboardInterrupt: + pass + finally: + _log.info("Stopping server")
+ +
[docs]class StaticProvider(_StaticProvider): + + """A channel provider which servers from a clearly defined list of names. + This list may change at any time. + + :param str name: Provider name. Must be unique within the local context in which it is used. + None, the default, will choose an appropriate value. + """ + def __init__(self, name=None): + if name is None: + # Caller doesn't care. Pick something unique w/o spaces + name = str(uuid.uuid4()) + super(StaticProvider, self).__init__(name)
+ +
[docs]class DynamicProvider(_DynamicProvider): + + """A channel provider which does not maintain a list of provided channel names. + + The following example shows a simple case, in fact so simple that StaticProvider + is a better fit. :: + + class DynHandler(object): + def __init__(self): + self.pv = SharedPV() + def testChannel(self, name): # return True, False, or DynamicProvider.NotYet + return name=="blah" + def makeChannel(self, name, peer): + if name=="blah": + return self.pv + # return None falls through to next source + provider = DynamicProvider("arbitrary", DynHandler()) + server = Server(providers=[provider]) + """ + + # Return from Handler.testChannel() to prevent caching of negative result. + # Use when testChannel('name') might shortly return True + NotYet = b'nocache' + + def __init__(self, name, handler): + _DynamicProvider.__init__(self, name, self._WrapHandler(handler)) + + class _WrapHandler(object): + + "Wrapper around user Handler which logs exception" + + def __init__(self, real): + self._real = real + + def testChannel(self, name): + try: + return self._real.testChannel(name) + except: + _log.exception("Unexpected") + + def makeChannel(self, name, peer): + try: + return self._real.makeChannel(name, peer) + except: + _log.exception("Unexpected")
+ +def _cleanup_servers(): + _log.debug("Stopping all Server instances") + servers = list(_p4p.all_servers) + for srv in servers: + srv.stop() +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/server/asyncio.html b/_modules/p4p/server/asyncio.html new file mode 100644 index 00000000..9b6d1299 --- /dev/null +++ b/_modules/p4p/server/asyncio.html @@ -0,0 +1,222 @@ + + + + + + + + p4p.server.asyncio — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.server.asyncio

+
+import logging
+
+from functools import partial
+
+import asyncio
+
+from .raw import SharedPV as _SharedPV, Handler
+from ..client.thread import RemoteError
+from ..client.asyncio import get_running_loop, create_task, all_tasks
+
+__all__ = (
+    'SharedPV',
+        'Handler',
+)
+
+_log = logging.getLogger(__name__)
+
+def _log_err(V):
+    if isinstance(V, Exception):
+        _log.error("Unhandled from SharedPV handler: %s", V)
+        # TODO: figure out how to show stack trace...
+        # until then, propagate in the hope that someone else will
+    return V
+
+
+def _handle(pv, op, M, args): # callback in asyncio loop
+    try:
+        _log.debug('SERVER HANDLE %s %s %r', op, M, args)
+        maybeco = M(*args)
+        if asyncio.iscoroutine(maybeco):
+            _log.debug('SERVER SCHEDULE %s', maybeco)
+            task = create_task(maybeco)
+
+            # we have no good place to join async put()/rpc() handler results
+            # other than SharedPV.close(sync=True) which is both optional,
+            # and potentially far in the future.  So we log and otherwise
+            # discard the result.
+            task.add_done_callback(_log_err)
+            task._SharedPV = pv # mark so _wait_closed() can distinguish
+        return # caller is responsible for op.done()
+    except RemoteError as e:
+        err = e
+    except Exception as e:
+        _log.exception("Unexpected")
+        err = e
+    if op is not None:
+        op.done(error=str(err))
+
+
+
[docs]class SharedPV(_SharedPV): + + def __init__(self, handler=None, **kws): + self.loop = get_running_loop() + _SharedPV.__init__(self, handler=handler, **kws) + self._disconnected = asyncio.Event() + self._disconnected.set() + + def _exec(self, op, M, *args): + # note than M may be _onFirstConnect or _onLastDisconnect + self.loop.call_soon_threadsafe(partial(_handle, self, op, M, args)) + + def _onFirstConnect(self, _junk): + self._disconnected.clear() + + def _onLastDisconnect(self, _junk): + self._disconnected.set() + + async def _wait_closed(self): + """Wait until any in-progress asynchronous put()/rpc() handler tasks have completed. + """ + _log.debug("Synchronizing %r", self) + + def _peak_done(F, V): + F.set_result(V) + return V + + Ts = [] + for t in all_tasks(): + if getattr(t, '_SharedPV', None) is not self: + continue + F = asyncio.Future() + t.add_done_callback(partial(_peak_done, F)) + Ts.append(F) + + await asyncio.gather(*Ts, return_exceptions=True) + # ignore any returned exceptions as they have already been logged + + _log.debug("Synchronized %r", self) + + # wait for Disconnect notification as well + await self._disconnected.wait() + + def close(self, destroy=False, sync=False): + """Close PV, disconnecting any clients. + + :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). + :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies). + :param float timeout: Applies only when sync=True. None for no timeout, otherwise a non-negative floating point value. + + close() with destory=True or sync=True will not prevent clients from re-connecting. + New clients may prevent sync=True from succeeding. + Prevent reconnection by __first__ stopping the Server, removing with :py:method:`StaticProvider.remove()`, + or preventing a :py:class:`DynamicProvider` from making new channels to this SharedPV. + """ + _SharedPV.close(self, destroy) + if sync: + return self._wait_closed()
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/server/raw.html b/_modules/p4p/server/raw.html new file mode 100644 index 00000000..540f0fe5 --- /dev/null +++ b/_modules/p4p/server/raw.html @@ -0,0 +1,389 @@ + + + + + + + + p4p.server.raw — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.server.raw

+
+import logging
+_log = logging.getLogger(__name__)
+
+from .._p4p import SharedPV as _SharedPV
+
+__all__ = (
+    'SharedPV',
+    'Handler',
+)
+
+
+class ServOpWrap(object):
+
+    def __init__(self, op, wrap, unwrap):
+        self._op, self._wrap, self._unwrap = op, wrap, unwrap
+
+    def value(self):
+        V = self._op.value()
+        try:
+            return self._unwrap(V)
+        except: # py3 will chain automatically, py2 won't
+            raise ValueError("Unable to unwrap %r with %r"%(V, self._unwrap))
+
+    def done(self, value=None, error=None):
+        if value is not None:
+            try:
+                value = self._wrap(value)
+            except:
+                raise ValueError("Unable to wrap %r with %r"%(value, self._wrap))
+        self._op.done(value, error)
+
+    def __getattr__(self, key):
+        return getattr(self._op, key) # dispatch to _p4p.ServerOperation
+
+
+
[docs]class Handler(object): + """Skeleton of SharedPV Handler + + Use of this as a base class is optional. + """ + +
[docs] def put(self, pv, op): + """ + Called each time a client issues a Put + operation on this Channel. + + :param SharedPV pv: The :py:class:`SharedPV` which this Handler is associated with. + :param ServerOperation op: The operation being initiated. + """ + op.done(error='Not supported')
+ +
[docs] def rpc(self, pv, op): + """ + Called each time a client issues a Remote Procedure Call + operation on this Channel. + + :param SharedPV pv: The :py:class:`SharedPV` which this Handler is associated with. + :param ServerOperation op: The operation being initiated. + """ + op.done(error='Not supported')
+ +
[docs] def onFirstConnect(self, pv): + """ + Called when the first Client channel is created. + + :param SharedPV pv: The :py:class:`SharedPV` which this Handler is associated with. + """ + pass
+ +
[docs] def onLastDisconnect(self, pv): + """ + Called when the last Client channel is closed. + + :param SharedPV pv: The :py:class:`SharedPV` which this Handler is associated with. + """ + pass
+ + +
[docs]class SharedPV(_SharedPV): + + """Shared state Process Variable. Callback based implementation. + + .. note:: if initial=None, the PV is initially **closed** and + must be :py:meth:`open()`'d before any access is possible. + + :param handler: A object which will receive callbacks when eg. a Put operation is requested. + May be omitted if the decorator syntax is used. + :param Value initial: An initial Value for this PV. If omitted, :py:meth:`open()`s must be called before client access is possible. + :param nt: An object with methods wrap() and unwrap(). eg :py:class:`p4p.nt.NTScalar`. + :param callable wrap: As an alternative to providing 'nt=', A callable to transform Values passed to open() and post(). + :param callable unwrap: As an alternative to providing 'nt=', A callable to transform Values returned Operations in Put/RPC handlers. + :param dict options: A dictionary of configuration options. + + Creating a PV in the open state, with no handler for Put or RPC (attempts will error). :: + + from p4p.nt import NTScalar + pv = SharedPV(nt=NTScalar('d'), value=0.0) + # ... later + pv.post(1.0) + + The full form of a handler object is: :: + + class MyHandler: + def put(self, pv, op): + pass + def rpc(self, pv, op): + pass + def onFirstConnect(self): # may be omitted + pass + def onLastDisconnect(self): # may be omitted + pass + pv = SharedPV(MyHandler()) + + Alternatively, decorators may be used. :: + + pv = SharedPV() + @pv.put + def onPut(pv, op): + pass + + The nt= or wrap= and unwrap= arguments can be used as a convience to allow + the open(), post(), and associated Operation.value() to be automatically + transform to/from :py:class:`Value` and more convienent Python types. + See :ref:`unwrap` + """ + + def __init__(self, handler=None, initial=None, + nt=None, wrap=None, unwrap=None, + options=None, **kws): + self.nt = nt + self._handler = handler or self._DummyHandler() + self._whandler = self._WrapHandler(self, self._handler) + + self._wrap = wrap or (nt and nt.wrap) or (lambda x: x) + self._unwrap = unwrap or (nt and nt.unwrap) or (lambda x: x) + + _SharedPV.__init__(self, self._whandler, options) + if initial is not None: + self.open(initial, nt=nt, wrap=wrap, unwrap=unwrap, **kws) + +
[docs] def open(self, value, nt=None, wrap=None, unwrap=None, **kws): + """Mark the PV as opened an provide its initial value. + This initial value is later updated with post(). + + :param value: A Value, or appropriate object (see nt= and wrap= of the constructor). + + Any clients which have begun connecting which began connecting while + this PV was in the close'd state will complete connecting. + + Only those fields of the value which are marked as changed will be stored. + """ + + self._wrap = wrap or (nt and nt.wrap) or self._wrap + self._unwrap = unwrap or (nt and nt.unwrap) or self._unwrap + + try: + V = self._wrap(value, **kws) + except: # py3 will chain automatically, py2 won't + raise ValueError("Unable to wrap %r with %r and %r"%(value, self._wrap, kws)) + _SharedPV.open(self, V)
+ +
[docs] def post(self, value, **kws): + """Provide an update to the Value of this PV. + + :param value: A Value, or appropriate object (see nt= and wrap= of the constructor). + + Only those fields of the value which are marked as changed will be stored. + + Any keyword arguments are forwarded to the NT wrap() method (if applicable). + Common arguments include: timestamp= , severity= , and message= . + """ + try: + V = self._wrap(value, **kws) + except: # py3 will chain automatically, py2 won't + raise ValueError("Unable to wrap %r with %r and %r"%(value, self._wrap, kws)) + _SharedPV.post(self, V)
+ +
[docs] def current(self): + V = _SharedPV.current(self) + try: + return self._unwrap(V) + except: # py3 will chain automatically, py2 won't + raise ValueError("Unable to unwrap %r with %r"%(V, self._unwrap))
+ + def _exec(self, op, M, *args): # sub-classes will replace this + try: + M(*args) + except Exception as e: + if op is not None: + op.done(error=str(e)) + _log.exception("Unexpected") + + def _onFirstConnect(self, _junk): + pass # see sub-classes. run before user onFirstConnect() + + def _onLastDisconnect(self, _junk): + pass # see sub-classes. run after user onLastDisconnect() + + class _DummyHandler(object): + pass + + class _WrapHandler(object): + + "Wrapper around user Handler which logs exceptions" + + def __init__(self, pv, real): + self._pv = pv # this creates a reference cycle, which should be collectable since SharedPV supports GC + self._real = real + + def onFirstConnect(self): + self._pv._exec(None, self._pv._onFirstConnect, None) + try: # user handler may omit onFirstConnect() + M = self._real.onFirstConnect + except AttributeError: + return + self._pv._exec(None, M, self._pv) + + def onLastDisconnect(self): + try: + M = self._real.onLastDisconnect + except AttributeError: + pass + else: + self._pv._exec(None, M, self._pv) + self._pv._exec(None, self._pv._onLastDisconnect, None) + + def put(self, op): + _log.debug('PUT %s %s', self._pv, op) + try: + self._pv._exec(op, self._real.put, self._pv, ServOpWrap(op, self._pv._wrap, self._pv._unwrap)) + except AttributeError: + op.done(error="Put not supported") + + def rpc(self, op): + _log.debug('RPC %s %s', self._pv, op) + try: + self._pv._exec(op, self._real.rpc, self._pv, op) + except AttributeError: + op.done(error="RPC not supported") + + @property + def onFirstConnect(self): + def decorate(fn): + self._handler.onFirstConnect = fn + return fn + return decorate + + @property + def onLastDisconnect(self): + def decorate(fn): + self._handler.onLastDisconnect = fn + return fn + return decorate + + @property + def put(self): + def decorate(fn): + self._handler.put = fn + return fn + return decorate + + @property + def rpc(self): + def decorate(fn): + self._handler.rpc = fn + return fn + return decorate + + def __repr__(self): + if self.isOpen(): + return '%s(value=%s)' % (self.__class__.__name__, repr(self.current())) + else: + return "%s(<closed>)" % (self.__class__.__name__,) + __str__ = __repr__
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/server/thread.html b/_modules/p4p/server/thread.html new file mode 100644 index 00000000..852b2ac3 --- /dev/null +++ b/_modules/p4p/server/thread.html @@ -0,0 +1,220 @@ + + + + + + + + p4p.server.thread — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.server.thread

+
+import logging
+_log = logging.getLogger(__name__)
+
+from functools import partial
+from threading import Event
+
+from ..util import _defaultWorkQueue
+from .raw import SharedPV as _SharedPV, Handler
+from ..client.raw import RemoteError
+
+__all__ = (
+    'SharedPV',
+    'Handler',
+)
+
+def _on_queue(op, M, *args):
+    try:
+        M(*args)
+        return
+    except RemoteError as e:
+        err = e
+    except Exception as e:
+        _log.exception("Unexpected")
+        err = e
+    if op is not None:
+        op.done(error=str(err))
+
+
+
[docs]class SharedPV(_SharedPV): + + """Shared state Process Variable. Callback based implementation. + + .. note:: if initial=None, the PV is initially **closed** and + must be :py:meth:`open()`'d before any access is possible. + + :param handler: A object which will receive callbacks when eg. a Put operation is requested. + May be omitted if the decorator syntax is used. + :param Value initial: An initial Value for this PV. If omitted, :py:meth:`open` s must be called before client access is possible. + :param nt: An object with methods wrap() and unwrap(). eg :py:class:`p4p.nt.NTScalar`. + :param callable wrap: As an alternative to providing 'nt=', A callable to transform Values passed to open() and post(). + :param callable unwrap: As an alternative to providing 'nt=', A callable to transform Values returned Operations in Put/RPC handlers. + :param WorkQueue queue: The threaded :py:class:`WorkQueue` on which handlers will be run. + :param dict options: A dictionary of configuration options. + + Creating a PV in the open state, with no handler for Put or RPC (attempts will error). :: + + from p4p.nt import NTScalar + pv = SharedPV(nt=NTScalar('d'), value=0.0) + # ... later + pv.post(1.0) + + The full form of a handler object is: :: + + class MyHandler: + def put(self, op): + pass + def rpc(self, op): + pass + def onFirstConnect(self): # may be omitted + pass + def onLastDisconnect(self): # may be omitted + pass + pv = SharedPV(MyHandler()) + + Alternatively, decorators may be used. :: + + pv = SharedPV() + @pv.put + def onPut(pv, op): + pass + + """ + + def __init__(self, queue=None, **kws): + _SharedPV.__init__(self, **kws) + self._queue = queue or _defaultWorkQueue() + self._disconnected = Event() + self._disconnected.set() + + def _exec(self, op, M, *args): + self._queue.push(partial(_on_queue, op, M, *args)) + + def _onFirstConnect(self, _junk): + self._disconnected.clear() + + def _onLastDisconnect(self, _junk): + self._disconnected.set() + +
[docs] def close(self, destroy=False, sync=False, timeout=None): + """Close PV, disconnecting any clients. + + :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). + :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies). + :param float timeout: Applies only when sync=True. None for no timeout, otherwise a non-negative floating point value. + + close() with destory=True or sync=True will not prevent clients from re-connecting. + New clients may prevent sync=True from succeeding. + Prevent reconnection by __first__ stopping the Server, removing with :py:meth:`StaticProvider.remove()`, + or preventing a :py:class:`DynamicProvider` from making new channels to this SharedPV. + """ + _SharedPV.close(self, destroy) + if sync: + # TODO: still not syncing PVA workers... + self._queue.sync() + self._disconnected.wait()
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/util.html b/_modules/p4p/util.html new file mode 100644 index 00000000..8121d5bf --- /dev/null +++ b/_modules/p4p/util.html @@ -0,0 +1,253 @@ + + + + + + + + p4p.util — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.util

+
+import logging
+_log = logging.getLogger(__name__)
+
+from functools import partial
+
+try:
+    from Queue import Queue, Full, Empty
+except ImportError:
+    from queue import Queue, Full, Empty
+from threading import Thread, Event
+
+__all__ = [
+    'WorkQueue',
+]
+
+
+
[docs]class WorkQueue(object): + + """A threaded work queue. + """ + _stopit = object() + + def __init__(self, maxsize=5): + self._Q = Queue(maxsize=maxsize) + + def push(self, callable): + self._Q.put_nowait(callable) # throws Queue.Full + + def push_wait(self, callable): + self._Q.put(callable) + +
[docs] def interrupt(self): + """Break one call to handle() + + eg. Call N times to break N threads. + + This call blocks if the queue is full. + """ + self._Q.put(self._stopit)
+ +
[docs] def handle(self): + """Process queued work until interrupt() is called + """ + while True: + # TODO: Queue.get() (and anything using thread.allocate_lock + # ignores signals :( so timeout periodically to allow delivery + try: + callable = None # ensure no lingering references to past work while blocking + callable = self._Q.get(True, 1.0) + except Empty: + continue # retry on timeout + try: + if callable is self._stopit: + break + callable() + except: + _log.exception("Error from WorkQueue w/ %r", callable) + finally: + self._Q.task_done()
+ +class ThreadedWorkQueue(WorkQueue): + def __init__(self, name=None, workers=1, daemon=False, **kws): + assert workers>=1, workers + WorkQueue.__init__(self, **kws) + self.name = name + self._daemon = daemon + self._T = [None]*workers + + def __enter__(self): + self.start() + def __exit__(self, A,B,C): + self.stop() + + def start(self): + for n in range(len(self._T)): + if self._T[n] is not None: + continue + T = self._T[n] = Thread(name='%s[%d]'%(self.name, n), target=self.handle) + T.daemon = self._daemon + T.start() + + return self # allow chaining + + def stop(self): + [self.interrupt() for T in self._T if T is not None] + [T.join() for T in self._T if T is not None] + self._T = [None]*len(self._T) + + return self # allow chaining + + def sync(self, timeout=None): + wait1 = [Event() for _n in range(len(self._T))] + wait2 = [Event() for _n in range(len(self._T))] + + def syncX(wait1, wait2): + wait1.set() + wait2.wait() + + [self.push_wait(partial(syncX, wait1[n], wait2[n])) for n in range(len(self._T))] + + # wait for all workers to ready wait1 barrier + for W in wait1: + W.wait(timeout=timeout) + + # allow workers to proceeed + for W in wait2: + W.set() + + return self # allow chaining + +# lazy create a default work queues + +class _DefaultWorkQueue(object): + + def __init__(self, workers=4): # TODO: configurable? + self.W = [None]*workers + self.n = 0 + + def __del__(self): + self.stop() + + def __call__(self): + W = self.W[self.n] + if W is None: + # daemon=True otherwise the MainThread exit handler tries to join too early + W = self.W[self.n] = ThreadedWorkQueue(maxsize=0, daemon=True).start() + + # sort of load balancing by giving different queues to each SharedPV + # but preserve ordering or callbacks as each SharedPV has only one queue + self.n = (self.n+1)%len(self.W) + return W + + def sync(self): + [W.sync() for W in self.W if W is not None] + + def stop(self): + [W.stop() for W in self.W if W is not None] + self.W = [None]*len(self.W) + +_defaultWorkQueue = _DefaultWorkQueue() +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_modules/p4p/wrapper.html b/_modules/p4p/wrapper.html new file mode 100644 index 00000000..adcd746c --- /dev/null +++ b/_modules/p4p/wrapper.html @@ -0,0 +1,340 @@ + + + + + + + + p4p.wrapper — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for p4p.wrapper

+# This module defines sub-classes of C extension classes
+# which add functionality that is better expressed in python.
+# These types are then pushed (by _magic) down into extension
+# code where they will be used as the types passed to callbacks.
+from . import _p4p
+
+__all__ = (
+    'Type',
+    'Value',
+    'Struct',
+    'StructArray',
+    'Union',
+    'UnionArray',
+)
+
+
+def Struct(spec=None, id=None):
+    return ('S', id, spec)
+
+
+def Union(spec=None, id=None):
+    return ('U', id, spec)
+
+
+def StructArray(spec=None, id=None):
+    return ('aS', id, spec)
+
+
+def UnionArray(spec=None, id=None):
+    return ('aU', id, spec)
+
+
+
[docs]class Type(_p4p._Type): + """Type(fields, id=None, base=None) + + :param list fields: A list of tuples describing members of this data structure. + :param str id: Type label string. + :param Type base: Copy the fields of `Type`, then amend with the provided fields. + + A definition of a data structure consisting of a list of field names and types, + as well as an optional type name string (id=""). + Field type specifications are either a string eg. "d" (double precision float), + or a tuple ("S", None, [fields...) defining a sub-structure. :: + + T = Type([ + ('value', 'I'), + ]) + + Defines a structure with a single field named 'value' with type u32 (unsigned integer width 32-bit). + + An example of defining a sub-structure. :: + + T = Type([ + ('value', ('S', None, [ + ('index', 'i'), + ])), + ]) + + Type specifier codes: + + ==== ======= + Code Type + ==== ======= + ? bool + s unicode + b s8 + B u8 + h s16 + H u16 + i i32 + I u32 + l i64 + L u64 + f f32 + d f64 + v variant + U union + S struct + ==== ======= + """ + __slots__ = [] # we don't allow custom attributes for now + __contains__ = _p4p._Type.has + + def __call__(self, initial=None): + return Value(self, initial) + +
[docs] def __iter__(self): + for k in self.keys(): + yield k
+ +
[docs] def items(self): + return [(k, self[k]) for k in self.keys()]
+ +
[docs] def values(self): + return [self[k] for k in self.keys()]
+ + def __repr__(self): + S, id, fields = self.aspy() + return 'Type(%s, id="%s")' % (fields, id) + __str__ = __repr__
+ +_p4p.Type = Type + + +
[docs]class Value(_p4p._Value): + """Value(type[, initial]) + + :param Type type: The `Type` describing the structure to be instanciated + :param dict initial: A dictionary (or any mapping) which gives initial values for fields. + + Representation of a data structure of a particular :py:class:`Type`. + + Can be created using a :py:class:`Type`, with an optional dict containing initial values. :: + + A = Value(Type([ + ('value', 'I'), + ]), { + 'value': 42, + }) + + Defines a structure with a single field named 'value' with type u32 (unsigned integer width 32-bit). + + An example of defining a sub-structure. :: + + A = Value(Type([ + ('value', ('S', None, [ + ('index', 'i'), + ])), + ]), { + 'value': {'index', 5}, + # 'value.index': 5, # equivalent + }) + + Defines a structure containing a sub-structure 'value' which has a single field 'index' which is + a signed 32-bit integer. + """ + __slots__ = [] # prevent attribute access to invalid fields + + __contains__ = _p4p._Value.has + + def keys(self): + """keys() -> Iterable[str] + """ + return self.type().keys() + + def __iter__(self): + return iter(self.type()) + +
[docs] def changed(self, *fields): + """changed(*fields) -> bool + Test if one or more named fields have changed. + + A field is considered to have changed if it is marked as changed, + or if its parent, or any child, field is marked as changed. + """ + S = super(Value, self).changed + for fld in fields or (None,): # no args tests for any change + if S(fld): + return True + return False
+ +
[docs] def changedSet(self, expand=False, parents=False): + """changedSet(expand=False, parents=False) -> set + :param bool expand: Whether to expand when entire sub-structures are marked as changed. + If True, then sub-structures are expanded and only leaf fields will be included. + If False, then a direct translation is made, which may include both leaf and sub-structure fields. + :param bool parents: If True, include fake entries for parent sub-structures with leaf fields marked as changed. + :returns: A :py:class:`set` of names of those fields marked as changed. + + Return a :py:class:`set` containing the names of all changed fields. :: + + A = Value(Type([ + ('x', 'i'), + ('z', ('S', None, [ + ('a', 'i'), + ('b', 'i'), + ])), + ]), { + }) + + A.mark('z') + assert A.changedSet(expand=False) == {'z'} # only shows fields explicitly marked + assert A.changedSet(expand=True) == {'z.a', 'z.b'} # actually used during network transmission + A.mark('z.a') # redundant + assert A.changedSet(expand=False) == {'z', 'z.a'} + assert A.changedSet(expand=True) == {'z.a', 'z.b'} + A.unmark('z') + assert A.changedSet(expand=False) == {'z.a'} + assert A.changedSet(expand=True) == {'z.a'} + assert A.changedSet(expand=False, parents=True) == {'z', 'z.a'} + assert A.changedSet(expand=True, parents=True) == {'z', 'z.a'} + + + * expand=False, parents=False gives a direct mapping of the underlying BitSet as it would (get/monitor), + or have been (put/rpc), moved over the network. + * expand=True, parents=False gives the effective set of leaf fields which will be moved over the network. + taking into account the use of whole sub-structure compress/shorthand bits. + * expand=False, parents=True gives a way of testing if anything changed within a set of interesting fields + (cf. set.intersect). + """ + return _p4p._Value.changedSet(self, expand, parents)
+ + # TODO: deprecate + asSet = changedSet + + def clear(self): + self.mark(None, False) + + __str__ = _p4p._Value.tostr + + def __repr__(self): + parts = [] + + ID = self.getID() + if ID!='structure': + parts.append('id:'+ID) + + try: + parts.append(repr(self.value)) + except AttributeError: # no .value + try: + parts.append(repr(self.get(self.type().keys()[0]))) + except IndexError: # empty Structure + pass + + return 'Value(%s)'%', '.join(parts)
+ +_p4p.Value = Value +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/_sources/building.rst.txt b/_sources/building.rst.txt new file mode 100644 index 00000000..46b6df3c --- /dev/null +++ b/_sources/building.rst.txt @@ -0,0 +1,176 @@ + +.. _building: + +Building +======== + +Release tars available from https://github.com/epics-base/p4p/releases + +The P4P modules requires: + +* Python 2.7 or >=3.5 (>=3.6 for asyncio support) +* numpy >=1.6 +* Cython >=0.25.2 +* nose2 (Optional, recommended to run unittests) + +and... + +Current (>= 4.0) + +* EPICS Base >= 3.14.12 +* PVXS >= 0.2.0 + +Prior to 4.0 + +* EPICS >= 7.0.2 + +or + +* EPICS Base >= 3.14.12 +* pvDataCPP >=7.1.0 +* pvAccessCPP >=6.1.0 + +P4P can be built and installed in one of two ways. +As a python package, preferably managed by PIP. +As an EPICS module. + +Optional + +* `cothread `_ needed by `p4p.client.cothread.Context`. +* `qtpy `_ needed for `p4p.client.Qt.Context`. + +Local (re)build as Python package +--------------------------------- + +The process for building as a python package using sources from pypi.org by adding the argument "--no-binary" +to prevent the use of pre-built binarys (except for numpy). :: + + python -m virtualenv p4ptest + . p4ptest/bin/activate + python -m pip install -U pip + python -m pip install \ + --only-binary numpy \ + --no-binary epicscorelibs,pvxslibs,p4p \ + nose2 p4p + python -m nose2 p4p # Optional: runs automatic tests + +Bootstrap a virtualenv offline +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It may be necessary to create a virtualenv including P4P on a machine with no internet access, +or to ensure the use of certain verified binary/source. +The following recipe was tested with virtualenv 16.1 and pip 18.1. + +First, from a machine with internet access, and having the same archetecture as the target machine, +collect the necessary files. :: + + mkdir /tmp/venv + cd /tmp/venv + python -m pip download virtualenv + unzip virtualenv-*.whl + python virtualenv.py --never-download prepenv + . prepenv/bin/activate + pip download -d virtualenv_support nose2 p4p + tar -caf p4p-env-`date -u +%Y%m%d`.tar.gz virtualenv.py virtualenv_support + deactivate + +Now move the created file p4p-env-\*.tar.gz to the target machine. +Then prepare the virtualenv env with. :: + + tar -xaf p4p-env-*.tar.gz + python virtualenv.py --never-download env + . env/bin/activate + pip install --no-index -f virtualenv_support p4p + python -m nose2 p4p # Optional: runs automatic tests + +Utilities to automate this process include https://pypi.org/project/pyutilib.virtualenv/ + +Build as EPICS Module +--------------------- + +P4P can also be built as an EPICS Module with additional python dependencies. + +Prepare the host to build python extensions. eg. a Debian Linux host:: + + sudo apt-get install build-essential python3-dev + +Install python dependencies on eg. a Debian Linux host:: + + sudo apt-get install python3-numpy python3-nose2 cython3 + +or with PIP:: + + python3 -m pip install -r requirements-latest.txt + +From from versioned source. (may replace "master" with release version number):: + + git clone --branch master https://github.com/epics-base/p4p.git + cd p4p + +Set location of EPICS modules. With EPICS >= 7.0.2:: + + cat < configure/RELEASE.local + PVXS=/path/to/pvxs + EPICS_BASE=/path/to/epics-base + EOF + make + +See below for details on building EPICS from source. + +By default P4P will build using 'python' found in the system search path. +To explicitly specify a particular version. :: + + make distclean + make PYTHON=python3 + +Alternately, the full path of the interpreter can be used. :: + + make distclean + make PYTHON=/usr/bin/python3 + +For convenience PYTHON can also be set in configure/CONFIG_SITE + +Multiple Python Versions +~~~~~~~~~~~~~~~~~~~~~~~~ + +To build for multiple python versions it is necessary to do a partial clean before building +another version. This will not remove the final tree. :: + + make PYTHON=python2 + make PYTHON=python2 clean + make PYTHON=python3 + make PYTHON=python3 clean + +.. note:: If PYTHON= is ever specified, then it must be specified for all targets except 'distclean'. + +.. _builddeps: + +Building EPICS dependencies +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the necessary EPICS modules are not present, then they may be built from source. :: + + sudo apt-get install libreadline6-dev libncurses5-dev perl + git clone https://github.com/epics-base/epics-base.git + git clone https://github.com/epics-base/pvxs.git + cat < pvxs/configure/RELEASE.local + EPICS_BASE=$PWD/epics-base + EOF + cat < p4p/configure/RELEASE.local + PVXS=$PWD/pvxs + EPICS_BASE=$PWD/epics-base + EOF + make -C epics-base + make -C pvxs + +CLI and unittests +~~~~~~~~~~~~~~~~~ + +To run the unittests: :: + + make nose + +For testing purposes several simple command line client tools are provided. +For further information run: :: + + PYTHONPATH=$PWD/python2.7/linux-x86_64 python -m p4p.client.cli -h diff --git a/_sources/client.rst.txt b/_sources/client.rst.txt new file mode 100644 index 00000000..758195d3 --- /dev/null +++ b/_sources/client.rst.txt @@ -0,0 +1,145 @@ + +.. _clientapi: + +Client API +========== + +.. currentmodule:: p4p.client.thread + +This module provides :py:class:`Context` for use in interactive and/or multi-threaded environment. +Most methods will block the calling thread until a return is available, or an error occurs. + +Alternatives to `p4p.client.thread.Context` are provided +`p4p.client.cothread.Context`, +`p4p.client.asyncio.Context`, +and `p4p.client.Qt.Context`. +These differ in how blocking for I/O operation is performed, +and the environment in which Monitor callbacks are run. + +Note that `p4p.client.Qt.Context` behaves differently from the others in some respects. +This is described in `qtclient`_. + +Usage +----- + +Start by creating a client :py:class:`Context`. :: + + >>> from p4p.client.thread import Context + >>> Context.providers() + ['pva', ....] + >>> ctxt = Context('pva') + +.. note:: The default network configuration taken from the process environment + may be overridden by passing 'conf=' to the `Context` class constructor. + +See `overviewpva` for background on PVAccess protocol. + +Get/Put +^^^^^^^ + +Get and Put operations can be performed on single PVs or a list of PVs. :: + + >>> V = ctxt.get('pv:name') + >>> A, B = ctxt.get(['pv:1', 'pv:2']) + >>> ctxt.put('pv:name', 5) + >>> ctxt.put('pv:name', {'value': 5}) # equivalent to previous + >>> ctxt.put('pv:name', {'field_1.value': 5, 'field_2.value': 5}) # put to multiple fields + +By default the values returned by :py:meth:`Context.get` are subject to :py:ref:`unwrap`. + +Monitor +^^^^^^^ + +Unlike get/put/rpc, the :py:meth:`Context.monitor` method does not block. +Instead it accepts a callback function which is called with each +new :py:class:`Value`, or :py:class:`Exception`. :: + + def cb(V): + print 'New value', V + sub = ctxt.monitor('pv:name', cb) + time.sleep(10) # arbitrary wait + sub.close() + +The monitor method returns a :py:class:`Subscription` which has a close method +to end the subscription. + +By default the values passed to monitor callbacks are subject to :py:ref:`unwrap`. + +`p4p.client.thread.Context` Runs callbacks in a worker thread pool. + +`p4p.client.cothread.Context` Runs callbacks in a per-subscription cothread. + +`p4p.client.asyncio.Context` Runs callbacks in a per-subscription coroutine. + +In all cases it is safe for a callback to block/yield. +Subsequent updates for a `Subscription` will not be delivered until the current callback has completed. +However, updates for other Subscriptions may be delivered. + +RPC +^^^ + +See `rpcapi`. + +API Reference +------------- + +.. module:: p4p.client.thread + +.. autoclass:: Context + + .. autoattribute:: name + + .. automethod:: close + + .. automethod:: get + + .. automethod:: put + + .. automethod:: monitor + + .. automethod:: rpc + + .. automethod:: providers + + .. automethod:: disconnect + + .. automethod:: set_debug + +.. autoclass:: Subscription + + .. automethod:: close + +.. autoclass:: Disconnected + +.. autoclass:: RemoteError + +.. autoclass:: Cancelled + +.. autoclass:: Finished + +.. autoclass:: TimeoutError + +.. _qtclient: + +Qt Client +--------- + +`p4p.client.Qt.Context` exists to bring the results of network operations into a Qt event loop. +This is done through the native signals and slots mechanism. + +Use requires the optional dependency `qtpy `_ package. + +This dependency is expressed as an extras_require= of "qt". +It may be depended upon accordingly as "p4p[qt]". + +`p4p.client.Qt.Context` differs from the other Context classes in several respects. + +* Each Context attempts to minimize the number of subscriptions to each named PV. + Multiple calls to monitor() will attempt to share this subscription if possible (subject to request argument). + +* All monitor() calls must express a desired maximum update rate limit through the limitHz argument. + +* As a convienence, the objects returned by put() and monitor() do not have to be stored by the caller. + The internal references kept by the Context may be cleared through the disconnect() method. + This cache extends to a single put and a single monitor subscription per PV. + So eg. initiating a put() to a PV will implicitly cancel a previous in-progress put(). diff --git a/_sources/gw.rst.txt b/_sources/gw.rst.txt new file mode 100644 index 00000000..b366909d --- /dev/null +++ b/_sources/gw.rst.txt @@ -0,0 +1,903 @@ +.. _gwpage: + +PVA Gateway +=========== + +.. currentmodule:: p4p + +Quick Start +----------- + +First install P4P (see the main :ref:`starting`). + +The following commands will set up a gateway instance named ``mygw`` on a Linux system that uses *systemd*: :: + + # generate a simple configuration file + sudo python -m p4p.gw --example-config /etc/pvagw/mygw.conf + # generate a systemd unit file to support the gateway + sudo python -m p4p.gw --example-systemd \ + /etc/systemd/system/pvagw@.service + # start the gateway + sudo systemctl daemon-reload + sudo systemctl start pvagw@mygw.service + # check to see if the instance has started correctly + sudo systemctl status pvagw@mygw.service + # set the instance to start automatically on boot + sudo systemctl enable pvagw@mygw.service + +Background +---------- + +The PVA Gateway provides a way for EPICS client software to access IOCs on an isolated network. + +In doing so, it reduces the resource load on the server-facing side, +and provides access control restrictions to requests from the client facing side. +The gateway is a specialized proxy for the PV Access (PVA) Protocol +which sits between groups of PVA clients and servers. (see `overviewpva`) + +.. graph:: nogw + :caption: PVA Connections without a Gateway + + rankdir="RL"; + serv1 [shape=box,label="EPICS IOC"]; + serv2 [shape=box,label="PVA server"]; + serv3 [shape=box,label="EPICS IOC"]; + cli1 [shape=box,label="pvget"]; + cli2 [shape=box,label="PVA client"]; + serv1 -- cli1 + serv2 -- cli1 + serv3 -- cli1 + serv1 -- cli2 + serv2 -- cli2 + serv3 -- cli2 + +Without a Gateway, ``M`` clients connect to ``N`` servers +with ``M*N`` connections (TCP sockets). If all clients are subscribed +to the same set of PVs, then each server is sending the same data values +``M`` times. + +.. graph:: gwnames + :caption: PVA Connections through a Gateway + + rankdir="RL"; + serv1 [shape=box,label="EPICS IOC"]; + serv2 [shape=box,label="PVA Server"]; + serv3 [shape=box,label="EPICS IOC"]; + subgraph clustergw { + label="Gateway\nProcess"; + gwc [label="Gateway\nClient"]; + gws [label="Gateway\nServer"]; + } + cli1 [shape=box,label="pvget"]; + cli2 [shape=box,label="PVA Client"]; + + serv1 -- gwc; + serv2 -- gwc; + serv3 -- gwc; + gws -- cli1; + gws -- cli2; + +Adding a Gateway reduces the number of connections to ``M+N``. +With ``M`` clients connecting to a gateway server on one side, and one gateway client connecting to ``N`` servers on the other. +Further, a Gateway de-duplicates subscription data updates +so that each server sends only a single update to the Gateway, +which then repeats it to each client. + +So the PVA servers and IOCs see only a single client, +and are shielded from a potentially large number of clients on +the other side of the gateway. + +.. note:: + Each gateway process can define multiple internal Servers and Clients. + This allows, for example, a single gateway process to connect to multiple IOC subnets, + providing EPICS clients to access all IOCs. + +Example +~~~~~~~ + +A common scenario is to have a gateway running on a host computer +with two network interfaces (NICs) on different subnets, +and thus two different broadcast domains. + +In this example, a server has two NICs with IP addresses +192.168.1.5/24 and 10.1.1.4/24. + +.. graph:: gwnet + :caption: Example: A Multi-homed Host for a Gateway + + rankdir="LR"; + serv [shape=box,label="PVA server\n192.168.1.23"]; + cli [shape=box,label="PVA client\n10.1.1.78"]; + subgraph clustergw { + label="Gateway\nHost"; + nic2 [shape=cds,label="NIC 10.1.1.4",orientation=180]; + nic1 [shape=cds,label="NIC 192.168.1.5"]; + } + cli -- nic2; + nic1 -- serv; + +To support this host, the gateway can be set up with the +following configuration file. +The intent is that the gateway provides EPICS clients on +the ``10.1.1.0/24`` subnet with access to IOCs or other PVA servers +on the ``192.168.1.0/24`` subnet. + +Each of the statements in this configuration file are explained +below :: + + /* C-style comments are supported */ + { + "version":2, + "clients":[ + { + "name":"client192", + "addrlist":"192.168.1.255", + "autoaddrlist":false + } + ], + "servers":[ + { + "name":"server10", + "clients":["client192"], + "interface":["10.1.1.4"], + "addrlist":"10.1.1.255", + "autoaddrlist":false, + "statusprefix":"GW:STS:" /* optional, but suggested */ + } + /* optional, allows server side access to Gateway status */ + ,{ + "name":"server192", + "clients":[], + "interface":["192.168.1.5"], + "addrlist":"192.168.1.255", + "autoaddrlist":false, + "statusprefix":"GW:STS:" + } + ] + } + +The *version* statement is described below. + +The *clients* section specifies the *name* of its only Client to be ``client192`` and is configured to search on the ``192.168.1.0/24`` subnet by +providing the ``192.168.1.255`` broadcast address as the only member of the *addrlist*. +This is the network to which an EPICS IOC is attached, so it will receive broadcast searches +from this gateway acting as a client. + +The *servers* section specifies the *name* of its first Server to be ``server10``, and indicates which *clients* can have access to it, in this case clients which are part of the ``clients192`` section. +It is configured to listen on the ``10.1.1.0/24`` subnet by specifying the local *interface* address ``10.1.1.4``. +This is the network on which an EPICS client such as *pvget* or *pvput* is attached, and this gateway will act as a Server to receive their search messages. +The interface broadcast address is also provided to enable sending of server beacon packets. +This is an optimization to reduce connection time, and it is not required. + +The *statusprefix* value is set to ``GW:STS:`` in this example, allowing the gateway to share some internal PVs which provide status information. +The :ref:`gwstatuspvs` suffixes are described below, with the *statusprefix* prepended. +Sites with multiple gateways on one subnet should give each a unique statusprefix. + +A second *servers* section is shown, with its *name* set to ``server192``. Its set of allowed *clients* is empty, but interfaces and address lists are specified. +This allows the status PVs mentioned above to be accessed from the subnet hosting the IOCs and other EPICS servers. +Without this section, those status PVs are only accessible from EPICS clients on the client subnets. + +.. note:: + A single gateway will not connect to itself (no Gateway client will connect to a Gateway server in the same instance). + However, this automatic loop avoidance is not possible in more complex situations involving multiple gateways. + If such a setup is judged necessary, care should be taken to ensure that loops can not form. + See also the ``servers[].ignoreaddr`` in :ref:`gwconfigfile`. + +Command Line Arguments +---------------------- + +.. argparse:: + :module: p4p.gw + :func: getargs + :prog: pvagw + +.. _gwconfref: + +Configuration File +------------------ + +Configuration is provided as a file using JSON syntax with C-style comments. :: + + /* C-style comments allowed */ + { + "version":2, + "readOnly":false, + "clients":[ + { + "name":"theclient", + "provider":"pva", + "addrlist":"...", + "autoaddrlist":false, + "bcastport":5076 + } + ], + "servers":[ + { + "name":"theserver", + "clients":["theclient"], + "interface":["..."], + "addrlist":"", + "ignoreaddr":["..."], + "autoaddrlist":false, + "serverport":5075, + "bcastport":5076, + "getholdoff":1.0, + "statusprefix":"PV:", + "access":"somefilename.acf", + "pvlist":"somefilename.pvlist" + } + ] + } + +See also PVXS client_ and server_ configuration references. + +.. _client: https://epics-base.github.io/pvxs/client.html#configuration + +.. _server: https://epics-base.github.io/pvxs/server.html#configuration + +Run ``pvagw --example-config -`` to see another example configuration. + +.. _gwconfigfile: + +Configuration File Keywords +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Here is a full list of JSON keys available for the configuration file, version 2. + +**version** + JSON Scheme version number. 2 is recommended for new files. Valid values are 1 or 2. + +**readOnly** (default: false) + Boolean flag which, if set, acts as a global access control rule which rejects + all PUT or RPC operations. This takes precedence over any ACF file rules. + +**clients** + List of Gateway Client configurations. + +**clients[].name** + Unique name for this Client within this gateway process. + +**clients[].provider** (default: "pva") + Selects a ChannelProvider. Currently only "pva" is valid. + +**clients[].addrlist** (default: "") + List of broadcast and unicast addresses to which search messages will be sent. + +**clients[].autoaddrlist** (default: true) + Whether to automatically populate *addrlist* with **all** local interface broadcast addresses. + Use caution when setting ``true``. + +**clients[].bcastport** (default: 5076) + UDP port to which searches are sent. + +**servers** + List of gateway Server configurations. + +**servers[].name** + Unique name of this Server within this gateway process. + +**servers[].clients** + A list of zero or more gateway Client names. + Search requests allowed through this server will be made through all listed clients. + +**servers[].interface** (default: ["0.0.0.0"]) + A list of local interface addresses to which this gateway Server will bind. + +**servers[].addrlist** (default: "") + List of broadcast and unicast addresses to which beacon messages will be sent + +**servers[].ignoreaddr** (default: "") + List of address to add into the banned list to explicit ignore hosts. + +**servers[].autoaddrlist** (default: true) + Whether to automatically populate *addrlist* with **all** local interface broadcast addresses. + Use caution when setting ``true``. + +**servers[].serverport** (default: 5075) + Default TCP port to bind. If not possible, a random port will be used. + +**servers[].bcastport** (default: 5076) + UDP port bound to receive search requests, as well as the port to which beacons are sent. + +**servers[].getholdoff** (default: 0) + A value greater than zero enables rate limiting of Get operations. + ``getholdoff`` defines a hold-off time after a GET on a PV completes, before the another will be issued. + Another GET for the same PV made before the hold-off expires will be delayed until expiration. + Concurrent GET operations may be combined. + + This activity is per PV. + +**servers[].statusprefix** (default: "") + The text used by this gateway as a prefix to construct names for PVs which communicate status information. + The PVs report overall status for the gateway process, regardless of the number of internal Clients or Servers. + Each of the status PVs are defined in :ref:`gwstatuspvs`. + Note that the prefix will typically end with the delimiter used in your PV naming convention, such as ``:``. + +**servers[].access** (default: "") + Name an ACF file to use for access control decisions for requests made through this server. + See :ref:`gwacf`. + Relative file names are interpreted in relation to the directory containing the config file. + +**servers[].pvlist** (default: "") + Name of PVList file used to restrict access to certain PVs through this Server. + See :ref:`gwpvlist`. + Relative file names are interpreted in relation to the directory containing the config file. + +**servers[].acf_client** + Needed only if ``access`` key is provided, and ``clients`` list has more than one entry. + Unambiguously selects which client is used to connect ``INP`` PVs for use by conditional ACF rules. + If not provided, then the first client in the list is used. + +.. _gwstatuspvs: + +Status PVs +---------- + +Servers with the ``statusprefix`` key set will provide access to the following PVs. +These values are aggregated from all defined internal gateway Servers and Clients. + +.. warning:: + The PV names resulting from the ``statusprefix`` and the PV suffixes shown below must be unique across your site. + Each gateway instance must have a unique ``statusprefix`` value. + +**asTest** + An RPC only PV which allows testing of PVList and ACF rules. :: + + $ pvcall asTest pv=some:name + + Other arguments include ``user="xx"``, ``peer="1.1.1.1:12345``, and ``roles=["yy"]``. + If omitted, the credentials of the requesting client are used. + +**clients** + A list of client's names connected to the GW server + +**cache** + A list of channels to which the GW Client is connected + +**refs** + Table of object type names and instance counts. + May be useful for detecting resource leaks while troubleshooting. + +**threads** + Available when running with python >= 3.5. + An RPC call which returns a text description of all python threads. + +.. note:: + The following PVs provide data bandwidth information for the overall gateway. + + * The ``ds`` in the names refer to *downstream* requests from EPICS clients to the gateway, or responses from the gateway to EPICS clients. + * The ``us`` in the names refer to *upstream* requests from the gateway to IOCs, or responses from an IOC to the gateway. + * The ``bypv`` or ``byhost`` in the names refer to status relating to the involved PVs or host machines, respectively. + * The ``rx`` and ``tx`` in the names refer to receiving or transmitting data from the gateway's perspective. + +**ds:bypv:rx** + A table containing bandwidth usage of requests for each PV sent from PVA clients such as **pvget** or **pvput** to this gateway. This can be a relatively low number since the requests are often small in size. + The table is sorted from highest bandwidth PVs to lowest. + +**us:bypv:tx** + A table containing bandwidth usage of requests for each PV sent from this gateway to PVA Servers such as IOCs. This can be a relatively low number since the requests are often small in size. + The table is sorted from highest bandwidth PVs to lowest. + +**us:bypv:rx** + A table containing bandwidth usage of responses from each PV sent from PVA Servers such as IOCs to this gateway. + The table is sorted from highest bandwidth PVs to lowest. + +**ds:bypv:tx** + A table containing bandwidth usage of responses from each PV sent from this gateway to EPICS clients that made the original requests. + The table is sorted from highest bandwidth PVs to lowest. + +**ds:byhost:rx** + A table containing bandwidth usage of each host sending requests from PVA clients such as **pvget** or **pvput** to this gateway. This can be a relatively low number since the requests are often small in size. + The table is sorted by host machine with the highest bandwidth usage to lowest. + +**us:byhost:tx** + A table containing bandwidth usage of requests sent from this gateway to each host containing PVA Servers such as IOCs. This can be a relatively low number since the requests are often small in size. + The table is sorted by host machine with the highest bandwidth usage to lowest. + +**us:byhost:rx** + A table containing bandwidth usage of each host providing responses from PVA Servers such as IOCs to this gateway. + The table is sorted by host machine with the highest bandwidth usage to lowest. + +**ds:byhost:tx** + A table containing bandwidth usage of each client's host accepting responses from this gateway. + The table is sorted by host machine with the highest bandwidth usage to lowest. + +.. _gwlogconfig: + +Log File Configuration +---------------------- + +The gateway is able to record messages associated with important events to one or more destinations as it runs, +including log files or a console device. +The messages can be debugging aids for developers, +or errors encountered as the gateway is working. +It also records the time at which the gateway starts or stops, and when starting, +lists the configuration details for the internal clients and servers, and lists each status PV that the gateway will make available. + +A python `dictConfig `_ +logging configuration file in JSON format can be passed to ``--logging`` +to provide control of formating of the logged messages. + +One logger name of special interest is ``p4p.gw.audit`` which is used for messages arising from :ref:`trapwrite`. + +The following is an example of a log configuration file which records ``INFO`` messages or worse to a log file, +but also records ``WARNING`` messages or worse to the computer console. +It specifies different formats for console-bound messages versus log file messages, +and instructs the system to maintain daily log files (and audit files, if enabled), +in a subdirectory called ``BL3-LOGS``. +It will create new, empty log files each midnight while keeping previous log files for 14 days. + +Note that fixed-width columns are specified for some fields using sequences like ``15s``, ``-4d`` or ``4.4s``, +similar to ``printf`` style format specifiers: :: + + { + "version": 1, + "disable_existing_loggers": false, + "formatters": { + "fileFormat": { + "format": "%(asctime)s | %(name)15s line %(lineno)-4d [%(levelname)4.4s] %(message)s" + }, + "consoleFormat": { + "format": "%(asctime)s | %(name)s: %(levelname)s - %(message)s" + } + }, + "handlers": { + "fileMessages": { + "level": "INFO", + "class": "logging.handlers.TimedRotatingFileHandler", + "formatter": "fileFormat", + "filename": "BL3-LOGS/gateway-BL3-DMZ.log", + "when": "midnight", + "interval": 1, + "backupCount": 14 + }, + "consoleMessages": { + "level": "WARNING", + "class": "logging.StreamHandler", + "formatter": "consoleFormat", + "stream": "ext://sys.stdout" + } + }, + "loggers": { + "": { + "handlers": ["fileMessages","consoleMessages"], + "level": "INFO", + "propagate": true + } + } + } + +.. _gwsec: + +Access Control Model +-------------------- + +A gateway may apply access control restrictions in addition to any restrictions +applied by individual IOCs, or other PVA servers, to which it connects. +By default a gateway apply **no restrictions**. +A gateway without a :ref:`gwpvlist` or :ref:`gwacf` will allow all clients to attempt any operation on any PV. + +One or more of the ``readOnly``, ``access``, and/or ``pvlist`` configuration file keys enable +restrictions within a gateway. + +The **simplest and most direct restriction is the readOnly** configuration file key, +which applies to all logical Servers within a gateway. +If set, no PUT or RPC operations are allowed. +Both MONITOR and GET operations are allowed, so ``readOnly`` applies a simple one-way policy +to allow clients to receive data without being permitted to change any PV settings. + +A more granular policy is often desired, +which can be expressed with a :ref:`gwpvlist` and/or :ref:`gwacf`. + +Access decisions are made as follows: + +1. PV name and client IP address are looked up in a PVList. + If DENY, then client searches are ignored. +2. If ``readOnly`` is set, then any PUT or RPC operation is rejected. GET/MONITOR proceed. +3. The PV name and peer IP address are looked up in a PVList. + If DENY, then the operation is rejected. + If ALLOW/ALIAS then an ASG name and level (0 or 1) is found. +4. The ASG name and level are look up in a ACF file. + GET/MONITOR operations are always allowed (no write only PVs). + PUT or RPC operations are allowed if appropriate WRITE/PUT/RPC permission is granted. + +.. _gwpvlist: + +PVList File +----------- + +The purpose of the PVList file is to specify which PVs are allowed or denied, +and to associate those PVs with access security groups (ASG) and security levels (ASL) in the access file. +Supported PVList file syntax is mostly compatible with that of the Channel Access Gateway_. + +.. _Gateway: https://epics.anl.gov/EpicsDocumentation/ExtensionsManuals/Gateway/Gateway.html + +If not provided, the default PVList file used is ``.* ALLOW``. + +While allows all PV names from all clients. + +PVList files are line based, with lines consisting of the following. + +.. note:: Matching is *not* in strict lexical order. See below. + +#. Blank lines and ``#`` comments are allowed. :: + + # comment line + +#. **Evaluation order statement**, primarily to maintain backward compatibility with CA Gateway. :: + + # (default if omitted) + EVALUATION ORDER ALLOW, DENY + + # Not currently supported + #EVALUATION ORDER DENY, ALLOW + +#. **A DENY statement** which specifies that certain PVs are denied access from certain EPICS clients. + It can specify an optional host from which clients will be denied access. + ```` is a `regular expression`_ to match PV names. + This statement is of the forms :: + + DENY + DENY FROM + +.. _regular expression: https://docs.python.org/3/library/re.html#regular-expression-syntax + +#. **An ALLOW statement** which specifies that certain PVs are allowed to be accessed from EPICS clients. + It can specify an optional *Access Security Group* (ASG), + with an accompanying but optional *Access Security Level* (``0`` or ``1``), + both of which used when evaluating an **ACF** file. + This statement is of the forms :: + + ALLOW + ALLOW + ALLOW + +If not provided, ``ASG`` is ``DEFAULT``, and ``ASL`` is ``0``. + +#. **An Alias statement** which provides a way to specify a specific PV name based on a more general pattern. + This is equivalent to a **ALLOW** statement with an additional name translation. + This statement is of the forms :: + + ALIAS + ALIAS + ALIAS + +When a gateway Server receives a request from a client to access a PV, +the PV name is compared to each pattern in the list. + +The order in which regular expressions are matched is that all DENY statements are considered +before any ALLOW/ALIAS statements (regardless of the order of lines). +PV names which do not match any statement are DENYed. + +When a PV name matches more than one ALLOW/ALIAS statements, +the order of lines is used. +The last match will have effect. + +Considering the following PVList file: :: + + ACCL:CRYO:.* DENY + ACCL:.* ALLOW MISCONFIG + ACCL:.* ALLOW + ACCL:RF.* ALLOW RF + +``ACCL:CRYO:ESTOP`` would match the ``DENY`` rule, so a gateway will not allow any access. + +``ACCL:RF:FPWR`` would match the ``ALLOW RF`` rule, and be allowed subject to rules for ``ASG(RF)``. + +``ACCL:ARC:CNT`` would match the last ``ALLOW`` rule, and be allowed subject to ``ASG(DEFAULT)``. + +Because both the ``ALLOW MISCONFIG`` and ``ALLOW`` rules have identical patterns, +the ``ALLOW`` will always be used and ``ALLOW MISCONFIG`` will never be used. + +Note that because ``DENY`` rules are always considered before ``ALLOW`` or ``ALIAS`` rules, +the preceding file is functionally identical to the following as moving the ``DENY`` +relative to ``ALLOW`` does not change the evaluation order. :: + + ACCL:.* ALLOW MISCONFIG + ACCL:.* ALLOW + ACCL:RF.* ALLOW RF + ACCL:CRYO:.* DENY + +When building a PVList file containing ``ALLOW`` or ``ALIAS`` rules with overlapping patterns, +it is therefore necessary to put the more general patterns before the more specific patterns. +eg. :: + + ACCL:RF.* ALLOW RF + ACCL:.* ALLOW + +In this example the ``ALLOW RF`` rule is effectively hidden, and will never be matched. + + +.. _gwacf: + +ACF Rules File +-------------- + +An Access Security File (ACF) is a list of access control rules to be applied +to requests based on which Access Security Group (``ASG``) was selected by a PVList file, or ``DEFAULT`` +if no PVList file is used. The ``ASG`` name selects which a group of rules. + +Unknown ``ASG`` names use the ``DEFAULT`` rules. +If no ``DEFAULT`` group is defined, then no privileges are granted. + +Each ACF file may define zero or more Host Access Groups (``HAG`` s) and/or +User Access Groups (``UAG`` s). +Also, one or more list of rules (``ASG`` s). +The HAG is a list of host names, and the UAG a list of user names. + +eg. PVs in ASG ``DEFAULT`` only permit PUT or RPC requests originating from +hosts ``incontrol`` or ``physics``. +PUT requests from ``physics`` will be logged. :: + + HAG(MCF) { "incontrol" } + HAG(OTHER) { "physics" } + ASG(DEFAULT) { + RULE(1, WRITE) { + HAG(MCF) + } + RULE(1, WRITE, TRAPWRITE) { + HAG(OTHER) + } + } + +Privileges +~~~~~~~~~~ + +``RULE`` s may grant one of the following privileges. + +``WRITE`` + Shorthand to grant both ``PUT`` and ``RPC`` requests. + +``PUT`` + Allow PUT operation on all fields. + +``RPC`` + Allow RPC operations. + +``UNCACHED`` + Special privilege which allows a client to bypass deduplication/sharing of subscription data. + A client would make use of this privilege by including a pvRequest option ``record._options.cache`` + with a boolean false value. + +``READ`` + Accepted for compatibility. + PVA Gateway always allows read access for any PV which is allowed by the PVList file. + Use a ``DENY`` in a PVList file to prevent clients from reading or subscribing to certain PVs. + +HAG Hostnames and IPs +~~~~~~~~~~~~~~~~~~~~~ + +Entries in a ``HAG()`` may be either host names, or numeric IP addresses. +Host names are resolved once on Gateway startup. +Therefore, changes in the hostname to IP mapping will not be visible +until a Gateway is restarted. + +.. _gwpvcred: + +UAG and Credentials +~~~~~~~~~~~~~~~~~~~ + +PV Access protocol provides a weakly authenticated means of identification based on a remotely provided user name. +This is combined with a set of "role"s taken by looking up system groups of which the username is a member. +(See ``/etc/nsswitch.conf`` on Linux). + +Both user and role names may appear in ``UAG`` lists. eg. :: + + UAG(SPECIAL) + { + root, + "role/admin" + } + +And a rule: :: + + ASG(DEFAULT) { + RULE(1, WRITE) { + UAG(SPECIAL) + } + } + +In this case, the ``RULE`` will be match if a client identifies itself with username ``root`` +or if the (remotely provided) username is a member of the (locally tested) ``admin`` role (eg. unix group). + +In this case, such a match will grant the ``WRITE`` privilege for PVs in the ``DEFAULT`` ASG. + +Role/group membership can be tested with the ``asTest`` status PV. + +.. _trapwrite: + +TRAPWRITE and Put logging +~~~~~~~~~~~~~~~~~~~~~~~~~ + +If a ``RULE`` includes the ``TRAPWRITE`` modifier, then a ``PUT`` operation it allows +will be logged. +Refer to the :ref:`gwlogconfig` section for more information. + +Messages are logged through the ``p4p.gw.audit`` python logger. + +ACF Syntax +~~~~~~~~~~ + +.. productionlist:: acf + acf: | item acf + item : uag | hag | asg + uag : UAG ( "NAME" ) { users } + hag : HAG ( "NAME" ) { hosts } + asg : ASG ( "NAME" ) { asitems } + users : "HOSTNAME" + :"HOSTNAME" , users + hosts : "USERNAME" + : "USERNAME" , hosts + asitems : | asitem asitems + asitem : INP[A-Z] ( "PVNAME" ) + : RULE ( ASL#, priv) rule_cond + : RULE ( ASL#, priv, trap) rule_cond + priv : READ | WRITE | PUT | RPC | UNCACHED + trap : TRAPWRITE | NOTRAPWRITE + rule_cond : | { conds } + conds : | cond conds + cond : UAG ( "NAME" ) + : HAG ( "NAME" ) + : CALC ( "EXPR" ) + +Application Notes +----------------- + +The process of configuring a Gateway begins by looking at the +physical and/or logical topology of the networks in question. + +A Gateway is typically placed at the boundary between one or more networks (subnets). + +While a simple Gateway configuration will have a single GW Server connected to a single GW Client, +more complicated configurations are possible, with many GW Servers and one GW Client, +or one GW Server and many GW Clients, or a many to many configuration. + +It is valid for a GW Client and GW Server to be associated with the same host interface and port +provided that they are not associated with each other. +Pairs of such GW Client and GW Server may be cross linked to form a bi-directional Gateway. + +It is meaningful to configure a GW Server with no GW Clients ( ``"clients":[]`` ) +provided that the ``"statusprefix"`` key is set. +This server will only provide the status PVs. +This can be used to eg. provide GW status monitoring from both sides of a one-way Gateway. + + +Differences from CA gateway +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Summary of known differences from CA gateway. + +* ``EVALUATION ORDER DENY, ALLOW`` is not supported. + +* Permission ``READ`` is implied. Write-only PVs are not possible. + +Implementation Details +---------------------- + +Gateway is implemented as a hybrid of Python and C++. +In the interest of performance, Python code is only in the "slow" path +for the PV search/connection decision. +After a PV is connected; permissions changes, auditing, and monitoring are communicated +externally from Python code. + +The APIs described below are not currently considered stable or public for use by external modules. +They are documentation here for the purposes of internal development and debugging. + +Negative Results Cache +~~~~~~~~~~~~~~~~~~~~~~ + +In order to shield the Python testChannel() handler from repeated reconnect attempts +for denied PVs, a list of blocked PVs, IPs, and pairs of PV and IP +is maintained in C++ code. Search requests matching one of these three criteria +will be ignored without calling testChannel(). + +p4p.gw Frontend +~~~~~~~~~~~~~~~ + +This module utilizes the related C++ extension to setup and manage a Gateway +which is configured in a manner similar to the `pva2pva gateway `_ +with an access control policy defined in a manner similar to `cagateway `_. +Other means of configuration and policy definition could be implemented. + +C++ Extension +~~~~~~~~~~~~~ + +Setup execution flow for use of the C++ extension is: + +1. Create a `ClientProvider` +2. Create a `Provider` using this client +3. Create a `p4p.server.Server` referencing the provider name. + +More than one `Provider` may reference to the same `ClientProvider`. +A `p4p.server.Server` may reference more than one `Provider`, +and a `Provider` may be referenced by more than one `p4p.server.Server`. +Many `p4p.server.Server` s may be created. + +After server startup, the handler object associated with a `Provider` +will be called according to the `_gw.ProviderHandler` interface. + +The C++ extension deals only with IP addresses in string form, +possibly with port number (eg. "1.2.3.4:5076)", and never host names. + +.. module:: p4p._gw + +.. autoclass:: Provider + + .. autoattribute:: Claim + + .. autoattribute:: Ignore + + .. autoattribute:: BanHost + + .. autoattribute:: BanPV + + .. autoattribute:: BanHostPV + + .. automethod:: testChannel + + .. automethod:: sweep + + .. automethod:: forceBan + + .. automethod:: clearBan + + .. automethod:: cachePeek + + .. automethod:: stats + + .. automethod:: report + +.. autoclass:: InfoBase + :members: + :undoc-members: + +.. autoclass:: CreateOp + :members: + :undoc-members: + +.. autoclass:: Channel + :members: + :undoc-members: + +Interfaces +~~~~~~~~~~ + +.. class:: ProviderHandler + + A Handler object associated with a `Provider` should implement these methods + + .. method:: testChannel(self, pvname, peer) + + :param str pvname: PV name being searched (downstream) + :param str peer: IP address of client which is searching + :returns: Claim, Ignore, BanHost, BanPV, or BanHostPV + + Hook into search phase. Called each time a client searches for a pvname. + If permitted, call and return the result of `Provider.testChannel()` with the desired upstream (server-side PV name). + + * Returning Claim may result in a later call to `makeChannel()`. + * Returning Ignore may result in a repeated call to testChannel() in future. + * Returning BanHost adds this host to the negative results cache + * Returning BanPV adds this PV to the negative results cache. + * Returning BanHostPV adds this combination of host and PV to the negative results cache + + .. method:: makeChannel(self, op) + + Hook info channel creation phase. If permitted, call and return the result of `CreateOp.create()`. + The `Channel` object may be stored by python code to track and effect active connections. + eg. call `Channel.access()` to set/change privileges. + Or `Channel.close()` to force disconnection. + + Due to the continuous nature of PVA client (re)connection process, inability to create + a channel at this stage is treated as a hard failure to avoid a reset loop. + If it is necessary to return None, then steps should be taken to ensure that a + re-connection attempt would have a different result. eg. through `Provider.forceBan()`. + + :param CreateOp op: Handle for ongoing operation + :returns: A `Channel`. + + .. method:: audit(self, msg) + + Hook info PUT logging process. Called from a worker thread. + + :param str msg: Message string to be logged diff --git a/_sources/index.rst.txt b/_sources/index.rst.txt new file mode 100644 index 00000000..fbda1843 --- /dev/null +++ b/_sources/index.rst.txt @@ -0,0 +1,47 @@ +PVAccess for Python (P4P) +========================= + +**P4P** is a wrapper around the PVAccess (aka. PVA) protocol network client and server. +P4P is part of the **EPICS** (Experimental Physics and Industrial Control System) ecosystem +for creating large (and small) scale distributed process control and data acqisition sytems. +https://epics.anl.gov/ + +P4P includes API for a `clientapi` and `serverapi`, +as well as a `gwpage` executable (``pvagw``) which can optionally enforce an access control policy. + +Supports Linux, OSX, and Windows. With python 2.7 and >=3.5 (>=3.6 for asyncio support). + +The recommended starting point is to install from pypi.org. :: + + python -m virtualenv p4ptest + . p4ptest/bin/activate + python -m pip install -U pip + python -m pip install p4p nose2 + python -m nose2 p4p # Optional: runs automatic tests + +- VCS: https://github.com/epics-base/p4p +- Docs: https://epics-base.github.io/p4p/ + +Contents: + +.. toctree:: + :maxdepth: 2 + + starting + overview + building + client + nt + values + server + rpc + internal + gw + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/_sources/internal.rst.txt b/_sources/internal.rst.txt new file mode 100644 index 00000000..f5ec3add --- /dev/null +++ b/_sources/internal.rst.txt @@ -0,0 +1,62 @@ +Internal API +============ + +This section is intended to help P4P developers. +The API described is *not* considered a public or stable API. +It may change without notice. + +Ownership +--------- + +The ownership relations between the various objects in the C++ +extensions are shown in the following diagrams. + +* Python objects are blue ovals +* C++ objects are black boxes + +* red lines are shared_ptr<> +* green lines are weak_ptr<> +* blue lines are python refs. (aka stored PyObject*) +* dashed lines are explicit breaks of a ref. loop + +Type and Value +~~~~~~~~~~~~~~ + +.. digraph:: values + + Value [shape=oval, color=blue]; + Type [shape=oval, color=blue]; + Array [shape=oval, color=blue]; + ndarray [shape=oval, color=blue]; + PVStructure [shape=box]; + Structure [shape=box]; + shared_vector [shape=box]; + + # wraps + Value -> PVStructure [color=red]; + Type -> Structure [color=red]; + Array -> shared_vector [color=red]; + # internal + PVStructure -> shared_vector [color=red]; + PVStructure -> Structure [color=red]; + # pyrefs + ndarray -> Array [color=blue]; + +API Reference +------------- + +Raw client API +~~~~~~~~~~~~~~ + +.. currentmodule:: p4p.client.raw + +.. automodule:: p4p.client.raw + :members: + +Raw server API +~~~~~~~~~~~~~~ + +.. currentmodule:: p4p.server.raw + +.. automodule:: p4p.server.raw + :members: diff --git a/_sources/nt.rst.txt b/_sources/nt.rst.txt new file mode 100644 index 00000000..9b7c065e --- /dev/null +++ b/_sources/nt.rst.txt @@ -0,0 +1,159 @@ +.. _ntapi: + +Common Types +============ + +.. currentmodule:: p4p.nt + +Helpers for creating standardized :py:class:`Type` instances. +as defined by http://epics-pvdata.sourceforge.net/alpha/normativeTypes/normativeTypes.html +. + +.. _unwrap: + +Automatic Value unwrapping +-------------------------- + +Automatic transformation can be performed. between `Value` and more convenient types. + +Transformation may be performed at the following points: + +* The result of `p4p.client.thread.Context.get()`, +* The argument the callable passed to `p4p.client.thread.Context.monitor()` +* The argument of `p4p.client.thread.Context.put()` +* The argument of `p4p.client.thread.Context.rpc()` +* The argument of `p4p.server.thread.SharedPV.open()` +* The argument of `p4p.server.thread.SharedPV.post()` +* The result of `p4p.server.thread.SharedPV.current()` + +Controlling (Un)wrapping +^^^^^^^^^^^^^^^^^^^^^^^^ + +Client `p4p.client.thread.Context` accepts an argument nt= which may be +``None`` to sure some reasonable defaults. ``False`` disables wrapping, +and always works with `Value`. *nt=* may also be passed a dictionary +keyed by top level structure IDs mapped to callables returning objects +conforming to `WrapperInterface`. + +The *unwrap* argument is legacy which functions like *nt=* but +mapping to plain functions instead of wrapper objects. :: + + from p4p.client.thread import Context + ctxt=Context('pva', nt=False) # disable (un)wrap. All methods use Value + +Server `p4p.server.thread.SharedPV` accepts an argument *nt=* which +is an instance of an object conforming to `WrapperInterface`. :: + + from p4p.server.thread import SharedPV + from p4p.nt import NTScalar + pv1 = SharedPV() # pv1.open() expects a plain Value + pv2 = SharedPV(nt=NTScalar('d', display=True)) + + # NTScalar automatically wraps this float into a Value + pv2.open(4.2) + + # send change w/ system times + pv2.post(3.3, timestamp=time.time()) + + # explicitly wrap and set additional fields + V = pv2.wrap(2.2, timestamp=time.time()) + V['display.description'] = "My special PV" + pv2.post(V) + +Conforming objects include `NTScalar`, `NTNDArray`, and others listed below. + +.. autofunction:: defaultNT + +NT wrap/unwrap interface +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. class:: WrapperInterface + + :since: 3.1.0 + + .. classmethod:: buildtype() + + Returns a `Type` based on some helper specific conditions. + + :rtype: `Type` + + .. method:: __init__ + + Each time the type ID of a Channel changes, a new wrapper will be instantiated if available. + + .. method:: unwrap(Value) -> object + + Called with a `Value` and may return an arbitrary object. + + Called by both clients and servers. eg. during `p4p.client.thread.Context.get()` + and `p4p.server.thread.SharedPV.current()`. + + .. method:: wrap(object) -> Value + + Called with an arbitrary object which it should try to translate into a `Value`. + + Called by servers. eg. during `p4p.server.thread.SharedPV.post()`. + + .. method:: assign(Value, object) + + Called to update a `Value` based on an arbitrary object. + + Called by clients. eg. during `p4p.client.thread.Context.put()`, where + the get= argument effects the state of the `Value` passed in. + +API Reference +------------- + +.. autoclass:: NTScalar + + .. automethod:: buildType + + .. automethod:: wrap + + .. automethod:: assign + + .. automethod:: unwrap + +.. autoclass:: NTNDArray + + .. automethod:: buildType + + .. automethod:: wrap + + .. automethod:: assign + + .. automethod:: unwrap + +.. autoclass:: NTTable + + .. automethod:: buildType + + .. automethod:: wrap + + .. automethod:: unwrap + +.. autoclass:: NTURI + + .. automethod:: buildType + + .. automethod:: wrap + +.. autoclass:: NTMultiChannel + + .. automethod:: buildType + +.. currentmodule:: p4p.nt.scalar + +.. autoclass:: ntfloat + +.. autoclass:: ntint + +.. autoclass:: ntstr + +.. autoclass:: ntnumericarray + +.. autoclass:: ntstringarray + +.. currentmodule:: p4p.nt.ndarray + +.. autoclass:: ntndarray diff --git a/_sources/overview.rst.txt b/_sources/overview.rst.txt new file mode 100644 index 00000000..26162a77 --- /dev/null +++ b/_sources/overview.rst.txt @@ -0,0 +1,71 @@ +Overview +======== + +.. currentmodule:: p4p + +What is EPICS? +~~~~~~~~~~~~~~ + +See https://epics.anl.gov/ + +.. _overviewpva: + +What is PVAccess? +~~~~~~~~~~~~~~~~~ + +The PVAccess network protocol is a hybrid supporting request/response, +and publish/subscribe operations. + +PVA is closely related to the Channel Access (CA) protocol, +which may work along side, and is intended to supersede. + +Four protocol operations are supported through the P4P wrapper. + +- Get - Fetch the present value of a PV. +- Put - Change the value of a PV. +- Monitor - Subscribe to changes in the value of a PV. +- RPC - A remote method call. + +Get, Put, Monitor, and RPC are to the PVA protocol what GET, PUT, POST are to the HTTP protocol. + +What is a PV? +~~~~~~~~~~~~~ + +In the EPICS world a Process Variable (PV) refers to the idea of +a globally addressed data structure. An EPICS control system is +composed of many PVs (in the millions for large facilities). The present value of +a PV is modified by a combination of remote operations via CA +and/or PVA, and via local processing (eg. values read from local +hardware). + +A common example of a PV is a measurement value, for example +a temperature measured by a particular sensor. + +Another example would be an electro-mechanical relay, which may be opened or closed. + +In this case a Get operation would poll the current open/closed state of the relay. +A Monitor operation (subscription) would receive notification when the relay state changes. +A Put operation would be used to command the relay to open or close, or perhaps toggle (the precise meaning of a Put is context dependent). + +So the Get, Put, and Monitor operation on a given PV are conventionally operating on a common data structure. +The RPC operation is more arbitrary, and need not have any relationship with a common data structure (eg. the open/closed state of the relay.) + +.. note:: In the context of the PVA or CA protocols, a **"PV name"** is an address string which uniquely identifies a Process Variable. + All PVA network operations begin with a "PV name" string. + +A "PV name" string is to the PVA and CA protocols what a URL is to the HTTP protocol. +The main difference being that while a URL is hierarchical, having a hostname and path string, +a PV name is not. The namespace of PV names is by default all local IP subnets (broadcast domains). +This can be made more complicated though the specifics of client/server network configuration. + +The P4P module provides the ability to run PVA clients (:ref:`clientapi`) and/or servers (:ref:`serverapi`). +Additional convenience APIs are provided when using the RPC network operation (:ref:`rpcapi`). + +What is a Value? +~~~~~~~~~~~~~~~~ + +P4P represents the data which goes into, and results from, PVA network operations +with the :py:class:`Value` class which represents a strongly typed data structure. +See :ref:`valueapi` for details. + +A set of standardized data structure definitions, and utilities is provided as the :ref:`ntapi` API. diff --git a/_sources/rpc.rst.txt b/_sources/rpc.rst.txt new file mode 100644 index 00000000..0d3bcc6e --- /dev/null +++ b/_sources/rpc.rst.txt @@ -0,0 +1,135 @@ +.. _rpcapi: + +RPC Server Helpers +================== + +.. currentmodule:: p4p.rpc + +Server Example +-------------- + +Remote Procedure Calls are received by the methods of a "target" object. +This is any class which has method decorated with :py:func:`rpc`. + +For example: :: + + from p4p.rpc import rpc, quickRPCServer + from p4p.nt import NTScalar + class Summer(object): + @rpc(NTScalar("d")) + def add(self, lhs, rhs): # 'lhs' and 'rhs' are arbitrary names. The method name 'add' will be part of the PV name + return float(lhs) + float(rhs) + adder = Summer() + +Turn on logging to see RPC related errors. :: + + import logging + logging.basicConfig(level=logging.DEBUG) + +Now run a server with :func:`quickRPCServer`. :: + + quickRPCServer(provider="Example", + prefix="pv:call:", # A prefix for method PV names. + target=adder) + +At this point the server is active. + +Beginning with EPICS 7.0.2 this can be tested using the "pvcall" utility + +.. code-block:: sh + + $ pvcall pv:call:add lhs=1 rhs=1 + 2018-10-30 19:49:34.834 2 + +Previous to EPICS 7.0.2 this can be tested using the "eget" utility from the pvAccessCPP module. + +.. code-block:: sh + + $ eget -s pv:call:add -a lhs=1 -a rhs=1 + 2 + $ eget -s pv:call:add -a lhs=1 -a rhs=1 -N # for more detail + epics:nt/NTScalar:1.0 + double value 2 + alarm_t alarm NO_ALARM NO_STATUS + time_t timeStamp 2017-05-20T08:14:31.917 0 + +Client Example +-------------- + +Remote procedure calls are made through the :meth:`~p4p.client.thread.Context.rpc` method of a :class:`~p4p.client.thread.Context`. +To assist in encoding arguments, a proxy object can be created with the :func:`rpcproxy` decorator. +A proxy for the preceding example would be: :: + + from p4p.rpc import rpcproxy, rpccall + @rpcproxy + class MyProxy(object): + @rpccall('%sadd') + def add(lhs='d', rhs='d'): + pass + +This proxy must be associated with a Context. :: + + from p4p.client.thread import Context + ctxt = Context('pva') + proxy = MyProxy(context=ctxt, format='pv:call:') + print proxy.add(1, 1) + + +A decorated proxy class has two additional contructor arguments. + +Using Low Level Client API +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It may be helpful to illustrate what a proxy method call is actually doing. :: + + from p4p import Type, Value + V = Value(Type([ + ('schema', 's'), + ('path', 's'), + ('query', ('s', None, [ + ('lhs', 'd'), + ('rhs', 'd'), + ])), + ]), { + 'schema': 'pva', + 'path': 'pv:call:add', + 'query': { + 'lhs': 1, + 'rhs': 1, + }, + }) + print ctxt.rpc('pv:call:add', V) + +API Reference +------------- + +.. autofunction:: rpc + +.. autofunction:: rpcproxy + +.. autofunction:: rpccall + +.. autofunction:: quickRPCServer + +.. autoclass:: RPCProxyBase + + :param Context context: The client :class:`~p4p.client.thread.Context` through which calls are made + :param format: A tuple or dict which is applied with the format '%' operator to the name strings given to :func:`rpccall`. + + .. autoattribute:: context + + .. autoattribute:: timeout + + .. autoattribute:: authority + + .. autoattribute:: throw + +.. autoclass:: NTURIDispatcher + +.. autoclass:: RemoteError + +.. autoclass:: WorkQueue + + .. automethod:: handle + + .. automethod:: interrupt diff --git a/_sources/server.rst.txt b/_sources/server.rst.txt new file mode 100644 index 00000000..b136ac9d --- /dev/null +++ b/_sources/server.rst.txt @@ -0,0 +1,206 @@ +.. _serverapi: + +Server API +========== + +.. currentmodule:: p4p.server + +Running a PVA Server +-------------------- + +A :py:class:`Server` instance starts/stops a PVAccess server. +In order to be useful, a Server must be associated with one or more Providers. + +Two Provider containers are available: :py:class:`StaticProvider` or :py:class:`DynamicProvider`. +Both are used with one of the SharedPV classes:, +:py:class:`thread.SharedPV`, :py:class:`asyncio.SharedPV`, and/or :py:class:`cothread.SharedPV`. +Instances of these different concurrency models may be mixed into a single Provider. + +Example +^^^^^^^ + +A server with a single "mailbox" PV. :: + + import time + from p4p.nt import NTScalar + from p4p.server import Server + from p4p.server.thread import SharedPV + + pv = SharedPV(nt=NTScalar('d'), # scalar double + initial=0.0) # setting initial value also open()'s + @pv.put + def handle(pv, op): + pv.post(op.value()) # just store and update subscribers + op.done() + + Server.forever(providers=[{ + 'demo:pv:name':pv, # PV name only appears here + }]) # runs until KeyboardInterrupt + +This server can be tested using the included command line tools. eg. :: + + $ python -m p4p.client.cli get demo:pv:name + $ python -m p4p.client.cli put demo:pv:name + $ python -m p4p.client.cli get demo:pv:name + +And in another shell. :: + + $ python -m p4p.client.cli monitor demo:pv:name + +Note that this example allows clients to change any field, not just '.value'. +This may be restricted by inspecting the `Value` returned by 'op.value()' +to see which fields are marked as changed with eg. `Value.changed()`. + +A client put operation can be failed with eg. 'op.done(error="oops")'. + +In the put handler function 'pv' is the `SharedPV` and 'op' is a `ServerOperation`. + +Server API +---------- + +.. autoclass:: Server + + .. automethod:: conf + + .. automethod:: stop + +.. autoclass:: StaticProvider + + .. automethod:: close + + .. automethod:: add + + .. automethod:: remove + + .. automethod:: keys + +For situations where PV names are not known ahead of time, +or when PVs are "created" only as requested, DynamicProvider should be used. + +.. autoclass:: DynamicProvider + + .. autoattribute:: NotYet + + +DynamicProvider Handler Interface +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A :py:class:`DynamicProvider` Handler class will define the following: + +.. class:: ProviderHandler + + .. method:: testChannel(pvname) + + Called with a PV name which some client is searching for. + + :return: True to claim this PV. False to "permenently" disclaim this PV. Or :py:attr:`DynamicProvider.NotYet` to temporarily disclaim. + + Each DynamicProvider maintains a cache of negative search results (when ```testChannel()==False```) + to avoid extra work on a subnet with many clients searching for non-existant PVs. + If it is desirable to defeat this behavour, for example as part of lazy pv creation, + then testChannel() can return :py:attr:`DynamicProvider.NotYet` instead of False. + + .. method:: makeChannel(pvname, src): + + Called when a client attempts to create a Channel for some PV. + The object which is returned will not be collected until + the client closes the Channel or becomes disconnected. + + :return: A :py:class:`SharedPV` instance. + + +ServerOperation +^^^^^^^^^^^^^^^ + +This class is passed to SharedPV handler `Handler.put()` and `Handler.rpc()` methods. + +.. autoclass:: ServerOperation + + .. automethod:: done + + .. automethod:: pvRequest + + .. automethod:: value + + .. automethod:: name + + .. automethod:: peer + + .. automethod:: account + + .. automethod:: roles + + .. automethod:: onCancel + + +SharedPV concurrency options +---------------------------- + +There is a SharedPV class for each of other three concurrency models +supported: OS threading, asyncio coroutines, and cothreads. +All have the same methods as :py:class:`thread.SharedPV`. + +The difference between :py:class:`thread.SharedPV`, :py:class:`asyncio.SharedPV`, and :py:class:`cothread.SharedPV` +is the context in which the handler methods are called (an OS thread, an asyncio coroutine, or a cothread). +This distinction determines how blocking operations may be carried out. + +Note that :py:class:`thread.SharedPV` uses a fixed size thread pool. +This limits the number of concurrent callbacks. + + +SharedPV API +------------ + +.. currentmodule:: p4p.server.thread + +.. autoclass:: SharedPV + + .. automethod:: open + + .. automethod:: close + + .. automethod:: post + + .. automethod:: current + + +SharedPV Handler Interface +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autoclass:: Handler + + .. automethod:: put + + .. automethod:: rpc + + .. automethod:: onFirstConnect + + .. automethod:: onLastDisconnect + +asyncio or cothread +^^^^^^^^^^^^^^^^^^^ + +.. currentmodule:: p4p.server.asyncio + +.. class:: SharedPV + + Same arguments as :py:class:`thread.SharedPV` except that queue= is replaced with loop= . + + :param loop: An asyncio event loop, or None to use the default. + +.. currentmodule:: p4p.server.cothread + +.. class:: SharedPV + +.. currentmodule:: p4p.server + +Global Provider registry +^^^^^^^^^^^^^^^^^^^^^^^^ + +If it becomes necessary for a Provider to be included in a server which is started +outside of Python code, then it must be placed in the global provider registry +with installProvider(). + +.. autofunction:: installProvider + +.. autofunction:: removeProvider diff --git a/_sources/starting.rst.txt b/_sources/starting.rst.txt new file mode 100644 index 00000000..66fea57c --- /dev/null +++ b/_sources/starting.rst.txt @@ -0,0 +1,68 @@ +.. _starting: + +Quick Start +=========== + +For testing and evaluation, it is recommended to install from pypi.org into a (disposable) virtualenv. :: + + python -m virtualenv p4ptest + . p4ptest/bin/activate + python -m pip install -U pip + python -m pip install p4p nose2 + python -m nose2 p4p # Optional: runs automatic tests + +With this complete, open three terminal instances. +One to run a PVA client, and two more to run PVA clients. +In the first run a PVA server. Feel free to replace 'my:pv:name' +with an arbitrary name string everywhere it occurs. :: + + $ . p4ptest/bin/activate + $ python -m p4p.server.cli my:pv:name=int + ... + INFO:p4p.server:Running server + +In a second terminal run the following. If successful, the last line will end with a zero value. :: + + $ . p4ptest/bin/activate + $ python -m p4p.client.cli monitor my:pv:name + ... + my:pv:name Mon Jul 9 19:24:01 2018 0L + +And finally, in a third terminal run the following. If successful, the second terminal should show the new value. :: + + $ . p4ptest/bin/activate + $ python -m p4p.client.cli put my:pv:name=5 + my:pv:name=5 + +Alternately, using the `clientapi`. :: + + from p4p.client.thread import Context + ctxt = Context('pva') + print(ctxt.get('my:pv:name')) + ctxt.put('my:pv:name', 6) + print(ctxt.get('my:pv:name')) + +Troubleshooting network issues +------------------------------ + +If the preceeding didn't work as described, there is likely a networking problem. +Restart both server and client with an added argument '-d'. +Look for lines like: :: + + ... + 2018-09-27T17:00:44.164 Broadcast address #0: 10.65.15.255:5076. (not unicast) + 2018-09-27T17:00:44.164 Broadcast address #1: 192.168.210.255:5076. (not unicast) + ... + +This indicates the two network interfaces were discovered on this host. +Localhost is not included by default. +If no interfaces are found, then check the system network configuration. +If interfaces are found, ensure that no firewalls are applied. + +By default, both client and server must share at least one discovered +local broadcast address. + +Non-default configuration involves the use of the $EPICS_PVA_ADDR_LIST +environment variable, or configuration options specifically passed +to conf= `p4p.client.thread.Context()`. This is considered beyond the +scope of a "quick start". diff --git a/_sources/values.rst.txt b/_sources/values.rst.txt new file mode 100644 index 00000000..b2d5a1c0 --- /dev/null +++ b/_sources/values.rst.txt @@ -0,0 +1,283 @@ +.. _valueapi: + +Working with Value and Type +=========================== + +.. currentmodule:: p4p + +Each :py:class:`Value` corresponds conceptually with a C/C++ struct in that it consists +of zero or more data fields. Values are strongly typed, with each Value having a corresponding +:py:class:`Type`. Each field has a concrete type, which may in turn be a sub-structure. + +Further, each Value holds a bit mask which identifies fields which have "changed". +This bit mask is used during PVA protocol operations to select a subset of fields +which will actually be transfered over the network. + +Working with Type and Value +--------------------------- + +:py:class:`Value` is initialized in two steps. +First a :py:class:`Type` describing the data structure is created, +then the Value container is built, and optionally initialized. + + >>> from p4p import Type, Value + >>> T = Type([('value', 'i')]) + >>> V = Value(T, {'value':42}) + +Here a simple structure is defined with a single field 'value' which is a signed 32-bit integer. +The created value initializes 'value' to 42. +This Value can then be accessed with: + + >>> V.value + 42 + >>> V['value'] + 42 + >>> V.get('value', 111) + 42 + >>> V.get('invalid', 111) # uses default + 111 + +Field values can also be changed + + >>> V.value = 43 + >>> V['value'] = 43 + +.. _valchange: + +Change tracking +^^^^^^^^^^^^^^^ + +Each :py:class:`Value` maintains a mask marking which of its field have been initialized/changed. + +A newly created Value has no fields marked (empty mask). :: + + V = Value(T) + assert V.asSet()==set() + +Initial values can be provided at construction. :: + + V = Value(T, {'value': 42}) + assert V.changed('value') + assert V.asSet()==set('value') + +Assignment of a new value automatically marks a field as changed. :: + + V = Value(T) + assert not V.changed('value') + V.value = 42 + assert V.changed('value') + +The change mask can be cleared if necessary. eg. when passing the same Value to SharedPV.post() several times. :: + + V = Value(T, {'value': 42}) + assert V.changed('value') + V.unmark() + assert not V.changed('value') + +.. _valuecodes: + +Type definitions +---------------- + +The :py:mod:`p4p.nt` module contains helpers to build common :py:class:`Type` definitions. + +Structures are strongly typed. +The type is specified with a code. +Supported codes are given in the table below. + +Type specifier codes: + +==== ======= +Code Type +==== ======= +? bool +s unicode +b s8 +B u8 +h s16 +H u16 +i i32 +I u32 +l i64 +L u64 +f f32 +d f64 +v variant +U union +S struct +==== ======= + +.. note:: Prefix with 'a' for "array of". For example, 'ai' is an array of signed 32-bit integers. + +A :py:class:`Type` is build with a list of tuples, +where each tuple defines a field. + +For all type codes except struct 'S' and discriminating union 'U' only the type code is needed. :: + + T = Type([ + ('value', 's'), # string + ('other', 'ad'), # array of double floating + ]) + +sub-structures and discriminating union have a nested tuple to fully define the field type. + + >>> T = Type([ + ('value', 's'), # string + ('alarm', ('S', None, [ + ('severity', 'i'), + ('status', 'i'), + ('message', 's'), + ])), + ]) + >>> V = Value(T, {'alarm':{'severity':0}}) + >>> V.alarm.severity + 0 + >>> V.alarm['severity'] + 0 + >>> V['alarm.severity'] + 0 + +Here a sub-structure 'alarm' is defined with three fields. + +A discriminating union is defined in the same manner. + + >>> V = Type([ + ('value', ('u', None, [ + ('ival', 'i'), + ('sval', 's'), + ])), + ])() + >>> V.value + None + >>> V.value = ('ival', 42) # explicitly select union field name + >>> V.value + 42 + >>> V.value = ('sval', 'hello') + >>> V.value + u'hello' + >>> V.value = 43 # beware still using 'sval' !! + >>> V.value + u'43' + +Assigning variant and union +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As the preceding example suggests, the rules for assigning values +to variant and union fields can be surprising. + +The rules for assigning a variant are as follows: + +============= ================================ +value type Action +============= ================================ +None clears current value +Value Stores a structure +int signed 32-bit (python 2.x only) +long signed 64-bit +float 64-bit floating +bytes|unicode string +ndarray array of integer or floating +============= ================================ + +Further, a variant union may be explicitly assigned with a specific scalar/array type +using a tuple of a type specifier code and value. + +Other types throw an Exception. + + >>> V = Type([('x','v')])() + >>> V.x = 4.2 # inferred 64-bit floating + >>> V.x = ('f', 4.2) # explicit 32-bit floating + + +The rules for assigning a discriminating union are as follows: + +============== ======================================================================== +value type Action +============== ======================================================================== +None clears current value +('field', val) explicitly specify the union field name +val If a union field has previously been selected, coerce assigned value +val If no union field previously select, attempt magic selection and coerce. +============== ======================================================================== + +Other types throw an Exception. + +API Reference +------------- + +.. module:: p4p + +.. autoclass:: Value + + .. automethod:: tolist + + .. automethod:: todict + + .. automethod:: tostr + + .. automethod:: items + + .. automethod:: getID + + .. automethod:: type + + .. automethod:: has + + .. automethod:: get + + .. automethod:: select + + .. method:: __getattr__(field) + + Access a sub-field. If the sub-field value. + + .. method:: __setattr__(field, value) + + Assign sub-field. + + .. method:: __getitem__(field) + + Same as __getattr__ + + .. method:: __setitem__(field, value) + + Same as __setattr__ + + .. automethod:: changed + + .. automethod:: changedSet + + .. automethod:: mark + + .. automethod:: unmark + + .. method:: asSet + + Deprecated alias for asSet() + +.. autoclass:: Type + + .. automethod:: getID + + .. automethod:: aspy + + .. automethod:: has + + .. method:: __getattr__(field) + + Return Type of field. Same as self.aspy(field) for non-structure fields. + + .. automethod:: keys + + .. automethod:: values + + .. automethod:: items + + .. automethod:: __iter__ + +Relation to C++ API +------------------- + +For those familiar with the `PVXS ` API. +A :py:class:`Type` wraps a TypeDef. +:py:class:`Value` wraps a Value. diff --git a/_static/_sphinx_javascript_frameworks_compat.js b/_static/_sphinx_javascript_frameworks_compat.js new file mode 100644 index 00000000..8549469d --- /dev/null +++ b/_static/_sphinx_javascript_frameworks_compat.js @@ -0,0 +1,134 @@ +/* + * _sphinx_javascript_frameworks_compat.js + * ~~~~~~~~~~ + * + * Compatability shim for jQuery and underscores.js. + * + * WILL BE REMOVED IN Sphinx 6.0 + * xref RemovedInSphinx60Warning + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + + +/** + * small helper function to urldecode strings + * + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL + */ +jQuery.urldecode = function(x) { + if (!x) { + return x + } + return decodeURIComponent(x.replace(/\+/g, ' ')); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} diff --git a/_static/alabaster.css b/_static/alabaster.css new file mode 100644 index 00000000..0eddaeb0 --- /dev/null +++ b/_static/alabaster.css @@ -0,0 +1,701 @@ +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: Georgia, serif; + font-size: 17px; + background-color: #fff; + color: #000; + margin: 0; + padding: 0; +} + + +div.document { + width: 940px; + margin: 30px auto 0 auto; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 220px; +} + +div.sphinxsidebar { + width: 220px; + font-size: 14px; + line-height: 1.5; +} + +hr { + border: 1px solid #B1B4B6; +} + +div.body { + background-color: #fff; + color: #3E4349; + padding: 0 30px 0 30px; +} + +div.body > .section { + text-align: left; +} + +div.footer { + width: 940px; + margin: 20px auto 30px auto; + font-size: 14px; + color: #888; + text-align: right; +} + +div.footer a { + color: #888; +} + +p.caption { + font-family: inherit; + font-size: inherit; +} + + +div.relations { + display: none; +} + + +div.sphinxsidebar a { + color: #444; + text-decoration: none; + border-bottom: 1px dotted #999; +} + +div.sphinxsidebar a:hover { + border-bottom: 1px solid #999; +} + +div.sphinxsidebarwrapper { + padding: 18px 10px; +} + +div.sphinxsidebarwrapper p.logo { + padding: 0; + margin: -10px 0 0 0px; + text-align: center; +} + +div.sphinxsidebarwrapper h1.logo { + margin-top: -10px; + text-align: center; + margin-bottom: 5px; + text-align: left; +} + +div.sphinxsidebarwrapper h1.logo-name { + margin-top: 0px; +} + +div.sphinxsidebarwrapper p.blurb { + margin-top: 0; + font-style: normal; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-family: Georgia, serif; + color: #444; + font-size: 24px; + font-weight: normal; + margin: 0 0 5px 0; + padding: 0; +} + +div.sphinxsidebar h4 { + font-size: 20px; +} + +div.sphinxsidebar h3 a { + color: #444; +} + +div.sphinxsidebar p.logo a, +div.sphinxsidebar h3 a, +div.sphinxsidebar p.logo a:hover, +div.sphinxsidebar h3 a:hover { + border: none; +} + +div.sphinxsidebar p { + color: #555; + margin: 10px 0; +} + +div.sphinxsidebar ul { + margin: 10px 0; + padding: 0; + color: #000; +} + +div.sphinxsidebar ul li.toctree-l1 > a { + font-size: 120%; +} + +div.sphinxsidebar ul li.toctree-l2 > a { + font-size: 110%; +} + +div.sphinxsidebar input { + border: 1px solid #CCC; + font-family: Georgia, serif; + font-size: 1em; +} + +div.sphinxsidebar hr { + border: none; + height: 1px; + color: #AAA; + background: #AAA; + + text-align: left; + margin-left: 0; + width: 50%; +} + +div.sphinxsidebar .badge { + border-bottom: none; +} + +div.sphinxsidebar .badge:hover { + border-bottom: none; +} + +/* To address an issue with donation coming after search */ +div.sphinxsidebar h3.donation { + margin-top: 10px; +} + +/* -- body styles ----------------------------------------------------------- */ + +a { + color: #004B6B; + text-decoration: underline; +} + +a:hover { + color: #6D4100; + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: Georgia, serif; + font-weight: normal; + margin: 30px 0px 10px 0px; + padding: 0; +} + +div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } +div.body h2 { font-size: 180%; } +div.body h3 { font-size: 150%; } +div.body h4 { font-size: 130%; } +div.body h5 { font-size: 100%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #DDD; + padding: 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + color: #444; + background: #EAEAEA; +} + +div.body p, div.body dd, div.body li { + line-height: 1.4em; +} + +div.admonition { + margin: 20px 0px; + padding: 10px 30px; + background-color: #EEE; + border: 1px solid #CCC; +} + +div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fafafa; +} + +div.admonition p.admonition-title { + font-family: Georgia, serif; + font-weight: normal; + font-size: 24px; + margin: 0 0 10px 0; + padding: 0; + line-height: 1; +} + +div.admonition p.last { + margin-bottom: 0; +} + +div.highlight { + background-color: #fff; +} + +dt:target, .highlight { + background: #FAF3E8; +} + +div.warning { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.danger { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.error { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.caution { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.attention { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.important { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.note { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.tip { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.hint { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.seealso { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.topic { + background-color: #EEE; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre, tt, code { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; + font-size: 0.9em; +} + +.hll { + background-color: #FFC; + margin: 0 -12px; + padding: 0 12px; + display: block; +} + +img.screenshot { +} + +tt.descname, tt.descclassname, code.descname, code.descclassname { + font-size: 0.95em; +} + +tt.descname, code.descname { + padding-right: 0.08em; +} + +img.screenshot { + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils { + border: 1px solid #888; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils td, table.docutils th { + border: 1px solid #888; + padding: 0.25em 0.7em; +} + +table.field-list, table.footnote { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +table.footnote { + margin: 15px 0; + width: 100%; + border: 1px solid #EEE; + background: #FDFDFD; + font-size: 0.9em; +} + +table.footnote + table.footnote { + margin-top: -15px; + border-top: none; +} + +table.field-list th { + padding: 0 0.8em 0 0; +} + +table.field-list td { + padding: 0; +} + +table.field-list p { + margin-bottom: 0.8em; +} + +/* Cloned from + * https://github.com/sphinx-doc/sphinx/commit/ef60dbfce09286b20b7385333d63a60321784e68 + */ +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +table.footnote td.label { + width: .1px; + padding: 0.3em 0 0.3em 0.5em; +} + +table.footnote td { + padding: 0.3em 0.5em; +} + +dl { + margin: 0; + padding: 0; +} + +dl dd { + margin-left: 30px; +} + +blockquote { + margin: 0 0 0 30px; + padding: 0; +} + +ul, ol { + /* Matches the 30px from the narrow-screen "li > ul" selector below */ + margin: 10px 0 10px 30px; + padding: 0; +} + +pre { + background: #EEE; + padding: 7px 30px; + margin: 15px 0px; + line-height: 1.3em; +} + +div.viewcode-block:target { + background: #ffd; +} + +dl pre, blockquote pre, li pre { + margin-left: 0; + padding-left: 30px; +} + +tt, code { + background-color: #ecf0f3; + color: #222; + /* padding: 1px 2px; */ +} + +tt.xref, code.xref, a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fff; +} + +a.reference { + text-decoration: none; + border-bottom: 1px dotted #004B6B; +} + +/* Don't put an underline on images */ +a.image-reference, a.image-reference:hover { + border-bottom: none; +} + +a.reference:hover { + border-bottom: 1px solid #6D4100; +} + +a.footnote-reference { + text-decoration: none; + font-size: 0.7em; + vertical-align: top; + border-bottom: 1px dotted #004B6B; +} + +a.footnote-reference:hover { + border-bottom: 1px solid #6D4100; +} + +a:hover tt, a:hover code { + background: #EEE; +} + + +@media screen and (max-width: 870px) { + + div.sphinxsidebar { + display: none; + } + + div.document { + width: 100%; + + } + + div.documentwrapper { + margin-left: 0; + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + } + + div.bodywrapper { + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + margin-left: 0; + } + + ul { + margin-left: 0; + } + + li > ul { + /* Matches the 30px from the "ul, ol" selector above */ + margin-left: 30px; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .bodywrapper { + margin: 0; + } + + .footer { + width: auto; + } + + .github { + display: none; + } + + + +} + + + +@media screen and (max-width: 875px) { + + body { + margin: 0; + padding: 20px 30px; + } + + div.documentwrapper { + float: none; + background: #fff; + } + + div.sphinxsidebar { + display: block; + float: none; + width: 102.5%; + margin: 50px -30px -20px -30px; + padding: 10px 20px; + background: #333; + color: #FFF; + } + + div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, + div.sphinxsidebar h3 a { + color: #fff; + } + + div.sphinxsidebar a { + color: #AAA; + } + + div.sphinxsidebar p.logo { + display: none; + } + + div.document { + width: 100%; + margin: 0; + } + + div.footer { + display: none; + } + + div.bodywrapper { + margin: 0; + } + + div.body { + min-height: 0; + padding: 0; + } + + .rtd_doc_footer { + display: none; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .footer { + width: auto; + } + + .github { + display: none; + } +} + + +/* misc. */ + +.revsys-inline { + display: none!important; +} + +/* Make nested-list/multi-paragraph items look better in Releases changelog + * pages. Without this, docutils' magical list fuckery causes inconsistent + * formatting between different release sub-lists. + */ +div#changelog > div.section > ul > li > p:only-child { + margin-bottom: 0; +} + +/* Hide fugly table cell borders in ..bibliography:: directive output */ +table.docutils.citation, table.docutils.citation td, table.docutils.citation th { + border: none; + /* Below needed in some edge cases; if not applied, bottom shadows appear */ + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + + +/* relbar */ + +.related { + line-height: 30px; + width: 100%; + font-size: 0.9rem; +} + +.related.top { + border-bottom: 1px solid #EEE; + margin-bottom: 20px; +} + +.related.bottom { + border-top: 1px solid #EEE; +} + +.related ul { + padding: 0; + margin: 0; + list-style: none; +} + +.related li { + display: inline; +} + +nav#rellinks { + float: right; +} + +nav#rellinks li+li:before { + content: "|"; +} + +nav#breadcrumbs li+li:before { + content: "\00BB"; +} + +/* Hide certain items when printing */ +@media print { + div.related { + display: none; + } +} \ No newline at end of file diff --git a/_static/basic.css b/_static/basic.css new file mode 100644 index 00000000..4e9a9f1f --- /dev/null +++ b/_static/basic.css @@ -0,0 +1,900 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 360px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} +nav.contents, +aside.topic, +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ +nav.contents, +aside.topic, +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +nav.contents > :last-child, +aside.topic > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +nav.contents::after, +aside.topic::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} +aside.footnote > span, +div.citation > span { + float: left; +} +aside.footnote > span:last-of-type, +div.citation > span:last-of-type { + padding-right: 0.5em; +} +aside.footnote > p { + margin-left: 2em; +} +div.citation > p { + margin-left: 4em; +} +aside.footnote > p:last-of-type, +div.citation > p:last-of-type { + margin-bottom: 0em; +} +aside.footnote > p:last-of-type:after, +div.citation > p:last-of-type:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0 0.5em; + content: ":"; + display: inline-block; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; + white-space: nowrap; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/_static/custom.css b/_static/custom.css new file mode 100644 index 00000000..2a924f1d --- /dev/null +++ b/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/_static/doctools.js b/_static/doctools.js new file mode 100644 index 00000000..527b876c --- /dev/null +++ b/_static/doctools.js @@ -0,0 +1,156 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Base JavaScript utilities for all Sphinx HTML documentation. + * + * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +"use strict"; + +const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ + "TEXTAREA", + "INPUT", + "SELECT", + "BUTTON", +]); + +const _ready = (callback) => { + if (document.readyState !== "loading") { + callback(); + } else { + document.addEventListener("DOMContentLoaded", callback); + } +}; + +/** + * Small JavaScript module for the documentation. + */ +const Documentation = { + init: () => { + Documentation.initDomainIndexTable(); + Documentation.initOnKeyListeners(); + }, + + /** + * i18n support + */ + TRANSLATIONS: {}, + PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), + LOCALE: "unknown", + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext: (string) => { + const translated = Documentation.TRANSLATIONS[string]; + switch (typeof translated) { + case "undefined": + return string; // no translation + case "string": + return translated; // translation exists + default: + return translated[0]; // (singular, plural) translation tuple exists + } + }, + + ngettext: (singular, plural, n) => { + const translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated !== "undefined") + return translated[Documentation.PLURAL_EXPR(n)]; + return n === 1 ? singular : plural; + }, + + addTranslations: (catalog) => { + Object.assign(Documentation.TRANSLATIONS, catalog.messages); + Documentation.PLURAL_EXPR = new Function( + "n", + `return (${catalog.plural_expr})` + ); + Documentation.LOCALE = catalog.locale; + }, + + /** + * helper function to focus on search bar + */ + focusSearchBar: () => { + document.querySelectorAll("input[name=q]")[0]?.focus(); + }, + + /** + * Initialise the domain index toggle buttons + */ + initDomainIndexTable: () => { + const toggler = (el) => { + const idNumber = el.id.substr(7); + const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); + if (el.src.substr(-9) === "minus.png") { + el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; + toggledRows.forEach((el) => (el.style.display = "none")); + } else { + el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; + toggledRows.forEach((el) => (el.style.display = "")); + } + }; + + const togglerElements = document.querySelectorAll("img.toggler"); + togglerElements.forEach((el) => + el.addEventListener("click", (event) => toggler(event.currentTarget)) + ); + togglerElements.forEach((el) => (el.style.display = "")); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); + }, + + initOnKeyListeners: () => { + // only install a listener if it is really needed + if ( + !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && + !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS + ) + return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.altKey || event.ctrlKey || event.metaKey) return; + + if (!event.shiftKey) { + switch (event.key) { + case "ArrowLeft": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const prevLink = document.querySelector('link[rel="prev"]'); + if (prevLink && prevLink.href) { + window.location.href = prevLink.href; + event.preventDefault(); + } + break; + case "ArrowRight": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const nextLink = document.querySelector('link[rel="next"]'); + if (nextLink && nextLink.href) { + window.location.href = nextLink.href; + event.preventDefault(); + } + break; + } + } + + // some keyboard layouts may need Shift to get / + switch (event.key) { + case "/": + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; + Documentation.focusSearchBar(); + event.preventDefault(); + } + }); + }, +}; + +// quick alias for translations +const _ = Documentation.gettext; + +_ready(Documentation.init); diff --git a/_static/documentation_options.js b/_static/documentation_options.js new file mode 100644 index 00000000..26cf270b --- /dev/null +++ b/_static/documentation_options.js @@ -0,0 +1,14 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '4.1.12', + LANGUAGE: 'en', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, + SHOW_SEARCH_SUMMARY: true, + ENABLE_SEARCH_SHORTCUTS: true, +}; \ No newline at end of file diff --git a/_static/file.png b/_static/file.png new file mode 100644 index 00000000..a858a410 Binary files /dev/null and b/_static/file.png differ diff --git a/_static/forkme_right_darkblue_121621.png b/_static/forkme_right_darkblue_121621.png new file mode 100644 index 00000000..146ef8a8 Binary files /dev/null and b/_static/forkme_right_darkblue_121621.png differ diff --git a/_static/graphviz.css b/_static/graphviz.css new file mode 100644 index 00000000..19e7afd3 --- /dev/null +++ b/_static/graphviz.css @@ -0,0 +1,19 @@ +/* + * graphviz.css + * ~~~~~~~~~~~~ + * + * Sphinx stylesheet -- graphviz extension. + * + * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +img.graphviz { + border: 0; + max-width: 100%; +} + +object.graphviz { + max-width: 100%; +} diff --git a/_static/jquery.js b/_static/jquery.js new file mode 100644 index 00000000..034a5452 --- /dev/null +++ b/_static/jquery.js @@ -0,0 +1,10907 @@ +/*! + * jQuery JavaScript Library v3.6.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright OpenJS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket trac-14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 + // Plus for old WebKit, typeof returns "function" for HTML collections + // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) + return typeof obj === "function" && typeof obj.nodeType !== "number" && + typeof obj.item !== "function"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.6.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), + function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.6 + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://js.foundation/ + * + * Date: 2021-02-16 + */ +( function( window ) { +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ( {} ).hasOwnProperty, + arr = [], + pop = arr.pop, + pushNative = arr.push, + push = arr.push, + slice = arr.slice, + + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[ i ] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + + "ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] + // or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rhtml = /HTML$/i, + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android<4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + pushNative.apply( target, slice.call( els ) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + + // Can't trust NodeList.length + while ( ( target[ j++ ] = els[ i++ ] ) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && + + // Support: IE 8 only + // Exclude object elements + ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + if ( newContext !== context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split( "|" ), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[ i ] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( ( cur = cur.nextSibling ) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return ( name === "input" || name === "button" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + var namespace = elem && elem.namespaceURI, + docElem = elem && ( elem.ownerDocument || elem ).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, + // Safari 4 - 5 only, Opera <=11.6 - 12.x only + // IE/Edge & older browsers don't support the :scope pseudo-class. + // Support: Safari 6.0 only + // Safari 6.0 supports :scope but it's an alias of :root there. + support.scope = assert( function( el ) { + docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); + return typeof el.querySelectorAll !== "undefined" && + !el.querySelectorAll( ":scope fieldset div" ).length; + } ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert( function( el ) { + el.className = "i"; + return !el.getAttribute( "className" ); + } ); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert( function( el ) { + el.appendChild( document.createComment( "" ) ); + return !el.getElementsByTagName( "*" ).length; + } ); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find[ "TAG" ] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + } ); + + assert( function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll( "[name=d]" ).length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: Opera 10 - 11 only + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll( "*,:x" ); + rbuggyQSA.push( ",.*:" ); + } ); + } + + if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector ) ) ) ) { + + assert( function( el ) { + + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + } ); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); + } : + function( a, b ) { + if ( b ) { + while ( ( b = b.parentNode ) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { + + // Choose the first element that is related to our preferred document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document || a.ownerDocument == preferredDoc && + contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document || b.ownerDocument == preferredDoc && + contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + return a == document ? -1 : + b == document ? 1 : + /* eslint-enable eqeqeq */ + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( ( cur = cur.parentNode ) ) { + ap.unshift( cur ); + } + cur = b; + while ( ( cur = cur.parentNode ) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[ i ] === bp[ i ] ) { + i++; + } + + return i ? + + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[ i ], bp[ i ] ) : + + // Otherwise nodes in our document sort first + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + ap[ i ] == preferredDoc ? -1 : + bp[ i ] == preferredDoc ? 1 : + /* eslint-enable eqeqeq */ + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( support.matchesSelector && documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( elem.ownerDocument || elem ) != document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[ 1 ] = match[ 1 ].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || + match[ 5 ] || "" ).replace( runescape, funescape ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { + return true; + } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( + className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + /* eslint-disable max-len */ + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + /* eslint-enable max-len */ + + }; + }, + + "CHILD": function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction( function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[ i ] ); + seed[ idx ] = !( matches[ idx ] = matched[ i ] ); + } + } ) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + "not": markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element (issue #299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + "has": markFunction( function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + } ), + + "contains": markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && + ( !document.hasFocus || document.hasFocus() ) && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return ( nodeName === "input" && !!elem.checked ) || + ( nodeName === "option" && !!elem.selected ); + }, + + "selected": function( elem ) { + + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos[ "empty" ]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( ( attr = elem.getAttribute( "type" ) ) == null || + attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo( function() { + return [ 0 ]; + } ), + + "last": createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + "even": createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "odd": createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? + argument + length : + argument > length ? + length : + argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rcombinators.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || + ( outerCache[ elem.uniqueID ] = {} ); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = uniqueCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( + selector || "*", + context.nodeType ? [ context ] : context, + [] + ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || Expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens + .slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), + len = elems.length; + + if ( outermost ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( + selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) + ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + + context = ( Expr.find[ "ID" ]( token.matches[ 0 ] + .replace( runescape, funescape ), context ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( Expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = Expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + token.matches[ 0 ].replace( runescape, funescape ), + rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || + context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert( function( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert( function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute( "href" ) === "#"; +} ) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + } ); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert( function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +} ) ) { + addHandle( "value", function( elem, _name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + } ); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert( function( el ) { + return el.getAttribute( "disabled" ) == null; +} ) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; + } + } ); +} + +return Sizzle; + +} )( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +} +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (trac-9521) + // Strict HTML recognition (trac-11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the primary Deferred + primary = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + primary.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( primary.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return primary.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); + } + + return primary.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See trac-6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (trac-9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see trac-8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (trac-14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (trac-11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (trac-14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (trac-13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (trac-15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (trac-12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 - 11+ +// focus() and blur() are asynchronous, except when they are no-op. +// So expect focus to be synchronous when the element is already active, +// and blur to be synchronous when the element is not already active. +// (focus and blur are always synchronous in other supported browsers, +// this just defines when we can count on it). +function expectSync( elem, type ) { + return ( elem === safeActiveElement() ) === ( type === "focus" ); +} + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (trac-13208) + // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (trac-13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", returnTrue ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, expectSync ) { + + // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add + if ( !expectSync ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var notAsync, result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + // Saved data should be false in such cases, but might be a leftover capture object + // from an async native handler (gh-4350) + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + // Support: IE <=9 - 11+ + // focus() and blur() are asynchronous + notAsync = expectSync( this, type ); + this[ type ](); + result = dataPriv.get( this, type ); + if ( saved !== result || notAsync ) { + dataPriv.set( this, type, false ); + } else { + result = {}; + } + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + + // Support: Chrome 86+ + // In Chrome, if an element having a focusout handler is blurred by + // clicking outside of it, it invokes the handler synchronously. If + // that handler calls `.remove()` on the element, the data is cleared, + // leaving `result` undefined. We need to guard against this. + return result && result.value; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering the + // native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + + // Support: IE <=9 - 11+ + // Extend with the prototype to reset the above stopImmediatePropagation() + jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event + event.stopImmediatePropagation(); + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (trac-504, trac-13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + which: true +}, 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; + }, + + // Suppress native focus or blur if we're currently inside + // a leveraged native-event stack + _default: function( event ) { + return dataPriv.get( event.target, type ); + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (trac-8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + + // Unwrap a CDATA section containing script contents. This shouldn't be + // needed as in XML documents they're already not visible when + // inspecting element contents and in HTML documents they have no + // meaning but we're preserving that logic for backwards compatibility. + // This will be removed completely in 4.0. See gh-4904. + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var rcustomProp = /^--/; + + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + +var whitespace = "[\\x20\\t\\r\\n\\f]"; + + +var rtrimCSS = new RegExp( + "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", + "g" +); + + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (trac-8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + // + // Support: Firefox 70+ + // Only Firefox includes border widths + // in computed dimensions. (gh-4529) + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; + tr.style.cssText = "border:1px solid"; + + // Support: Chrome 86+ + // Height set through cssText does not get applied. + // Computed height then comes back as 0. + tr.style.height = "1px"; + trChild.style.height = "9px"; + + // Support: Android 8 Chrome 86+ + // In our bodyBackground.html iframe, + // display for all div elements is set to "inline", + // which causes a problem only in Android 8 Chrome 86. + // Ensuring the div is display: block + // gets around this issue. + trChild.style.display = "block"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + + parseInt( trStyle.borderTopWidth, 10 ) + + parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + isCustomProp = rcustomProp.test( name ), + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, trac-12537) + // .css('--customProperty) (gh-3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + // trim whitespace for custom property (issue gh-4926) + if ( isCustomProp ) { + + // rtrim treats U+000D CARRIAGE RETURN and U+000C FORM FEED + // as whitespace while CSS does not, but this is not a problem + // because CSS preprocessing replaces them with U+000A LINE FEED + // (which *is* CSS whitespace) + // https://www.w3.org/TR/css-syntax-3/#input-preprocessing + ret = ret.replace( rtrimCSS, "$1" ); + } + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "gridArea": true, + "gridColumn": true, + "gridColumnEnd": true, + "gridColumnStart": true, + "gridRow": true, + "gridRowEnd": true, + "gridRowStart": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (trac-7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug trac-9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (trac-7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // Use proper attribute retrieval (trac-12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + if ( cur.indexOf( " " + className + " " ) < 0 ) { + cur += className + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + removeClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + + // This expression is here for better compressibility (see addClass) + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Remove *all* instances + while ( cur.indexOf( " " + className + " " ) > -1 ) { + cur = cur.replace( " " + className + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var classNames, className, i, self, + type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + classNames = classesToArray( value ); + + return this.each( function() { + if ( isValidValue ) { + + // Toggle individual class names + self = jQuery( this ); + + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (trac-14686, trac-14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (trac-2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (trac-9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (trac-6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml, parserErrorElem; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) {} + + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ).filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ).map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // trac-7653, trac-8125, trac-8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + +originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes trac-9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (trac-10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket trac-12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // trac-9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script but not if jsonp + if ( !isSuccess && + jQuery.inArray( "script", s.dataTypes ) > -1 && + jQuery.inArray( "json", s.dataTypes ) < 0 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (trac-11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // trac-1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see trac-8605, trac-14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // trac-14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Building

+

Release tars available from https://github.com/epics-base/p4p/releases

+

The P4P modules requires:

+
    +
  • Python 2.7 or >=3.5 (>=3.6 for asyncio support)

  • +
  • numpy >=1.6

  • +
  • Cython >=0.25.2

  • +
  • nose2 (Optional, recommended to run unittests)

  • +
+

and…

+

Current (>= 4.0)

+
    +
  • EPICS Base >= 3.14.12

  • +
  • PVXS >= 0.2.0

  • +
+

Prior to 4.0

+
    +
  • EPICS >= 7.0.2

  • +
+

or

+
    +
  • EPICS Base >= 3.14.12

  • +
  • pvDataCPP >=7.1.0

  • +
  • pvAccessCPP >=6.1.0

  • +
+

P4P can be built and installed in one of two ways. +As a python package, preferably managed by PIP. +As an EPICS module.

+

Optional

+
    +
  • cothread needed by p4p.client.cothread.Context.

  • +
  • qtpy needed for p4p.client.Qt.Context.

  • +
+
+

Local (re)build as Python package

+

The process for building as a python package using sources from pypi.org by adding the argument “–no-binary” +to prevent the use of pre-built binarys (except for numpy).

+
python -m virtualenv p4ptest
+. p4ptest/bin/activate
+python -m pip install -U pip
+python -m pip install \
+ --only-binary numpy \
+ --no-binary epicscorelibs,pvxslibs,p4p \
+ nose2 p4p
+python -m nose2 p4p   # Optional: runs automatic tests
+
+
+
+

Bootstrap a virtualenv offline

+

It may be necessary to create a virtualenv including P4P on a machine with no internet access, +or to ensure the use of certain verified binary/source. +The following recipe was tested with virtualenv 16.1 and pip 18.1.

+

First, from a machine with internet access, and having the same archetecture as the target machine, +collect the necessary files.

+
mkdir /tmp/venv
+cd /tmp/venv
+python -m pip download virtualenv
+unzip virtualenv-*.whl
+python virtualenv.py --never-download prepenv
+. prepenv/bin/activate
+pip download -d virtualenv_support nose2 p4p
+tar -caf p4p-env-`date -u +%Y%m%d`.tar.gz virtualenv.py virtualenv_support
+deactivate
+
+
+

Now move the created file p4p-env-*.tar.gz to the target machine. +Then prepare the virtualenv env with.

+
tar -xaf p4p-env-*.tar.gz
+python virtualenv.py --never-download env
+. env/bin/activate
+pip install --no-index -f virtualenv_support p4p
+python -m nose2 p4p   # Optional: runs automatic tests
+
+
+

Utilities to automate this process include https://pypi.org/project/pyutilib.virtualenv/

+
+
+
+

Build as EPICS Module

+

P4P can also be built as an EPICS Module with additional python dependencies.

+

Prepare the host to build python extensions. eg. a Debian Linux host:

+
sudo apt-get install build-essential python3-dev
+
+
+

Install python dependencies on eg. a Debian Linux host:

+
sudo apt-get install python3-numpy python3-nose2 cython3
+
+
+

or with PIP:

+
python3 -m pip install -r requirements-latest.txt
+
+
+

From from versioned source. (may replace “master” with release version number):

+
git clone --branch master https://github.com/epics-base/p4p.git
+cd p4p
+
+
+

Set location of EPICS modules. With EPICS >= 7.0.2:

+
cat <<EOF > configure/RELEASE.local
+PVXS=/path/to/pvxs
+EPICS_BASE=/path/to/epics-base
+EOF
+make
+
+
+

See below for details on building EPICS from source.

+

By default P4P will build using ‘python’ found in the system search path. +To explicitly specify a particular version.

+
make distclean
+make PYTHON=python3
+
+
+

Alternately, the full path of the interpreter can be used.

+
make distclean
+make PYTHON=/usr/bin/python3
+
+
+

For convenience PYTHON can also be set in configure/CONFIG_SITE

+
+

Multiple Python Versions

+

To build for multiple python versions it is necessary to do a partial clean before building +another version. This will not remove the final tree.

+
make PYTHON=python2
+make PYTHON=python2 clean
+make PYTHON=python3
+make PYTHON=python3 clean
+
+
+
+

Note

+

If PYTHON= is ever specified, then it must be specified for all targets except ‘distclean’.

+
+
+
+

Building EPICS dependencies

+

If the necessary EPICS modules are not present, then they may be built from source.

+
sudo apt-get install libreadline6-dev libncurses5-dev perl
+git clone https://github.com/epics-base/epics-base.git
+git clone https://github.com/epics-base/pvxs.git
+cat <<EOF > pvxs/configure/RELEASE.local
+EPICS_BASE=$PWD/epics-base
+EOF
+cat <<EOF > p4p/configure/RELEASE.local
+PVXS=$PWD/pvxs
+EPICS_BASE=$PWD/epics-base
+EOF
+make -C epics-base
+make -C pvxs
+
+
+
+
+

CLI and unittests

+

To run the unittests:

+
make nose
+
+
+

For testing purposes several simple command line client tools are provided. +For further information run:

+
PYTHONPATH=$PWD/python2.7/linux-x86_64 python -m p4p.client.cli -h
+
+
+
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/client.html b/client.html new file mode 100644 index 00000000..818e5efe --- /dev/null +++ b/client.html @@ -0,0 +1,438 @@ + + + + + + + + + Client API — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Client API

+

This module provides Context for use in interactive and/or multi-threaded environment. +Most methods will block the calling thread until a return is available, or an error occurs.

+

Alternatives to p4p.client.thread.Context are provided +p4p.client.cothread.Context, +p4p.client.asyncio.Context, +and p4p.client.Qt.Context. +These differ in how blocking for I/O operation is performed, +and the environment in which Monitor callbacks are run.

+

Note that p4p.client.Qt.Context behaves differently from the others in some respects. +This is described in qtclient.

+
+

Usage

+

Start by creating a client Context.

+
>>> from p4p.client.thread import Context
+>>> Context.providers()
+['pva', ....]
+>>> ctxt = Context('pva')
+
+
+
+

Note

+

The default network configuration taken from the process environment +may be overridden by passing ‘conf=’ to the Context class constructor.

+
+

See What is PVAccess? for background on PVAccess protocol.

+
+

Get/Put

+

Get and Put operations can be performed on single PVs or a list of PVs.

+
>>> V = ctxt.get('pv:name')
+>>> A, B = ctxt.get(['pv:1', 'pv:2'])
+>>> ctxt.put('pv:name', 5)
+>>> ctxt.put('pv:name', {'value': 5}) # equivalent to previous
+>>> ctxt.put('pv:name', {'field_1.value': 5, 'field_2.value': 5}) # put to multiple fields
+
+
+

By default the values returned by Context.get() are subject to Automatic Value unwrapping.

+
+
+

Monitor

+

Unlike get/put/rpc, the Context.monitor() method does not block. +Instead it accepts a callback function which is called with each +new Value, or Exception.

+
def cb(V):
+       print 'New value', V
+sub = ctxt.monitor('pv:name', cb)
+time.sleep(10) # arbitrary wait
+sub.close()
+
+
+

The monitor method returns a Subscription which has a close method +to end the subscription.

+

By default the values passed to monitor callbacks are subject to Automatic Value unwrapping.

+

p4p.client.thread.Context Runs callbacks in a worker thread pool.

+

p4p.client.cothread.Context Runs callbacks in a per-subscription cothread.

+

p4p.client.asyncio.Context Runs callbacks in a per-subscription coroutine.

+

In all cases it is safe for a callback to block/yield. +Subsequent updates for a Subscription will not be delivered until the current callback has completed. +However, updates for other Subscriptions may be delivered.

+
+
+

RPC

+

See RPC Server Helpers.

+
+
+
+

API Reference

+
+
+class p4p.client.thread.Context(provider, conf=None, useenv=True)[source]
+
+
Parameters:
+
    +
  • provider (str) – A Provider name. Try “pva” or run Context.providers() for a complete list.

  • +
  • conf (dict) – Configuration to pass to provider. Depends on provider selected.

  • +
  • useenv (bool) – Allow the provider to use configuration from the process environment.

  • +
  • workers (int) – Size of thread pool in which monitor callbacks are run. Default is 4

  • +
  • maxsize (int) – Size of internal work queue used for monitor callbacks. Default is unlimited

  • +
  • nt (dict) – Controls Automatic Value unwrapping. None uses defaults. Set False to disable

  • +
  • unwrap (dict) – Legacy Automatic Value unwrapping.

  • +
  • queue (WorkQueue) – A work queue through which monitor callbacks are dispatched.

  • +
+
+
+

The methods of this Context will block the calling thread until completion or timeout

+

The meaning, and allowed keys, of the configuration dictionary depend on the provider. +conf= will override values taken from the process environment. Pass useenv=False to +ensure that environment variables are completely ignored.

+

The “pva” provider understands the following keys:

+
    +
  • EPICS_PVA_ADDR_LIST

  • +
  • EPICS_PVA_AUTO_ADDR_LIST

  • +
  • EPICS_PVA_SERVER_PORT

  • +
  • EPICS_PVA_BROADCAST_PORT

  • +
+
+
+name = ''
+

Provider name string

+
+ +
+
+close()[source]
+

Force close all Channels and cancel all Operations

+
+ +
+
+get(name, request=None, timeout=5.0, throw=True)[source]
+

Fetch current value of some number of PVs.

+
+
Parameters:
+
    +
  • name – A single name string or list of name strings

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • timeout (float) – Operation timeout in seconds

  • +
  • throw (bool) – When true, operation error throws an exception. If False then the Exception is returned instead of the Value

  • +
+
+
Returns:
+

A p4p.Value or Exception, or list of same. Subject to Automatic Value unwrapping.

+
+
+

When invoked with a single name then returns is a single value. +When invoked with a list of name, then returns a list of values

+
>>> ctxt = Context('pva')
+>>> V = ctxt.get('pv:name')
+>>> A, B = ctxt.get(['pv:1', 'pv:2'])
+>>>
+
+
+
+ +
+
+put(name, values, request=None, timeout=5.0, throw=True, process=None, wait=None, get=True)[source]
+

Write a new value of some number of PVs.

+
+
Parameters:
+
    +
  • name – A single name string or list of name strings

  • +
  • values – A single value, a list of values, a dict, a Value. May be modified by the constructor nt= argument.

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • timeout (float) – Operation timeout in seconds

  • +
  • throw (bool) – When true, operation error throws an exception. +If False then the Exception is returned instead of the Value

  • +
  • process (str) – Control remote processing. May be ‘true’, ‘false’, ‘passive’, or None.

  • +
  • wait (bool) – Wait for all server processing to complete.

  • +
  • get (bool) – Whether to do a Get before the Put. If True then the value passed to the builder callable +will be initialized with recent PV values. eg. use this with NTEnum to find the enumeration list.

  • +
+
+
Returns:
+

A None or Exception, or list of same

+
+
+

When invoked with a single name then returns is a single value. +When invoked with a list of name, then returns a list of values

+

If ‘wait’ or ‘process’ is specified, then ‘request’ must be omitted or None.

+
>>> ctxt = Context('pva')
+>>> ctxt.put('pv:name', 5.0)
+>>> ctxt.put(['pv:1', 'pv:2'], [1.0, 2.0])
+>>> ctxt.put('pv:name', {'value':5})
+>>>
+
+
+

The provided value(s) will be automatically coerced to the target type. +If this is not possible then an Exception is raised/returned.

+

Unless the provided value is a dict, it is assumed to be a plain value +and an attempt is made to store it in ‘.value’ field.

+
+ +
+
+monitor(name, cb, request=None, notify_disconnect=False, queue=None)[source]
+

Create a subscription.

+
+
Parameters:
+
    +
  • name (str) – PV name string

  • +
  • cb (callable) – Processing callback

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • notify_disconnect (bool) – In additional to Values, the callback may also be call with instances of Exception. +Specifically: Disconnected , RemoteError, or Cancelled

  • +
  • queue (WorkQueue) – A work queue through which monitor callbacks are dispatched.

  • +
+
+
Returns:
+

a Subscription instance

+
+
+

The callable will be invoked with one argument which is either.

+ +
+ +
+
+rpc(name, value, request=None, timeout=5.0, throw=True)[source]
+

Perform a Remote Procedure Call (RPC) operation

+
+
Parameters:
+
    +
  • name (str) – PV name string

  • +
  • value (Value) – Arguments. Must be Value instance

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • timeout (float) – Operation timeout in seconds

  • +
  • throw (bool) – When true, operation error throws an exception. +If False then the Exception is returned instead of the Value

  • +
+
+
Returns:
+

A Value or Exception. Subject to Automatic Value unwrapping.

+
+
+
>>> ctxt = Context('pva')
+>>> ctxt.rpc('pv:name:add', {'A':5, 'B'; 6})
+>>>
+
+
+

The provided value(s) will be automatically coerced to the target type. +If this is not possible then an Exception is raised/returned.

+

Unless the provided value is a dict, it is assumed to be a plain value +and an attempt is made to store it in ‘.value’ field.

+
+ +
+
+static providers()[source]
+
+ +
+
+disconnect(*args, **kws)[source]
+

Clear internal Channel cache, allowing currently unused channels to be implictly closed.

+
+
Parameters:
+

name (str) – None, to clear the entire cache, or a name string to clear only a certain entry.

+
+
+
+ +
+
+static set_debug(lvl)[source]
+
+ +
+ +
+
+class p4p.client.thread.Subscription(ctxt, name, cb, notify_disconnect=False, queue=None)[source]
+

An active subscription.

+

Returned by Context.monitor.

+
+
+close()[source]
+

Close subscription.

+
+ +
+ +
+
+class p4p.client.thread.Disconnected(msg=None)
+

Channel becomes disconected.

+
+ +
+
+class p4p.client.thread.RemoteError
+

Thrown with an error message which has been sent by a server to its remote client

+
+ +
+
+class p4p.client.thread.Cancelled(msg=None)
+

Cancelled from client end.

+
+ +
+
+class p4p.client.thread.Finished(msg=None)
+

Special case of Disconnected when a Subscription has received all updates it will ever receive.

+
+ +
+
+class p4p.client.thread.TimeoutError
+

Timeout expired.

+
+ +
+
+

Qt Client

+

p4p.client.Qt.Context exists to bring the results of network operations into a Qt event loop. +This is done through the native signals and slots mechanism.

+

Use requires the optional dependency qtpy package.

+

This dependency is expressed as an extras_require= of “qt”. +It may be depended upon accordingly as “p4p[qt]”.

+

p4p.client.Qt.Context differs from the other Context classes in several respects.

+
    +
  • Each Context attempts to minimize the number of subscriptions to each named PV. +Multiple calls to monitor() will attempt to share this subscription if possible (subject to request argument).

  • +
  • All monitor() calls must express a desired maximum update rate limit through the limitHz argument.

  • +
  • As a convienence, the objects returned by put() and monitor() do not have to be stored by the caller. +The internal references kept by the Context may be cleared through the disconnect() method. +This cache extends to a single put and a single monitor subscription per PV. +So eg. initiating a put() to a PV will implicitly cancel a previous in-progress put().

  • +
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/genindex.html b/genindex.html new file mode 100644 index 00000000..fd663d46 --- /dev/null +++ b/genindex.html @@ -0,0 +1,749 @@ + + + + + + + + Index — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ + +

Index

+ +
+ _ + | A + | B + | C + | D + | E + | F + | G + | H + | I + | K + | M + | N + | O + | P + | Q + | R + | S + | T + | U + | V + | W + +
+

_

+ + + +
+ +

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

H

+ + + +
+ +

I

+ + + +
+ +

K

+ + +
+ +

M

+ + + +
+ +

N

+ + + +
+ +

O

+ + + +
+ +

P

+ + + +
+ +

Q

+ + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + +
+ +

V

+ + + +
+ +

W

+ + + +
+ + + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/gw.html b/gw.html new file mode 100644 index 00000000..db623a3d --- /dev/null +++ b/gw.html @@ -0,0 +1,1126 @@ + + + + + + + + + PVA Gateway — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

PVA Gateway

+
+

Quick Start

+

First install P4P (see the main Quick Start).

+

The following commands will set up a gateway instance named mygw on a Linux system that uses systemd:

+
  # generate a simple configuration file
+sudo python -m p4p.gw --example-config /etc/pvagw/mygw.conf
+  # generate a systemd unit file to support the gateway
+sudo python -m p4p.gw --example-systemd \
+     /etc/systemd/system/pvagw@.service
+  # start the gateway
+sudo systemctl daemon-reload
+sudo systemctl start pvagw@mygw.service
+  # check to see if the instance has started correctly
+sudo systemctl status pvagw@mygw.service
+  # set the instance to start automatically on boot
+sudo systemctl enable pvagw@mygw.service
+
+
+
+
+

Background

+

The PVA Gateway provides a way for EPICS client software to access IOCs on an isolated network.

+

In doing so, it reduces the resource load on the server-facing side, +and provides access control restrictions to requests from the client facing side. +The gateway is a specialized proxy for the PV Access (PVA) Protocol +which sits between groups of PVA clients and servers. (see What is PVAccess?)

+
+
graph nogw {
+rankdir="RL";
+serv1 [shape=box,label="EPICS IOC"];
+serv2 [shape=box,label="PVA server"];
+serv3 [shape=box,label="EPICS IOC"];
+cli1 [shape=box,label="pvget"];
+cli2 [shape=box,label="PVA client"];
+serv1 -- cli1
+serv2 -- cli1
+serv3 -- cli1
+serv1 -- cli2
+serv2 -- cli2
+serv3 -- cli2
+}
+
+

PVA Connections without a Gateway

+
+
+

Without a Gateway, M clients connect to N servers +with M*N connections (TCP sockets). If all clients are subscribed +to the same set of PVs, then each server is sending the same data values +M times.

+
+
graph gwnames {
+rankdir="RL";
+serv1 [shape=box,label="EPICS IOC"];
+serv2 [shape=box,label="PVA Server"];
+serv3 [shape=box,label="EPICS IOC"];
+subgraph clustergw {
+    label="Gateway\nProcess";
+    gwc [label="Gateway\nClient"];
+    gws [label="Gateway\nServer"];
+}
+cli1 [shape=box,label="pvget"];
+cli2 [shape=box,label="PVA Client"];
+
+serv1 -- gwc;
+serv2 -- gwc;
+serv3 -- gwc;
+gws -- cli1;
+gws -- cli2;
+}
+
+

PVA Connections through a Gateway

+
+
+

Adding a Gateway reduces the number of connections to M+N. +With M clients connecting to a gateway server on one side, and one gateway client connecting to N servers on the other. +Further, a Gateway de-duplicates subscription data updates +so that each server sends only a single update to the Gateway, +which then repeats it to each client.

+

So the PVA servers and IOCs see only a single client, +and are shielded from a potentially large number of clients on +the other side of the gateway.

+
+

Note

+

Each gateway process can define multiple internal Servers and Clients. +This allows, for example, a single gateway process to connect to multiple IOC subnets, +providing EPICS clients to access all IOCs.

+
+
+

Example

+

A common scenario is to have a gateway running on a host computer +with two network interfaces (NICs) on different subnets, +and thus two different broadcast domains.

+

In this example, a server has two NICs with IP addresses +192.168.1.5/24 and 10.1.1.4/24.

+
+
graph gwnet {
+rankdir="LR";
+serv [shape=box,label="PVA server\n192.168.1.23"];
+cli  [shape=box,label="PVA client\n10.1.1.78"];
+subgraph clustergw {
+    label="Gateway\nHost";
+    nic2 [shape=cds,label="NIC 10.1.1.4",orientation=180];
+    nic1 [shape=cds,label="NIC 192.168.1.5"];
+}
+cli -- nic2;
+nic1 -- serv;
+}
+
+

Example: A Multi-homed Host for a Gateway

+
+
+

To support this host, the gateway can be set up with the +following configuration file. +The intent is that the gateway provides EPICS clients on +the 10.1.1.0/24 subnet with access to IOCs or other PVA servers +on the 192.168.1.0/24 subnet.

+

Each of the statements in this configuration file are explained +below

+
/* C-style comments are supported */
+{
+    "version":2,
+    "clients":[
+        {
+            "name":"client192",
+            "addrlist":"192.168.1.255",
+            "autoaddrlist":false
+        }
+    ],
+    "servers":[
+        {
+            "name":"server10",
+            "clients":["client192"],
+            "interface":["10.1.1.4"],
+            "addrlist":"10.1.1.255",
+            "autoaddrlist":false,
+            "statusprefix":"GW:STS:" /* optional, but suggested */
+        }
+    /* optional, allows server side access to Gateway status */
+        ,{
+            "name":"server192",
+            "clients":[],
+            "interface":["192.168.1.5"],
+            "addrlist":"192.168.1.255",
+            "autoaddrlist":false,
+            "statusprefix":"GW:STS:"
+        }
+    ]
+}
+
+
+

The version statement is described below.

+

The clients section specifies the name of its only Client to be client192 and is configured to search on the 192.168.1.0/24 subnet by +providing the 192.168.1.255 broadcast address as the only member of the addrlist. +This is the network to which an EPICS IOC is attached, so it will receive broadcast searches +from this gateway acting as a client.

+

The servers section specifies the name of its first Server to be server10, and indicates which clients can have access to it, in this case clients which are part of the clients192 section. +It is configured to listen on the 10.1.1.0/24 subnet by specifying the local interface address 10.1.1.4. +This is the network on which an EPICS client such as pvget or pvput is attached, and this gateway will act as a Server to receive their search messages. +The interface broadcast address is also provided to enable sending of server beacon packets. +This is an optimization to reduce connection time, and it is not required.

+

The statusprefix value is set to GW:STS: in this example, allowing the gateway to share some internal PVs which provide status information. +The Status PVs suffixes are described below, with the statusprefix prepended. +Sites with multiple gateways on one subnet should give each a unique statusprefix.

+

A second servers section is shown, with its name set to server192. Its set of allowed clients is empty, but interfaces and address lists are specified. +This allows the status PVs mentioned above to be accessed from the subnet hosting the IOCs and other EPICS servers. +Without this section, those status PVs are only accessible from EPICS clients on the client subnets.

+
+

Note

+

A single gateway will not connect to itself (no Gateway client will connect to a Gateway server in the same instance). +However, this automatic loop avoidance is not possible in more complex situations involving multiple gateways. +If such a setup is judged necessary, care should be taken to ensure that loops can not form. +See also the servers[].ignoreaddr in Configuration File Keywords.

+
+
+
+
+

Command Line Arguments

+
usage: pvagw [-h] [--no-ban-local] [-v] [--logging LOGGING] [--debug] [-T] [--example-config] [--example-systemd]
+             config
+
+
+
+

Positional Arguments

+
+
config
+

Config file

+
+
+
+
+

Named Arguments

+
+
--no-ban-local
+

Legacy option. Ignored

+

Default: False

+
+
-v, --verbose
+

Enable basic logging with DEBUG level

+

Default: 20

+
+
--logging
+

Use logging config from file (JSON in dictConfig format)

+
+
--debug
+

Enable extremely verbose low level PVA debugging

+

Default: False

+
+
-T, --test-config
+

Read and validate configuration files, then exit w/o starting a gateway. Also prints the names of all configuration files read.

+

Default: False

+
+
--example-config
+

Write an example configuration file and exit. “–example-config -” writes to stdout

+

Default: False

+
+
--example-systemd
+

Write an example systemd unit file and exit “–example-systemd -” writes to stdout

+

Default: False

+
+
+
+
+
+

Configuration File

+

Configuration is provided as a file using JSON syntax with C-style comments.

+
/* C-style comments allowed */
+{
+    "version":2,
+    "readOnly":false,
+    "clients":[
+        {
+            "name":"theclient",
+            "provider":"pva",
+            "addrlist":"...",
+            "autoaddrlist":false,
+            "bcastport":5076
+        }
+    ],
+    "servers":[
+        {
+            "name":"theserver",
+            "clients":["theclient"],
+            "interface":["..."],
+            "addrlist":"",
+            "ignoreaddr":["..."],
+            "autoaddrlist":false,
+            "serverport":5075,
+            "bcastport":5076,
+            "getholdoff":1.0,
+            "statusprefix":"PV:",
+            "access":"somefilename.acf",
+            "pvlist":"somefilename.pvlist"
+        }
+    ]
+}
+
+
+

See also PVXS client and server configuration references.

+

Run pvagw --example-config - to see another example configuration.

+
+

Configuration File Keywords

+

Here is a full list of JSON keys available for the configuration file, version 2.

+
+
version

JSON Scheme version number. 2 is recommended for new files. Valid values are 1 or 2.

+
+
readOnly (default: false)

Boolean flag which, if set, acts as a global access control rule which rejects +all PUT or RPC operations. This takes precedence over any ACF file rules.

+
+
clients

List of Gateway Client configurations.

+
+
clients[].name

Unique name for this Client within this gateway process.

+
+
clients[].provider (default: “pva”)

Selects a ChannelProvider. Currently only “pva” is valid.

+
+
clients[].addrlist (default: “”)

List of broadcast and unicast addresses to which search messages will be sent.

+
+
clients[].autoaddrlist (default: true)

Whether to automatically populate addrlist with all local interface broadcast addresses. +Use caution when setting true.

+
+
clients[].bcastport (default: 5076)

UDP port to which searches are sent.

+
+
servers

List of gateway Server configurations.

+
+
servers[].name

Unique name of this Server within this gateway process.

+
+
servers[].clients

A list of zero or more gateway Client names. +Search requests allowed through this server will be made through all listed clients.

+
+
servers[].interface (default: [“0.0.0.0”])

A list of local interface addresses to which this gateway Server will bind.

+
+
servers[].addrlist (default: “”)

List of broadcast and unicast addresses to which beacon messages will be sent

+
+
servers[].ignoreaddr (default: “”)

List of address to add into the banned list to explicit ignore hosts.

+
+
servers[].autoaddrlist (default: true)

Whether to automatically populate addrlist with all local interface broadcast addresses. +Use caution when setting true.

+
+
servers[].serverport (default: 5075)

Default TCP port to bind. If not possible, a random port will be used.

+
+
servers[].bcastport (default: 5076)

UDP port bound to receive search requests, as well as the port to which beacons are sent.

+
+
servers[].getholdoff (default: 0)

A value greater than zero enables rate limiting of Get operations. +getholdoff defines a hold-off time after a GET on a PV completes, before the another will be issued. +Another GET for the same PV made before the hold-off expires will be delayed until expiration. +Concurrent GET operations may be combined.

+

This activity is per PV.

+
+
servers[].statusprefix (default: “”)

The text used by this gateway as a prefix to construct names for PVs which communicate status information. +The PVs report overall status for the gateway process, regardless of the number of internal Clients or Servers. +Each of the status PVs are defined in Status PVs. +Note that the prefix will typically end with the delimiter used in your PV naming convention, such as :.

+
+
servers[].access (default: “”)

Name an ACF file to use for access control decisions for requests made through this server. +See ACF Rules File. +Relative file names are interpreted in relation to the directory containing the config file.

+
+
servers[].pvlist (default: “”)

Name of PVList file used to restrict access to certain PVs through this Server. +See PVList File. +Relative file names are interpreted in relation to the directory containing the config file.

+
+
servers[].acf_client

Needed only if access key is provided, and clients list has more than one entry. +Unambiguously selects which client is used to connect INP PVs for use by conditional ACF rules. +If not provided, then the first client in the list is used.

+
+
+
+
+
+

Status PVs

+

Servers with the statusprefix key set will provide access to the following PVs. +These values are aggregated from all defined internal gateway Servers and Clients.

+
+

Warning

+

The PV names resulting from the statusprefix and the PV suffixes shown below must be unique across your site. +Each gateway instance must have a unique statusprefix value.

+
+
+
<statusprefix>asTest

An RPC only PV which allows testing of PVList and ACF rules.

+
$ pvcall <statusprefix>asTest pv=some:name
+
+
+

Other arguments include user="xx", peer="1.1.1.1:12345, and roles=["yy"]. +If omitted, the credentials of the requesting client are used.

+
+
<statusprefix>clients

A list of client’s names connected to the GW server

+
+
<statusprefix>cache

A list of channels to which the GW Client is connected

+
+
<statusprefix>refs

Table of object type names and instance counts. +May be useful for detecting resource leaks while troubleshooting.

+
+
<statusprefix>threads

Available when running with python >= 3.5. +An RPC call which returns a text description of all python threads.

+
+
+
+

Note

+

The following PVs provide data bandwidth information for the overall gateway.

+
    +
  • The ds in the names refer to downstream requests from EPICS clients to the gateway, or responses from the gateway to EPICS clients.

  • +
  • The us in the names refer to upstream requests from the gateway to IOCs, or responses from an IOC to the gateway.

  • +
  • The bypv or byhost in the names refer to status relating to the involved PVs or host machines, respectively.

  • +
  • The rx and tx in the names refer to receiving or transmitting data from the gateway’s perspective.

  • +
+
+
+
<statusprefix>ds:bypv:rx

A table containing bandwidth usage of requests for each PV sent from PVA clients such as pvget or pvput to this gateway. This can be a relatively low number since the requests are often small in size. +The table is sorted from highest bandwidth PVs to lowest.

+
+
<statusprefix>us:bypv:tx

A table containing bandwidth usage of requests for each PV sent from this gateway to PVA Servers such as IOCs. This can be a relatively low number since the requests are often small in size. +The table is sorted from highest bandwidth PVs to lowest.

+
+
<statusprefix>us:bypv:rx

A table containing bandwidth usage of responses from each PV sent from PVA Servers such as IOCs to this gateway. +The table is sorted from highest bandwidth PVs to lowest.

+
+
<statusprefix>ds:bypv:tx

A table containing bandwidth usage of responses from each PV sent from this gateway to EPICS clients that made the original requests. +The table is sorted from highest bandwidth PVs to lowest.

+
+
<statusprefix>ds:byhost:rx

A table containing bandwidth usage of each host sending requests from PVA clients such as pvget or pvput to this gateway. This can be a relatively low number since the requests are often small in size. +The table is sorted by host machine with the highest bandwidth usage to lowest.

+
+
<statusprefix>us:byhost:tx

A table containing bandwidth usage of requests sent from this gateway to each host containing PVA Servers such as IOCs. This can be a relatively low number since the requests are often small in size. +The table is sorted by host machine with the highest bandwidth usage to lowest.

+
+
<statusprefix>us:byhost:rx

A table containing bandwidth usage of each host providing responses from PVA Servers such as IOCs to this gateway. +The table is sorted by host machine with the highest bandwidth usage to lowest.

+
+
<statusprefix>ds:byhost:tx

A table containing bandwidth usage of each client’s host accepting responses from this gateway. +The table is sorted by host machine with the highest bandwidth usage to lowest.

+
+
+
+
+

Log File Configuration

+

The gateway is able to record messages associated with important events to one or more destinations as it runs, +including log files or a console device. +The messages can be debugging aids for developers, +or errors encountered as the gateway is working. +It also records the time at which the gateway starts or stops, and when starting, +lists the configuration details for the internal clients and servers, and lists each status PV that the gateway will make available.

+

A python dictConfig +logging configuration file in JSON format can be passed to --logging +to provide control of formating of the logged messages.

+

One logger name of special interest is p4p.gw.audit which is used for messages arising from TRAPWRITE and Put logging.

+

The following is an example of a log configuration file which records INFO messages or worse to a log file, +but also records WARNING messages or worse to the computer console. +It specifies different formats for console-bound messages versus log file messages, +and instructs the system to maintain daily log files (and audit files, if enabled), +in a subdirectory called BL3-LOGS. +It will create new, empty log files each midnight while keeping previous log files for 14 days.

+

Note that fixed-width columns are specified for some fields using sequences like 15s, -4d or 4.4s, +similar to printf style format specifiers:

+
{
+    "version": 1,
+    "disable_existing_loggers": false,
+    "formatters": {
+        "fileFormat": {
+            "format": "%(asctime)s | %(name)15s line %(lineno)-4d [%(levelname)4.4s] %(message)s"
+        },
+        "consoleFormat": {
+            "format": "%(asctime)s | %(name)s: %(levelname)s - %(message)s"
+        }
+    },
+    "handlers": {
+        "fileMessages": {
+            "level": "INFO",
+            "class": "logging.handlers.TimedRotatingFileHandler",
+            "formatter": "fileFormat",
+            "filename": "BL3-LOGS/gateway-BL3-DMZ.log",
+            "when": "midnight",
+            "interval": 1,
+            "backupCount": 14
+        },
+        "consoleMessages": {
+            "level": "WARNING",
+            "class": "logging.StreamHandler",
+            "formatter": "consoleFormat",
+            "stream": "ext://sys.stdout"
+        }
+    },
+    "loggers": {
+        "": {
+            "handlers": ["fileMessages","consoleMessages"],
+            "level": "INFO",
+            "propagate": true
+        }
+    }
+}
+
+
+
+
+

Access Control Model

+

A gateway may apply access control restrictions in addition to any restrictions +applied by individual IOCs, or other PVA servers, to which it connects. +By default a gateway apply no restrictions. +A gateway without a PVList File or ACF Rules File will allow all clients to attempt any operation on any PV.

+

One or more of the readOnly, access, and/or pvlist configuration file keys enable +restrictions within a gateway.

+

The simplest and most direct restriction is the readOnly configuration file key, +which applies to all logical Servers within a gateway. +If set, no PUT or RPC operations are allowed. +Both MONITOR and GET operations are allowed, so readOnly applies a simple one-way policy +to allow clients to receive data without being permitted to change any PV settings.

+

A more granular policy is often desired, +which can be expressed with a PVList File and/or ACF Rules File.

+

Access decisions are made as follows:

+
    +
  1. PV name and client IP address are looked up in a PVList. +If DENY, then client searches are ignored.

  2. +
  3. If readOnly is set, then any PUT or RPC operation is rejected. GET/MONITOR proceed.

  4. +
  5. The PV name and peer IP address are looked up in a PVList. +If DENY, then the operation is rejected. +If ALLOW/ALIAS then an ASG name and level (0 or 1) is found.

  6. +
  7. The ASG name and level are look up in a ACF file. +GET/MONITOR operations are always allowed (no write only PVs). +PUT or RPC operations are allowed if appropriate WRITE/PUT/RPC permission is granted.

  8. +
+
+
+

PVList File

+

The purpose of the PVList file is to specify which PVs are allowed or denied, +and to associate those PVs with access security groups (ASG) and security levels (ASL) in the access file. +Supported PVList file syntax is mostly compatible with that of the Channel Access Gateway.

+

If not provided, the default PVList file used is .* ALLOW.

+

While allows all PV names from all clients.

+

PVList files are line based, with lines consisting of the following.

+
+

Note

+

Matching is not in strict lexical order. See below.

+
+
    +
  1. Blank lines and # comments are allowed.

    +
    # comment line
    +
    +
    +
  2. +
  3. Evaluation order statement, primarily to maintain backward compatibility with CA Gateway.

    +
    # (default if omitted)
    +EVALUATION ORDER ALLOW, DENY
    +
    +# Not currently supported
    +#EVALUATION ORDER DENY, ALLOW
    +
    +
    +
  4. +
  5. A DENY statement which specifies that certain PVs are denied access from certain EPICS clients. +It can specify an optional host from which clients will be denied access. +<PV name regexp> is a regular expression to match PV names. +This statement is of the forms

    +
    <PV name regexp> DENY
    +<PV name regexp> DENY FROM <hostname_or_IP>
    +
    +
    +
  6. +
+
    +
  1. An ALLOW statement which specifies that certain PVs are allowed to be accessed from EPICS clients. +It can specify an optional Access Security Group (ASG), +with an accompanying but optional Access Security Level (0 or 1), +both of which used when evaluating an ACF file. +This statement is of the forms

    +
    <PV name regexp> ALLOW
    +<PV name regexp> ALLOW <ASG>
    +<PV name regexp> ALLOW <ASG> <ASL_0_or_1>
    +
    +
    +
  2. +
+

If not provided, ASG is DEFAULT, and ASL is 0.

+
    +
  1. An Alias statement which provides a way to specify a specific PV name based on a more general pattern. +This is equivalent to a ALLOW statement with an additional name translation. +This statement is of the forms

    +
    <PV name regexp> ALIAS <real PV name>
    +<PV name regexp> ALIAS <real PV name> <ASG>
    +<PV name regexp> ALIAS <real PV name> <ASG> <ASL_0_or_1>
    +
    +
    +
  2. +
+

When a gateway Server receives a request from a client to access a PV, +the PV name is compared to each pattern in the list.

+

The order in which regular expressions are matched is that all DENY statements are considered +before any ALLOW/ALIAS statements (regardless of the order of lines). +PV names which do not match any statement are DENYed.

+

When a PV name matches more than one ALLOW/ALIAS statements, +the order of lines is used. +The last match will have effect.

+

Considering the following PVList file:

+
ACCL:CRYO:.* DENY
+ACCL:.*      ALLOW MISCONFIG
+ACCL:.*      ALLOW
+ACCL:RF.*    ALLOW RF
+
+
+

ACCL:CRYO:ESTOP would match the DENY rule, so a gateway will not allow any access.

+

ACCL:RF:FPWR would match the ALLOW RF rule, and be allowed subject to rules for ASG(RF).

+

ACCL:ARC:CNT would match the last ALLOW rule, and be allowed subject to ASG(DEFAULT).

+

Because both the ALLOW MISCONFIG and ALLOW rules have identical patterns, +the ALLOW will always be used and ALLOW MISCONFIG will never be used.

+

Note that because DENY rules are always considered before ALLOW or ALIAS rules, +the preceding file is functionally identical to the following as moving the DENY +relative to ALLOW does not change the evaluation order.

+
ACCL:.*      ALLOW MISCONFIG
+ACCL:.*      ALLOW
+ACCL:RF.*    ALLOW RF
+ACCL:CRYO:.* DENY
+
+
+

When building a PVList file containing ALLOW or ALIAS rules with overlapping patterns, +it is therefore necessary to put the more general patterns before the more specific patterns. +eg.

+
ACCL:RF.*    ALLOW RF
+ACCL:.*      ALLOW
+
+
+

In this example the ALLOW RF rule is effectively hidden, and will never be matched.

+
+
+

ACF Rules File

+

An Access Security File (ACF) is a list of access control rules to be applied +to requests based on which Access Security Group (ASG) was selected by a PVList file, or DEFAULT +if no PVList file is used. The ASG name selects which a group of rules.

+

Unknown ASG names use the DEFAULT rules. +If no DEFAULT group is defined, then no privileges are granted.

+

Each ACF file may define zero or more Host Access Groups (HAG s) and/or +User Access Groups (UAG s). +Also, one or more list of rules (ASG s). +The HAG is a list of host names, and the UAG a list of user names.

+

eg. PVs in ASG DEFAULT only permit PUT or RPC requests originating from +hosts incontrol or physics. +PUT requests from physics will be logged.

+
HAG(MCF) { "incontrol" }
+HAG(OTHER) { "physics" }
+ASG(DEFAULT) {
+    RULE(1, WRITE) {
+        HAG(MCF)
+    }
+    RULE(1, WRITE, TRAPWRITE) {
+        HAG(OTHER)
+    }
+}
+
+
+
+

Privileges

+

RULE s may grant one of the following privileges.

+
+
WRITE

Shorthand to grant both PUT and RPC requests.

+
+
PUT

Allow PUT operation on all fields.

+
+
RPC

Allow RPC operations.

+
+
UNCACHED

Special privilege which allows a client to bypass deduplication/sharing of subscription data. +A client would make use of this privilege by including a pvRequest option record._options.cache +with a boolean false value.

+
+
READ

Accepted for compatibility. +PVA Gateway always allows read access for any PV which is allowed by the PVList file. +Use a DENY in a PVList file to prevent clients from reading or subscribing to certain PVs.

+
+
+
+
+

HAG Hostnames and IPs

+

Entries in a HAG() may be either host names, or numeric IP addresses. +Host names are resolved once on Gateway startup. +Therefore, changes in the hostname to IP mapping will not be visible +until a Gateway is restarted.

+
+
+

UAG and Credentials

+

PV Access protocol provides a weakly authenticated means of identification based on a remotely provided user name. +This is combined with a set of “role”s taken by looking up system groups of which the username is a member. +(See /etc/nsswitch.conf on Linux).

+

Both user and role names may appear in UAG lists. eg.

+
UAG(SPECIAL)
+{
+    root,
+    "role/admin"
+}
+
+
+

And a rule:

+
ASG(DEFAULT) {
+    RULE(1, WRITE) {
+        UAG(SPECIAL)
+    }
+}
+
+
+

In this case, the RULE will be match if a client identifies itself with username root +or if the (remotely provided) username is a member of the (locally tested) admin role (eg. unix group).

+

In this case, such a match will grant the WRITE privilege for PVs in the DEFAULT ASG.

+

Role/group membership can be tested with the <statusprefix>asTest status PV.

+
+
+

TRAPWRITE and Put logging

+

If a RULE includes the TRAPWRITE modifier, then a PUT operation it allows +will be logged. +Refer to the Log File Configuration section for more information.

+

Messages are logged through the p4p.gw.audit python logger.

+
+
+

ACF Syntax

+
+acf       ::=  | item acf
+item      ::=  uag | hag | asg
+uag       ::=  UAG ( "NAME" ) { users }
+hag       ::=  HAG ( "NAME" ) { hosts }
+asg       ::=  ASG ( "NAME" ) { asitems }
+users     ::=  "HOSTNAME"
+              "HOSTNAME" , users
+hosts     ::=  "USERNAME"
+               "USERNAME" , hosts
+asitems   ::=  | asitem asitems
+asitem    ::=  INP[A-Z] ( "PVNAME" )
+               RULE ( ASL#, priv) rule_cond
+               RULE ( ASL#, priv, trap) rule_cond
+priv      ::=  READ | WRITE | PUT | RPC | UNCACHED
+trap      ::=  TRAPWRITE | NOTRAPWRITE
+rule_cond ::=  | { conds }
+conds     ::=  | cond conds
+cond      ::=  UAG ( "NAME" )
+               HAG ( "NAME" )
+               CALC ( "EXPR" )
+
+
+
+
+

Application Notes

+

The process of configuring a Gateway begins by looking at the +physical and/or logical topology of the networks in question.

+

A Gateway is typically placed at the boundary between one or more networks (subnets).

+

While a simple Gateway configuration will have a single GW Server connected to a single GW Client, +more complicated configurations are possible, with many GW Servers and one GW Client, +or one GW Server and many GW Clients, or a many to many configuration.

+

It is valid for a GW Client and GW Server to be associated with the same host interface and port +provided that they are not associated with each other. +Pairs of such GW Client and GW Server may be cross linked to form a bi-directional Gateway.

+

It is meaningful to configure a GW Server with no GW Clients ( "clients":[] ) +provided that the "statusprefix" key is set. +This server will only provide the status PVs. +This can be used to eg. provide GW status monitoring from both sides of a one-way Gateway.

+
+

Differences from CA gateway

+

Summary of known differences from CA gateway.

+
    +
  • EVALUATION ORDER DENY, ALLOW is not supported.

  • +
  • Permission READ is implied. Write-only PVs are not possible.

  • +
+
+
+
+

Implementation Details

+

Gateway is implemented as a hybrid of Python and C++. +In the interest of performance, Python code is only in the “slow” path +for the PV search/connection decision. +After a PV is connected; permissions changes, auditing, and monitoring are communicated +externally from Python code.

+

The APIs described below are not currently considered stable or public for use by external modules. +They are documentation here for the purposes of internal development and debugging.

+
+

Negative Results Cache

+

In order to shield the Python testChannel() handler from repeated reconnect attempts +for denied PVs, a list of blocked PVs, IPs, and pairs of PV and IP +is maintained in C++ code. Search requests matching one of these three criteria +will be ignored without calling testChannel().

+
+
+

p4p.gw Frontend

+

This module utilizes the related C++ extension to setup and manage a Gateway +which is configured in a manner similar to the pva2pva gateway +with an access control policy defined in a manner similar to cagateway. +Other means of configuration and policy definition could be implemented.

+
+
+

C++ Extension

+

Setup execution flow for use of the C++ extension is:

+
    +
  1. Create a ClientProvider

  2. +
  3. Create a Provider using this client

  4. +
  5. Create a p4p.server.Server referencing the provider name.

  6. +
+

More than one Provider may reference to the same ClientProvider. +A p4p.server.Server may reference more than one Provider, +and a Provider may be referenced by more than one p4p.server.Server. +Many p4p.server.Server s may be created.

+

After server startup, the handler object associated with a Provider +will be called according to the _gw.ProviderHandler interface.

+

The C++ extension deals only with IP addresses in string form, +possibly with port number (eg. “1.2.3.4:5076)”, and never host names.

+
+
+class p4p._gw.Provider
+
+
+Claim
+
+ +
+
+Ignore
+
+ +
+
+BanHost
+
+ +
+
+BanPV
+
+ +
+
+BanHostPV
+
+ +
+
+testChannel(usname)
+

Add the upstream name to the channel cache and begin trying to connect. +Returns Claim if the channel is connected, and Ignore if it is not.

+
+
Parameters:
+

usname (bytes) – Upstream (Server side) PV name

+
+
Returns:
+

Claim or Ignore

+
+
+
+ +
+
+sweep()
+

Call periodically to remove unused Channel from channel cache.

+
+ +
+
+forceBan()
+

Preemptively Add an entry to the negative result cache. +Either host or usname must be not None

+
+
Parameters:
+
    +
  • host (bytes) – None or a host name

  • +
  • usname (bytes) – None or a upstream (Server side) PV name

  • +
+
+
+
+ +
+
+clearBan()
+

Clear the negative results cache

+
+ +
+
+cachePeek()
+

Returns PV names in channel cache

+
+
Returns:
+

a set of strings

+
+
+
+ +
+
+stats()
+

Return statistics of various internal caches

+
+
Return type:
+

dict

+
+
+
+ +
+
+report()
+

Run Client/Upstream bandwidth usage report

+
+
Returns:
+

List of tuple

+
+
Return type:
+

[(usname, opTx, opRx, peer, trTx, trRx)]

+
+
+
+ +
+ +
+
+class p4p._gw.InfoBase
+
+
+account
+
+ +
+
+peer
+
+ +
+
+roles
+
+ +
+ +
+
+class p4p._gw.CreateOp
+

Handle for in-progress Channel creation request

+
+
+create()
+

Create a Channel with a given upstream (server-side) name

+
+
Parameters:
+

name (bytes) – Upstream name to use. This is what the GW Client will search for.

+
+
Returns:
+

A Channel

+
+
+
+ +
+
+name
+
+ +
+ +
+
+class p4p._gw.Channel
+
+
+access()
+
+ +
+
+expired
+
+ +
+
+name
+
+ +
+ +
+
+

Interfaces

+
+
+class p4p._gw.ProviderHandler
+

A Handler object associated with a Provider should implement these methods

+
+
+testChannel(self, pvname, peer)
+
+
Parameters:
+
    +
  • pvname (str) – PV name being searched (downstream)

  • +
  • peer (str) – IP address of client which is searching

  • +
+
+
Returns:
+

Claim, Ignore, BanHost, BanPV, or BanHostPV

+
+
+

Hook into search phase. Called each time a client searches for a pvname. +If permitted, call and return the result of Provider.testChannel() with the desired upstream (server-side PV name).

+
    +
  • Returning Claim may result in a later call to makeChannel().

  • +
  • Returning Ignore may result in a repeated call to testChannel() in future.

  • +
  • Returning BanHost adds this host to the negative results cache

  • +
  • Returning BanPV adds this PV to the negative results cache.

  • +
  • Returning BanHostPV adds this combination of host and PV to the negative results cache

  • +
+
+ +
+
+makeChannel(self, op)
+

Hook info channel creation phase. If permitted, call and return the result of CreateOp.create(). +The Channel object may be stored by python code to track and effect active connections. +eg. call Channel.access() to set/change privileges. +Or Channel.close() to force disconnection.

+

Due to the continuous nature of PVA client (re)connection process, inability to create +a channel at this stage is treated as a hard failure to avoid a reset loop. +If it is necessary to return None, then steps should be taken to ensure that a +re-connection attempt would have a different result. eg. through Provider.forceBan().

+
+
Parameters:
+

op (CreateOp) – Handle for ongoing operation

+
+
Returns:
+

A Channel.

+
+
+
+ +
+
+audit(self, msg)
+

Hook info PUT logging process. Called from a worker thread.

+
+
Parameters:
+

msg (str) – Message string to be logged

+
+
+
+ +
+ +
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 00000000..c2f630dd --- /dev/null +++ b/index.html @@ -0,0 +1,216 @@ + + + + + + + + + PVAccess for Python (P4P) — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

PVAccess for Python (P4P)

+

P4P is a wrapper around the PVAccess (aka. PVA) protocol network client and server. +P4P is part of the EPICS (Experimental Physics and Industrial Control System) ecosystem +for creating large (and small) scale distributed process control and data acqisition sytems. +https://epics.anl.gov/

+

P4P includes API for a Client API and Server API, +as well as a PVA Gateway executable (pvagw) which can optionally enforce an access control policy.

+

Supports Linux, OSX, and Windows. With python 2.7 and >=3.5 (>=3.6 for asyncio support).

+

The recommended starting point is to install from pypi.org.

+
python -m virtualenv p4ptest
+. p4ptest/bin/activate
+python -m pip install -U pip
+python -m pip install p4p nose2
+python -m nose2 p4p   # Optional: runs automatic tests
+
+
+ +

Contents:

+ +
+
+

Indices and tables

+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/internal.html b/internal.html new file mode 100644 index 00000000..c8c6c46f --- /dev/null +++ b/internal.html @@ -0,0 +1,436 @@ + + + + + + + + + Internal API — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Internal API

+

This section is intended to help P4P developers. +The API described is not considered a public or stable API. +It may change without notice.

+
+

Ownership

+

The ownership relations between the various objects in the C++ +extensions are shown in the following diagrams.

+
    +
  • Python objects are blue ovals

  • +
  • C++ objects are black boxes

  • +
  • red lines are shared_ptr<>

  • +
  • green lines are weak_ptr<>

  • +
  • blue lines are python refs. (aka stored PyObject*)

  • +
  • dashed lines are explicit breaks of a ref. loop

  • +
+
+

Type and Value

+
digraph values {
+Value [shape=oval, color=blue];
+Type [shape=oval, color=blue];
+Array [shape=oval, color=blue];
+ndarray [shape=oval, color=blue];
+PVStructure [shape=box];
+Structure [shape=box];
+shared_vector [shape=box];
+
+# wraps
+Value -> PVStructure [color=red];
+Type -> Structure [color=red];
+Array -> shared_vector [color=red];
+# internal
+PVStructure -> shared_vector [color=red];
+PVStructure -> Structure [color=red];
+# pyrefs
+ndarray -> Array [color=blue];
+}
+
+
+
+

API Reference

+
+

Raw client API

+
+
+class p4p.client.raw.Context(provider='pva', conf=None, useenv=None, unwrap=None, nt=None, **kws)[source]
+
+
Parameters:
+
    +
  • provider (str) – A Provider name. Try “pva” or run Context.providers() for a complete list.

  • +
  • dict (conf) – Configuration to pass to provider. Depends on provider selected.

  • +
  • useenv (bool) – Allow the provider to use configuration from the process environment.

  • +
  • nt (dict) – Controls Automatic Value unwrapping. None uses defaults. Set False to disable

  • +
  • unwrap (dict) – Legacy Automatic Value unwrapping.

  • +
+
+
+
+
+disconnect(name=None)[source]
+

Clear internal Channel cache, allowing currently unused channels to be implictly closed.

+
+
Parameters:
+

name (str) – None, to clear the entire cache, or a name string to clear only a certain entry.

+
+
+
+ +
+
+get(name, handler, request=None)[source]
+

Begin Fetch of current value of a PV

+
+
Parameters:
+
    +
  • name – A single name string or list of name strings

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • handler (callable) – Completion notification. Called with a Value, RemoteError, or Cancelled

  • +
+
+
Returns:
+

A object with a method cancel() which may be used to abort the operation.

+
+
+
+ +
+
+monitor(name, handler, request=None, **kws)[source]
+

Begin subscription to named PV

+
+
Parameters:
+
    +
  • name (str) – PV name string

  • +
  • handler (callable) – Completion notification. Called with None (FIFO not empty), RemoteError, Cancelled, or Disconnected

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • notify_disconnect (bool) – Whether disconnect (and done) notifications are delivered to the callback (as None).

  • +
+
+
Returns:
+

A Subscription

+
+
+
+ +
+
+put(name, handler, builder=None, request=None, get=True)[source]
+

Write a new value to a PV.

+
+
Parameters:
+
    +
  • name – A single name string or list of name strings

  • +
  • handler (callable) – Completion notification. Called with None (success), RemoteError, or Cancelled

  • +
  • builder (callable) – Called when the PV Put type is known. A builder is responsible +for filling in the Value to be sent. builder(value)

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
  • get (bool) – Whether to do a Get before the Put. If True then the value passed to the builder callable +will be initialized with recent PV values. eg. use this with NTEnum to find the enumeration list.

  • +
+
+
Returns:
+

A object with a method cancel() which may be used to abort the operation.

+
+
+
+ +
+
+rpc(name, handler, value, request=None)[source]
+

Perform RPC operation on PV

+
+
Parameters:
+
    +
  • name – A single name string or list of name strings

  • +
  • handler (callable) – Completion notification. Called with a Value, RemoteError, or Cancelled

  • +
  • request – A p4p.Value or string to qualify this request, or None to use a default.

  • +
+
+
Returns:
+

A object with a method cancel() which may be used to abort the operation.

+
+
+
+ +
+ +
+
+exception p4p.client.raw.RemoteError
+

Thrown with an error message which has been sent by a server to its remote client

+
+ +
+
+class p4p.client.raw.Subscription(context, name, nt, **kws)[source]
+

Interface to monitor subscription FIFO

+

Use method poll() to try to pop an item from the FIFO. +None indicates the FIFO is empty, must wait for another Data event before +calling poll() again.

+

complete()==True after poll()==False indicates that no more updates will +ever be forthcoming. This is normal (not error) completion.

+

cancel() aborts the subscription.

+
+ +
+
+

Raw server API

+
+
+class p4p.server.raw.Handler[source]
+

Skeleton of SharedPV Handler

+

Use of this as a base class is optional.

+
+
+onFirstConnect(pv)[source]
+

Called when the first Client channel is created.

+
+
Parameters:
+

pv (SharedPV) – The SharedPV which this Handler is associated with.

+
+
+
+ +
+
+onLastDisconnect(pv)[source]
+

Called when the last Client channel is closed.

+
+
Parameters:
+

pv (SharedPV) – The SharedPV which this Handler is associated with.

+
+
+
+ +
+
+put(pv, op)[source]
+

Called each time a client issues a Put +operation on this Channel.

+
+
Parameters:
+
+
+
+
+ +
+
+rpc(pv, op)[source]
+

Called each time a client issues a Remote Procedure Call +operation on this Channel.

+
+
Parameters:
+
+
+
+
+ +
+ +
+
+class p4p.server.raw.SharedPV(handler=None, initial=None, nt=None, wrap=None, unwrap=None, options=None, **kws)[source]
+

Shared state Process Variable. Callback based implementation.

+
+

Note

+

if initial=None, the PV is initially closed and +must be open()’d before any access is possible.

+
+
+
Parameters:
+
    +
  • handler – A object which will receive callbacks when eg. a Put operation is requested. +May be omitted if the decorator syntax is used.

  • +
  • initial (Value) – An initial Value for this PV. If omitted, :py:meth:`open()`s must be called before client access is possible.

  • +
  • nt – An object with methods wrap() and unwrap(). eg p4p.nt.NTScalar.

  • +
  • wrap (callable) – As an alternative to providing ‘nt=’, A callable to transform Values passed to open() and post().

  • +
  • unwrap (callable) – As an alternative to providing ‘nt=’, A callable to transform Values returned Operations in Put/RPC handlers.

  • +
  • options (dict) – A dictionary of configuration options.

  • +
+
+
+

Creating a PV in the open state, with no handler for Put or RPC (attempts will error).

+
from p4p.nt import NTScalar
+pv = SharedPV(nt=NTScalar('d'), value=0.0)
+# ... later
+pv.post(1.0)
+
+
+

The full form of a handler object is:

+
class MyHandler:
+    def put(self, pv, op):
+        pass
+    def rpc(self, pv, op):
+        pass
+    def onFirstConnect(self): # may be omitted
+        pass
+    def onLastDisconnect(self): # may be omitted
+        pass
+
+
+

pv = SharedPV(MyHandler())

+

Alternatively, decorators may be used.

+
pv = SharedPV()
+@pv.put
+def onPut(pv, op):
+    pass
+
+
+

The nt= or wrap= and unwrap= arguments can be used as a convience to allow +the open(), post(), and associated Operation.value() to be automatically +transform to/from Value and more convienent Python types. +See Automatic Value unwrapping

+
+
+open(value, nt=None, wrap=None, unwrap=None, **kws)[source]
+

Mark the PV as opened an provide its initial value. +This initial value is later updated with post().

+
+
Parameters:
+

value – A Value, or appropriate object (see nt= and wrap= of the constructor).

+
+
+

Any clients which have begun connecting which began connecting while +this PV was in the close’d state will complete connecting.

+

Only those fields of the value which are marked as changed will be stored.

+
+ +
+
+post(value, **kws)[source]
+

Provide an update to the Value of this PV.

+
+
Parameters:
+

value – A Value, or appropriate object (see nt= and wrap= of the constructor).

+
+
+

Only those fields of the value which are marked as changed will be stored.

+

Any keyword arguments are forwarded to the NT wrap() method (if applicable). +Common arguments include: timestamp= , severity= , and message= .

+
+ +
+ +
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/nt.html b/nt.html new file mode 100644 index 00000000..3963f972 --- /dev/null +++ b/nt.html @@ -0,0 +1,550 @@ + + + + + + + + + Common Types — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Common Types

+

Helpers for creating standardized Type instances. +as defined by http://epics-pvdata.sourceforge.net/alpha/normativeTypes/normativeTypes.html +.

+
+

Automatic Value unwrapping

+

Automatic transformation can be performed. between Value and more convenient types.

+

Transformation may be performed at the following points:

+ +
+

Controlling (Un)wrapping

+

Client p4p.client.thread.Context accepts an argument nt= which may be +None to sure some reasonable defaults. False disables wrapping, +and always works with Value. nt= may also be passed a dictionary +keyed by top level structure IDs mapped to callables returning objects +conforming to WrapperInterface.

+

The unwrap argument is legacy which functions like nt= but +mapping to plain functions instead of wrapper objects.

+
from p4p.client.thread import Context
+ctxt=Context('pva', nt=False) # disable (un)wrap.  All methods use Value
+
+
+

Server p4p.server.thread.SharedPV accepts an argument nt= which +is an instance of an object conforming to WrapperInterface.

+
from p4p.server.thread import SharedPV
+from p4p.nt import NTScalar
+pv1 = SharedPV() # pv1.open() expects a plain Value
+pv2 = SharedPV(nt=NTScalar('d', display=True))
+
+# NTScalar automatically wraps this float into a Value
+pv2.open(4.2)
+
+# send change w/ system times
+pv2.post(3.3, timestamp=time.time())
+
+# explicitly wrap and set additional fields
+V = pv2.wrap(2.2, timestamp=time.time())
+V['display.description'] = "My special PV"
+pv2.post(V)
+
+
+

Conforming objects include NTScalar, NTNDArray, and others listed below.

+
+
+p4p.nt.defaultNT()[source]
+

Returns a copy of the default NT helper mappings.

+
+
Since:
+

3.1.0

+
+
+
+ +
+
+

NT wrap/unwrap interface

+
+
+class p4p.nt.WrapperInterface
+
+
Since:
+

3.1.0

+
+
+
+
+classmethod buildtype()
+

Returns a Type based on some helper specific conditions.

+
+
Return type:
+

Type

+
+
+
+ +
+
+__init__()
+

Each time the type ID of a Channel changes, a new wrapper will be instantiated if available.

+
+ +
+
+unwrap(Value) object
+

Called with a Value and may return an arbitrary object.

+

Called by both clients and servers. eg. during p4p.client.thread.Context.get() +and p4p.server.thread.SharedPV.current().

+
+ +
+
+wrap(object) Value
+

Called with an arbitrary object which it should try to translate into a Value.

+

Called by servers. eg. during p4p.server.thread.SharedPV.post().

+
+ +
+
+assign(Value, object)
+

Called to update a Value based on an arbitrary object.

+

Called by clients. eg. during p4p.client.thread.Context.put(), where +the get= argument effects the state of the Value passed in.

+
+ +
+ +
+
+
+

API Reference

+
+
+class p4p.nt.NTScalar(valtype='d', **kws)[source]
+

Describes a single scalar or array of scalar values and associated meta-data

+
>>> stype = NTScalar('d') # scalar double
+>>> V = stype.wrap(4.2)
+>>> assert isinstance(V, Value)
+
+
+
>>> stype = NTScalar.buildType('ad') # vector double
+>>> V = Value(stype, {'value': [4.2, 4.3]})
+
+
+

The result of wrap() is an augmented value object combining +ntwrappercommon and a python value type (str, int, float, numpy.ndarray).

+

Agumented values have some additional attributes including:

+
    +
  • .timestamp - The update timestamp is a float representing seconds since 1 jan 1970 UTC.

  • +
  • .raw_stamp - A tuple of (seconds, nanoseconds)

  • +
  • .severity - An integer in the range [0, 3]

  • +
  • .raw - The complete underlying Value

  • +
+
+
Parameters:
+
    +
  • valtype (str) – A type code to be used with the ‘value’ field. See Type definitions

  • +
  • extra (list) – A list of tuples describing additional non-standard fields

  • +
  • display (bool) – Include optional fields for display meta-data

  • +
  • control (bool) – Include optional fields for control meta-data

  • +
  • valueAlarm (bool) – Include optional fields for alarm level meta-data

  • +
  • form (bool) – Include display.form instead of the deprecated display.format.

  • +
+
+
+
+
+static buildType(valtype, extra=[], *args, **kws)[source]
+

Build a Type

+
+
Parameters:
+
    +
  • valtype (str) – A type code to be used with the ‘value’ field. See Type definitions

  • +
  • extra (list) – A list of tuples describing additional non-standard fields

  • +
  • display (bool) – Include optional fields for display meta-data

  • +
  • control (bool) – Include optional fields for control meta-data

  • +
  • valueAlarm (bool) – Include optional fields for alarm level meta-data

  • +
  • form (bool) – Include display.form instead of the deprecated display.format.

  • +
+
+
Returns:
+

A Type

+
+
+
+ +
+
+wrap(value, **kws)[source]
+

Pack python value into Value

+

Accepts dict to explicitly initialize fields by name. +Any other type is assigned to the ‘value’ field.

+
+ +
+
+assign(V, py)[source]
+

Store python value in Value

+
+ +
+
+classmethod unwrap(value)[source]
+

Unpack a Value into an augmented python type (selected from the ‘value’ field)

+
+ +
+ +
+
+class p4p.nt.NTNDArray(**kws)[source]
+

Representation of an N-dimensional array with meta-data

+

Translates into ntndarray

+
+
+classmethod buildType(extra=[])[source]
+

Build type

+
+ +
+
+wrap(value, **kws)[source]
+

Wrap numpy.ndarray as Value

+
+ +
+
+assign(V, py)[source]
+

Store python value in Value

+
+ +
+
+classmethod unwrap(value)[source]
+

Unwrap Value as NTNDArray

+
+ +
+ +
+
+class p4p.nt.NTTable(columns=[], extra=[])[source]
+

A generic table

+
>>> table = NTTable.buildType(columns=[
+    ('columnA', 'ai'),
+    ('columnB', 'as'),
+])
+
+
+
+
+static buildType(columns=[], extra=[])[source]
+

Build a table

+
+
Parameters:
+
    +
  • columns (list) – List of column names and types. eg [(‘colA’, ‘d’)]

  • +
  • extra (list) – A list of tuples describing additional non-standard fields

  • +
+
+
Returns:
+

A Type

+
+
+
+ +
+
+wrap(values, **kws)[source]
+

Pack an iterable of dict into a Value

+
>>> T=NTTable([('A', 'ai'), ('B', 'as')])
+>>> V = T.wrap([
+    {'A':42, 'B':'one'},
+    {'A':43, 'B':'two'},
+])
+
+
+
+ +
+
+static unwrap(value)[source]
+

Iterate an NTTable

+
+
Returns:
+

An iterator yielding an OrderedDict for each column

+
+
+
+ +
+ +
+
+class p4p.nt.NTURI(args)[source]
+
+
+static buildType(args)[source]
+

Build NTURI

+
+
Parameters:
+

args (list) – A list of tuples of query argument name and PVD type code.

+
+
+
>>> I = NTURI([
+    ('arg_a', 'I'),
+    ('arg_two', 's'),
+])
+
+
+
+ +
+
+wrap(path, args=(), kws={}, scheme='', authority='')[source]
+

Wrap argument values (tuple/list with optional dict) into Value

+
+
Parameters:
+
    +
  • path (str) – The PV name to which this call is made

  • +
  • args (tuple) – Ordered arguments

  • +
  • kws (dict) – Keyword arguments

  • +
+
+
Return type:
+

Value

+
+
+
+ +
+ +
+
+class p4p.nt.NTMultiChannel(*args, **kws)[source]
+

Describes a structure holding the equivalent of a number of NTScalar

+
+
+static buildType(valtype, extra=[])[source]
+

Build a Type

+
+
Parameters:
+
    +
  • valtype (str) – A type code to be used with the ‘value’ field. Must be an array

  • +
  • extra (list) – A list of tuples describing additional non-standard fields

  • +
+
+
Returns:
+

A Type

+
+
+
+ +
+ +
+
+class p4p.nt.scalar.ntfloat(x=0, /)[source]
+

Augmented float with additional attributes

+
    +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+
+ +
+
+class p4p.nt.scalar.ntint[source]
+

Augmented integer with additional attributes

+
    +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+
+ +
+
+class p4p.nt.scalar.ntstr[source]
+

Augmented string with additional attributes

+
    +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+
+ +
+
+class p4p.nt.scalar.ntnumericarray[source]
+

Augmented numpy.ndarray with additional attributes

+
    +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+
+ +
+
+class p4p.nt.scalar.ntstringarray(iterable=(), /)[source]
+

Augmented list of strings with additional attributes

+
    +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+
+ +
+
+class p4p.nt.ndarray.ntndarray(*args, **kws)[source]
+

Augmented numpy.ndarray with additional attributes

+
    +
  • .attrib - dictionary

  • +
  • .severity

  • +
  • .status

  • +
  • .timestamp - Seconds since 1 Jan 1970 UTC as a float

  • +
  • .raw_stamp - A tuple (seconds, nanoseconds)

  • +
  • .raw - The underlying p4p.Value.

  • +
+

Keys in the attrib dictionary may be any python which may be stored in a PVA field, +including an arbitrary Value. +However, special handling is attempted if the provided Value appears to be an NTScalar +or similar, in which case the .value, .alarm and .timeStamp are unpacked to the NTAttribute +and other fields are discarded.

+
+ +
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/objects.inv b/objects.inv new file mode 100644 index 00000000..5a55a22a Binary files /dev/null and b/objects.inv differ diff --git a/overview.html b/overview.html new file mode 100644 index 00000000..c132b544 --- /dev/null +++ b/overview.html @@ -0,0 +1,180 @@ + + + + + + + + + Overview — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Overview

+
+

What is EPICS?

+

See https://epics.anl.gov/

+
+
+

What is PVAccess?

+

The PVAccess network protocol is a hybrid supporting request/response, +and publish/subscribe operations.

+

PVA is closely related to the Channel Access (CA) protocol, +which may work along side, and is intended to supersede.

+

Four protocol operations are supported through the P4P wrapper.

+
    +
  • Get - Fetch the present value of a PV.

  • +
  • Put - Change the value of a PV.

  • +
  • Monitor - Subscribe to changes in the value of a PV.

  • +
  • RPC - A remote method call.

  • +
+

Get, Put, Monitor, and RPC are to the PVA protocol what GET, PUT, POST are to the HTTP protocol.

+
+
+

What is a PV?

+

In the EPICS world a Process Variable (PV) refers to the idea of +a globally addressed data structure. An EPICS control system is +composed of many PVs (in the millions for large facilities). The present value of +a PV is modified by a combination of remote operations via CA +and/or PVA, and via local processing (eg. values read from local +hardware).

+

A common example of a PV is a measurement value, for example +a temperature measured by a particular sensor.

+

Another example would be an electro-mechanical relay, which may be opened or closed.

+

In this case a Get operation would poll the current open/closed state of the relay. +A Monitor operation (subscription) would receive notification when the relay state changes. +A Put operation would be used to command the relay to open or close, or perhaps toggle (the precise meaning of a Put is context dependent).

+

So the Get, Put, and Monitor operation on a given PV are conventionally operating on a common data structure. +The RPC operation is more arbitrary, and need not have any relationship with a common data structure (eg. the open/closed state of the relay.)

+
+

Note

+

In the context of the PVA or CA protocols, a “PV name” is an address string which uniquely identifies a Process Variable. +All PVA network operations begin with a “PV name” string.

+
+

A “PV name” string is to the PVA and CA protocols what a URL is to the HTTP protocol. +The main difference being that while a URL is hierarchical, having a hostname and path string, +a PV name is not. The namespace of PV names is by default all local IP subnets (broadcast domains). +This can be made more complicated though the specifics of client/server network configuration.

+

The P4P module provides the ability to run PVA clients (Client API) and/or servers (Server API). +Additional convenience APIs are provided when using the RPC network operation (RPC Server Helpers).

+
+
+

What is a Value?

+

P4P represents the data which goes into, and results from, PVA network operations +with the Value class which represents a strongly typed data structure. +See Working with Value and Type for details.

+

A set of standardized data structure definitions, and utilities is provided as the Common Types API.

+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/py-modindex.html b/py-modindex.html new file mode 100644 index 00000000..68020378 --- /dev/null +++ b/py-modindex.html @@ -0,0 +1,150 @@ + + + + + + + + Python Module Index — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ + +

Python Module Index

+ +
+ p +
+ + + + + + + + + + + + + + + + + + + +
 
+ p
+ p4p +
    + p4p._gw +
    + p4p.client.raw +
    + p4p.client.thread +
    + p4p.server.raw +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/rpc.html b/rpc.html new file mode 100644 index 00000000..6c9495f2 --- /dev/null +++ b/rpc.html @@ -0,0 +1,396 @@ + + + + + + + + + RPC Server Helpers — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

RPC Server Helpers

+
+

Server Example

+

Remote Procedure Calls are received by the methods of a “target” object. +This is any class which has method decorated with rpc().

+

For example:

+
from p4p.rpc import rpc, quickRPCServer
+from p4p.nt import NTScalar
+class Summer(object):
+    @rpc(NTScalar("d"))
+    def add(self, lhs, rhs): # 'lhs' and 'rhs' are arbitrary names.  The method name 'add' will be part of the PV name
+        return float(lhs) + float(rhs)
+adder = Summer()
+
+
+

Turn on logging to see RPC related errors.

+
import logging
+logging.basicConfig(level=logging.DEBUG)
+
+
+

Now run a server with quickRPCServer().

+
quickRPCServer(provider="Example",
+               prefix="pv:call:",  # A prefix for method PV names.
+               target=adder)
+
+
+

At this point the server is active.

+

Beginning with EPICS 7.0.2 this can be tested using the “pvcall” utility

+
$ pvcall pv:call:add lhs=1 rhs=1
+2018-10-30 19:49:34.834  2
+
+
+

Previous to EPICS 7.0.2 this can be tested using the “eget” utility from the pvAccessCPP module.

+
$ eget -s pv:call:add -a lhs=1 -a rhs=1
+2
+$ eget -s pv:call:add -a lhs=1 -a rhs=1 -N  # for more detail
+epics:nt/NTScalar:1.0
+    double value 2
+    alarm_t alarm NO_ALARM NO_STATUS <no message>
+    time_t timeStamp 2017-05-20T08:14:31.917 0
+
+
+
+
+

Client Example

+

Remote procedure calls are made through the rpc() method of a Context. +To assist in encoding arguments, a proxy object can be created with the rpcproxy() decorator. +A proxy for the preceding example would be:

+
from p4p.rpc import rpcproxy, rpccall
+@rpcproxy
+class MyProxy(object):
+    @rpccall('%sadd')
+    def add(lhs='d', rhs='d'):
+        pass
+
+
+

This proxy must be associated with a Context.

+
from p4p.client.thread import Context
+ctxt = Context('pva')
+proxy = MyProxy(context=ctxt, format='pv:call:')
+print proxy.add(1, 1)
+
+
+

A decorated proxy class has two additional contructor arguments.

+
+

Using Low Level Client API

+

It may be helpful to illustrate what a proxy method call is actually doing.

+
from p4p import Type, Value
+V = Value(Type([
+    ('schema', 's'),
+    ('path', 's'),
+    ('query', ('s', None, [
+        ('lhs', 'd'),
+        ('rhs', 'd'),
+    ])),
+]), {
+    'schema': 'pva',
+    'path': 'pv:call:add',
+    'query': {
+        'lhs': 1,
+        'rhs': 1,
+    },
+})
+print ctxt.rpc('pv:call:add', V)
+
+
+
+
+
+

API Reference

+
+
+p4p.rpc.rpc(rtype=None)[source]
+

Decorator marks a method for export.

+
+
Parameters:
+

type – Specifies which Type this method will return.

+
+
+

The return type (rtype) must be one of:

+ +

Exported methods raise an Exception to indicate an error to the remote caller. +RemoteError may be raised to send a specific message describing the error condition.

+
>>> class Example(object):
+    @rpc(NTScalar.buildType('d'))
+    def add(self, lhs, rhs):
+        return {'value':float(lhs)+flost(rhs)}
+
+
+
+ +
+
+p4p.rpc.rpcproxy(spec)[source]
+

Decorator to enable this class to proxy RPC client calls

+

The decorated class constructor takes two additional arguments, +context= is required to be a Context. +format`= can be a string, tuple, or dictionary and is applied +to PV name strings given to :py:func:`rpcall. +Other arguments are passed to the user class constructor.

+
@rpcproxy
+class MyProxy(object):
+    @rpccall("%s:add")
+    def add(lhs='d', rhs='d'):
+        pass
+
+ctxt = Context('pva')
+proxy = MyProxy(context=ctxt, format="tst:")  # evaluates "%s:add"%"tst:"
+
+
+

The decorated class will be a sub-class of the provided class and RPCProxyBase.

+
+ +
+
+p4p.rpc.rpccall(pvname, request=None, rtype=None)[source]
+

Decorator marks a client proxy method.

+
+
Parameters:
+
    +
  • pvname (str) – The PV name, which will be formated using the ‘format’ argument of the proxy class constructor.

  • +
  • request – A pvRequest string or p4p.Value passed to eg. p4p.client.thread.Context.rpc().

  • +
+
+
+

The method to be decorated must have all keyword arguments, +where the keywords are type code strings or Type.

+
+ +
+
+p4p.rpc.quickRPCServer(provider, prefix, target, maxsize=20, workers=1, useenv=True, conf=None, isolate=False)[source]
+

Run an RPC server in the current thread

+

Calls are handled sequentially, and always in the current thread, if workers=1 (the default). +If workers>1 then calls are handled concurrently by a pool of worker threads. +Requires NTURI style argument encoding.

+
+
Parameters:
+
    +
  • provider (str) – A provider name. Must be unique in this process.

  • +
  • prefix (str) – PV name prefix. Along with method names, must be globally unique.

  • +
  • target – The object which is exporting methods. (use the rpc() decorator)

  • +
  • maxsize (int) – Number of pending RPC calls to be queued.

  • +
  • workers (int) – Number of worker threads (default 1)

  • +
  • useenv – Passed to Server

  • +
  • conf – Passed to Server

  • +
  • isolate – Passed to Server

  • +
+
+
+
+ +
+
+class p4p.rpc.RPCProxyBase[source]
+

Base class for automatically generated proxy classes

+
+
Parameters:
+
    +
  • context (Context) – The client Context through which calls are made

  • +
  • format – A tuple or dict which is applied with the format ‘%’ operator to the name strings given to rpccall().

  • +
+
+
+
+
+context = None
+

The Context provided on construction

+
+ +
+
+timeout = 3.0
+

Timeout of RPC calls in seconds

+
+ +
+
+authority = ''
+

Authority string sent with NTURI requests

+
+ +
+
+throw = True
+

Whether call errors raise an exception, or return it

+
+ +
+ +
+
+class p4p.rpc.NTURIDispatcher(queue, prefix=None, **kws)[source]
+

RPC dispatcher using NTURI (a al. eget)

+

Method names are prefixed with a fixed string.

+
>>> queue = WorkQueue()
+>>> class Summer(object):
+    @rpc([('result', 'i')])
+    def add(self, a=None, b=None):
+        return {'result': int(a)+int(b)}
+>>> installProvider("arbitrary", NTURIDispatcher(queue, target=Summer(), prefix="pv:prefix:"))
+
+
+

Making a call with the CLI ‘eget’ utility:

+
$ eget -s pv:prefix:add -a a=1 -a b=2
+....
+int result 3
+
+
+
+
Parameters:
+
    +
  • WorkQueue (queue) – A WorkQueue to which RPC calls will be added

  • +
  • str (prefix) – PV name prefix used by RPC methods

  • +
  • target – The object which has the RPC calls

  • +
+
+
+
+ +
+
+class p4p.rpc.RemoteError
+

Thrown with an error message which has been sent by a server to its remote client

+
+ +
+
+class p4p.rpc.WorkQueue(maxsize=5)[source]
+

A threaded work queue.

+
+
+handle()[source]
+

Process queued work until interrupt() is called

+
+ +
+
+interrupt()[source]
+

Break one call to handle()

+

eg. Call N times to break N threads.

+

This call blocks if the queue is full.

+
+ +
+ +
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/search.html b/search.html new file mode 100644 index 00000000..e0b7afd3 --- /dev/null +++ b/search.html @@ -0,0 +1,134 @@ + + + + + + + + Search — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Search

+ + + + +

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

+ + +
+ + + +
+ + + +
+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/searchindex.js b/searchindex.js new file mode 100644 index 00000000..b8776b55 --- /dev/null +++ b/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({"docnames": ["building", "client", "gw", "index", "internal", "nt", "overview", "rpc", "server", "starting", "values"], "filenames": ["building.rst", "client.rst", "gw.rst", "index.rst", "internal.rst", "nt.rst", "overview.rst", "rpc.rst", "server.rst", "starting.rst", "values.rst"], "titles": ["Building", "Client API", "PVA Gateway", "PVAccess for Python (P4P)", "Internal API", "Common Types", "Overview", "RPC Server Helpers", "Server API", "Quick Start", "Working with Value and Type"], "terms": {"releas": 0, "tar": 0, "avail": [0, 1, 2, 5, 8], "from": [0, 1, 3, 4, 5, 6, 7, 8, 9, 10], "http": [0, 3, 5, 6], "github": [0, 3], "com": [0, 3], "base": [0, 2, 3, 4, 5, 7, 8, 10], "p4p": [0, 1, 4, 5, 6, 7, 8, 9, 10], "The": [0, 1, 2, 3, 4, 5, 6, 7, 8, 10], "requir": [0, 1, 2, 7], "2": [0, 1, 2, 3, 5, 7, 10], "7": [0, 3, 7], "3": [0, 2, 3, 5, 7], "5": [0, 1, 2, 3, 7, 9, 10], "6": [0, 1, 3, 9], "asyncio": [0, 1, 3], "support": [0, 2, 3, 6, 8, 10], "numpi": [0, 5], "1": [0, 1, 2, 4, 5, 7, 8, 9], "cython": 0, "0": [0, 1, 2, 4, 5, 7, 8, 9, 10], "25": 0, "nose2": [0, 3, 9], "option": [0, 1, 2, 3, 4, 5, 9, 10], "recommend": [0, 2, 3, 9], "run": [0, 1, 2, 3, 4, 6, 7, 9], "current": [0, 1, 2, 4, 5, 6, 7, 8, 10], "4": [0, 1, 2, 5, 10], "14": [0, 2, 7], "12": 0, "pvx": [0, 2, 10], "prior": 0, "pvdatacpp": 0, "pvaccesscpp": [0, 7], "can": [0, 1, 2, 3, 4, 5, 6, 7, 8, 10], "built": [0, 10], "instal": [0, 2, 3, 9], "one": [0, 1, 2, 5, 7, 8, 9, 10], "two": [0, 2, 5, 7, 8, 9, 10], "wai": [0, 2, 10], "As": [0, 1, 4, 8, 10], "prefer": 0, "manag": [0, 2, 8], "pip": [0, 3, 9], "an": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "cothread": [0, 1], "need": [0, 2, 6, 10], "client": [0, 2, 3, 5, 6, 8, 9], "context": [0, 1, 4, 5, 6, 7, 8, 9], "qtpy": [0, 1], "qt": [0, 3], "process": [0, 1, 2, 3, 4, 6, 7, 8], "us": [0, 1, 2, 4, 5, 6, 8, 9, 10], "sourc": [0, 1, 4, 5, 7, 8, 10], "pypi": [0, 3, 9], "org": [0, 3, 9], "ad": [0, 2, 5, 7, 9, 10], "argument": [0, 1, 3, 4, 5, 7, 8, 9], "binari": 0, "prevent": [0, 2, 8], "pre": 0, "except": [0, 1, 4, 7, 8, 10], "m": [0, 2, 3, 8, 9], "p4ptest": [0, 3, 9], "bin": [0, 3, 9], "activ": [0, 1, 2, 3, 7, 9], "u": [0, 2, 3, 9, 10], "onli": [0, 1, 2, 4, 8, 10], "epicscorelib": 0, "pvxslib": 0, "automat": [0, 1, 2, 3, 4, 7, 8, 9, 10], "test": [0, 2, 3, 7, 8, 9, 10], "It": [0, 1, 2, 4, 7], "mai": [0, 1, 2, 4, 5, 6, 7, 8, 10], "necessari": [0, 2, 8, 10], "creat": [0, 1, 2, 3, 4, 5, 7, 8, 10], "includ": [0, 2, 3, 4, 5, 8, 9, 10], "machin": [0, 2], "internet": 0, "access": [0, 3, 4, 6, 8, 10], "ensur": [0, 1, 2, 9], "certain": [0, 1, 2, 4], "verifi": 0, "follow": [0, 1, 2, 4, 5, 8, 9, 10], "recip": 0, "wa": [0, 2, 4, 8], "16": 0, "18": 0, "first": [0, 2, 4, 8, 9, 10], "have": [0, 1, 2, 4, 5, 6, 7, 8, 10], "same": [0, 1, 2, 8, 10], "archetectur": 0, "target": [0, 1, 7], "collect": [0, 8], "file": [0, 3], "mkdir": 0, "tmp": 0, "venv": 0, "cd": 0, "download": 0, "unzip": 0, "whl": 0, "py": [0, 4, 5, 7], "never": [0, 2], "prepenv": 0, "d": [0, 2, 4, 5, 7, 8, 9, 10], "virtualenv_support": 0, "caf": 0, "env": 0, "date": 0, "y": 0, "gz": 0, "deactiv": 0, "now": [0, 7], "move": [0, 2, 10], "Then": 0, "prepar": 0, "xaf": 0, "index": [0, 3, 10], "f": [0, 10], "util": [0, 2, 6, 7], "autom": 0, "thi": [0, 1, 2, 4, 5, 6, 7, 8, 9, 10], "project": 0, "pyutilib": 0, "also": [0, 1, 2, 5, 8, 10], "addit": [0, 1, 2, 5, 6, 7, 8], "host": [0, 2, 9], "extens": [0, 4], "eg": [0, 1, 2, 4, 5, 6, 7, 8, 10], "debian": 0, "linux": [0, 2, 3], "sudo": [0, 2], "apt": 0, "get": [0, 2, 4, 5, 6, 8, 9, 10], "essenti": 0, "python3": 0, "dev": 0, "cython3": 0, "r": 0, "latest": 0, "txt": 0, "replac": [0, 8, 9], "master": 0, "number": [0, 1, 2, 5, 7, 8], "git": 0, "clone": 0, "branch": 0, "set": [0, 1, 2, 4, 5, 6, 8, 10], "locat": 0, "With": [0, 2, 3, 9], "cat": 0, "eof": 0, "configur": [0, 1, 3, 4, 6, 8, 9], "path": [0, 2, 5, 6, 7], "epics_bas": 0, "make": [0, 2, 7, 8], "see": [0, 1, 2, 4, 5, 6, 7, 8], "below": [0, 2, 5, 8, 10], "detail": [0, 3, 6, 7], "By": [0, 1, 2, 9, 10], "default": [0, 1, 2, 4, 5, 6, 7, 8, 9, 10], "found": [0, 2, 9], "system": [0, 2, 3, 5, 6, 9], "search": [0, 2, 3, 8], "To": [0, 2, 7, 10], "explicitli": [0, 5, 10], "specifi": [0, 1, 2, 7, 10], "particular": [0, 6, 10], "distclean": 0, "altern": [0, 1, 4, 8, 9], "full": [0, 2, 4, 7, 8], "interpret": [0, 2], "usr": 0, "For": [0, 7, 8, 9, 10], "conveni": [0, 5, 6, 8], "config_sit": 0, "i": [0, 1, 2, 3, 4, 5, 7, 8, 9, 10], "do": [0, 1, 2, 4, 7, 8], "partial": 0, "clean": 0, "befor": [0, 1, 2, 4, 8], "anoth": [0, 2, 4, 6, 8], "remov": [0, 2, 8], "final": [0, 9], "tree": 0, "python2": 0, "If": [0, 1, 2, 4, 7, 8, 9, 10], "ever": [0, 1, 4], "must": [0, 1, 2, 4, 5, 7, 8, 9], "all": [0, 1, 2, 5, 6, 7, 8, 10], "ar": [0, 1, 2, 4, 5, 6, 7, 8, 9, 10], "present": [0, 6], "thei": [0, 2], "libreadline6": 0, "libncurses5": 0, "perl": 0, "pwd": 0, "c": [0, 3, 4, 8], "nose": 0, "purpos": [0, 2], "sever": [0, 1, 4, 5, 8, 10], "simpl": [0, 2, 8, 10], "command": [0, 3, 6, 8], "line": [0, 3, 4, 8, 9], "tool": [0, 8], "provid": [0, 1, 2, 4, 5, 6, 7, 10], "further": [0, 2, 10], "inform": [0, 2], "pythonpath": 0, "x86_64": 0, "h": [0, 2, 10], "modul": [1, 2, 3, 6, 7, 10], "interact": 1, "multi": [1, 2], "thread": [1, 2, 5, 7, 8, 9], "environ": [1, 4, 8, 9], "most": [1, 2], "method": [1, 2, 4, 5, 6, 7, 8], "block": [1, 2, 7, 8], "call": [1, 2, 4, 5, 6, 7, 8], "until": [1, 2, 7, 8], "return": [1, 2, 4, 5, 7, 8, 10], "error": [1, 2, 4, 7, 8], "occur": [1, 9], "These": [1, 2], "differ": [1, 6, 8], "how": [1, 8], "o": [1, 2, 8], "oper": [1, 2, 4, 6, 7, 8, 10], "perform": [1, 2, 4, 5], "which": [1, 2, 3, 4, 5, 6, 7, 8, 10], "callback": [1, 4, 8], "note": [1, 3, 8], "behav": 1, "other": [1, 2, 5, 7, 8, 10], "some": [1, 2, 5, 8], "respect": [1, 2], "describ": [1, 2, 4, 5, 7, 9, 10], "qtclient": 1, "start": [1, 3, 8], "import": [1, 2, 4, 5, 7, 8, 9, 10], "pva": [1, 3, 4, 5, 6, 7, 9, 10], "ctxt": [1, 5, 7, 9], "network": [1, 2, 3, 6, 10], "taken": [1, 2], "overridden": 1, "pass": [1, 2, 4, 5, 7, 8, 9, 10], "conf": [1, 2, 4, 7, 8, 9], "class": [1, 2, 4, 5, 6, 7, 8, 10], "constructor": [1, 4, 7, 8, 10], "what": [1, 2, 3, 7], "pvaccess": [1, 2, 8], "background": [1, 3], "protocol": [1, 2, 3, 6, 10], "singl": [1, 2, 4, 5, 8, 10], "pv": [1, 3, 4, 5, 7, 8, 9], "list": [1, 2, 4, 5, 7, 8, 10], "v": [1, 2, 5, 7, 10], "name": [1, 4, 5, 6, 7, 8, 9, 10], "A": [1, 2, 4, 5, 6, 7, 8, 10], "b": [1, 5, 7, 8, 10], "valu": [1, 2, 3, 7, 8, 9], "equival": [1, 2, 5, 10], "previou": [1, 2, 7], "field_1": 1, "field_2": 1, "multipl": [1, 2], "field": [1, 2, 4, 5, 8, 10], "subject": [1, 2], "unwrap": [1, 3, 4, 8], "unlik": 1, "doe": [1, 2, 8, 10], "instead": [1, 5, 8], "accept": [1, 2, 5], "function": [1, 2, 5, 8], "each": [1, 2, 4, 5, 8, 10], "new": [1, 2, 4, 5, 8, 9, 10], "def": [1, 4, 7, 8], "cb": 1, "print": [1, 2, 7, 8, 9], "sub": [1, 7, 10], "time": [1, 2, 4, 5, 7, 8, 10], "sleep": 1, "10": [1, 2, 7, 9], "arbitrari": [1, 5, 6, 7, 8, 9], "wait": [1, 4], "close": [1, 2, 4, 6, 8], "subscript": [1, 2, 4, 6], "ha": [1, 2, 4, 7, 10], "end": [1, 2, 9], "worker": [1, 2, 7], "pool": [1, 7, 8], "per": [1, 2], "coroutin": [1, 8], "In": [1, 2, 6, 8, 9], "case": [1, 2, 5, 6, 7, 8], "safe": 1, "yield": [1, 5], "subsequ": [1, 8], "updat": [1, 2, 4, 5, 8], "deliv": [1, 4, 8], "complet": [1, 2, 4, 5, 8, 9], "howev": [1, 2, 5], "server": [1, 2, 3, 5, 6, 9], "helper": [1, 3, 5, 6, 10], "none": [1, 2, 4, 5, 7, 8, 10], "useenv": [1, 4, 7, 8], "true": [1, 2, 4, 5, 7, 8, 10], "paramet": [1, 2, 4, 5, 7, 8, 10], "str": [1, 2, 4, 5, 7, 8, 10], "try": [1, 2, 4, 5], "dict": [1, 2, 4, 5, 7, 8, 10], "depend": [1, 4, 6], "select": [1, 2, 4, 5, 8, 10], "bool": [1, 4, 5, 8, 10], "allow": [1, 2, 4, 8], "int": [1, 5, 7, 9, 10], "size": [1, 2, 8], "maxsiz": [1, 7], "intern": [1, 2, 3], "work": [1, 2, 3, 5, 6, 7, 8, 9], "queue": [1, 7, 8], "unlimit": 1, "nt": [1, 4, 7, 8, 10], "control": [1, 3, 4, 6], "fals": [1, 2, 4, 5, 7, 8, 10], "disabl": [1, 4, 5], "legaci": [1, 2, 4, 5], "workqueu": [1, 7, 8], "through": [1, 2, 6, 7, 8], "dispatch": [1, 7], "timeout": [1, 7, 8], "mean": [1, 2, 6], "kei": [1, 2, 5, 8, 10], "dictionari": [1, 4, 5, 7, 8, 10], "overrid": [1, 8], "variabl": [1, 4, 6, 8, 9], "ignor": [1, 2, 8], "understand": 1, "epics_pva_addr_list": [1, 9], "epics_pva_auto_addr_list": 1, "epics_pva_server_port": 1, "epics_pva_broadcast_port": 1, "string": [1, 2, 4, 5, 6, 7, 8, 9, 10], "forc": [1, 2, 8], "channel": [1, 2, 4, 5, 6, 8], "cancel": [1, 4, 8], "request": [1, 2, 4, 6, 7, 8], "throw": [1, 7, 10], "fetch": [1, 4, 6], "qualifi": [1, 4], "float": [1, 5, 7, 8, 10], "second": [1, 2, 5, 7, 9], "when": [1, 2, 4, 6, 8, 10], "invok": [1, 8], "write": [1, 2, 4], "modifi": [1, 2, 6, 8], "remot": [1, 2, 4, 6, 7, 8], "passiv": 1, "whether": [1, 2, 4, 7, 8, 10], "builder": [1, 4], "callabl": [1, 4, 5, 8, 10], "initi": [1, 4, 5, 8, 10], "recent": [1, 4], "ntenum": [1, 4], "find": [1, 4], "enumer": [1, 4], "omit": [1, 2, 4, 8], "": [1, 2, 4, 5, 7, 8, 10], "coerc": [1, 10], "type": [1, 2, 3, 6, 7, 8], "possibl": [1, 2, 4, 8], "rais": [1, 7], "unless": 1, "assum": 1, "plain": [1, 5], "attempt": [1, 2, 4, 5, 8, 10], "made": [1, 2, 5, 6, 7, 10], "store": [1, 2, 4, 5, 8, 10], "notify_disconnect": [1, 4], "instanc": [1, 2, 5, 7, 8, 9], "specif": [1, 2, 5, 6, 7, 9, 10], "disconnect": [1, 2, 4, 8], "remoteerror": [1, 4, 7], "either": [1, 2, 10], "procedur": [1, 4, 7, 8], "add": [1, 2, 7, 8], "static": [1, 5], "arg": [1, 5], "kw": [1, 4, 5, 7, 8], "clear": [1, 2, 4, 10], "cach": [1, 4, 8], "unus": [1, 2, 4], "implictli": [1, 4], "entir": [1, 4, 10], "entri": [1, 2, 4, 8, 10], "set_debug": 1, "lvl": 1, "msg": [1, 2, 8], "becom": [1, 8], "disconect": 1, "thrown": [1, 4, 7], "messag": [1, 2, 4, 7, 8, 10], "been": [1, 4, 7, 10], "sent": [1, 2, 4, 7], "its": [1, 2, 4, 7, 8, 10], "finish": 1, "special": [1, 2, 5], "receiv": [1, 2, 4, 6, 7, 8], "timeouterror": 1, "expir": [1, 2], "exist": [1, 8, 10], "bring": 1, "result": [1, 5, 6, 7, 8], "event": [1, 2, 4, 8], "loop": [1, 2, 4, 8], "done": [1, 4, 8], "nativ": 1, "signal": [1, 8], "slot": 1, "mechan": [1, 6], "packag": [1, 3], "express": [1, 2], "extras_requir": 1, "upon": 1, "accordingli": 1, "minim": 1, "share": [1, 2, 4, 8, 9], "desir": [1, 2, 8], "maximum": 1, "rate": [1, 2], "limit": [1, 2, 8, 10], "limithz": 1, "convien": [1, 4], "object": [1, 2, 4, 5, 7, 8], "caller": [1, 7], "kept": 1, "extend": 1, "so": [1, 2, 6, 8], "implicitli": [1, 8], "progress": [1, 2, 8], "main": [2, 6], "up": 2, "mygw": 2, "systemd": 2, "gener": [2, 5, 7], "python": [2, 4, 5, 8, 9, 10], "config": [2, 8], "etc": 2, "pvagw": [2, 3], "unit": 2, "servic": 2, "systemctl": 2, "daemon": 2, "reload": 2, "check": [2, 9], "correctli": 2, "boot": 2, "enabl": [2, 7], "epic": [2, 3, 5, 7], "softwar": 2, "ioc": 2, "isol": [2, 7, 8], "reduc": 2, "resourc": 2, "load": 2, "face": 2, "side": [2, 6], "restrict": [2, 8], "proxi": [2, 7], "sit": 2, "between": [2, 4, 5, 8], "group": [2, 8], "connect": [2, 4, 8], "without": [2, 4, 8], "n": [2, 5, 7], "tcp": 2, "socket": 2, "subscrib": [2, 6, 8], "send": [2, 5, 7], "data": [2, 3, 4, 5, 6, 10], "de": 2, "duplic": [2, 8], "repeat": 2, "shield": 2, "potenti": 2, "larg": [2, 3, 6], "defin": [2, 5, 8, 10], "subnet": [2, 6, 8], "common": [2, 3, 4, 6, 8, 10], "scenario": 2, "comput": 2, "nic": 2, "thu": 2, "broadcast": [2, 6, 9], "domain": [2, 6], "address": [2, 6, 8, 9], "192": [2, 9], "168": [2, 9], "24": [2, 9], "home": 2, "intent": 2, "statement": 2, "explain": 2, "style": [2, 7], "comment": 2, "version": 2, "client192": 2, "addrlist": 2, "255": [2, 9], "autoaddrlist": 2, "server10": 2, "statusprefix": 2, "st": 2, "suggest": [2, 10], "server192": 2, "section": [2, 4], "member": [2, 10], "attach": 2, "act": 2, "indic": [2, 4, 7, 8, 9], "part": [2, 3, 7, 8], "clients192": 2, "listen": [2, 8], "local": [2, 3, 6, 8, 9], "pvget": 2, "pvput": 2, "beacon": 2, "packet": 2, "optim": 2, "suffix": 2, "prepend": 2, "site": 2, "should": [2, 5, 8, 9], "give": [2, 10], "uniqu": [2, 6, 7, 8], "shown": [2, 4], "Its": 2, "empti": [2, 4, 10], "mention": 2, "abov": 2, "those": [2, 4, 8, 10], "itself": 2, "avoid": [2, 8], "more": [2, 4, 5, 6, 7, 8, 9, 10], "complex": 2, "situat": [2, 8], "involv": [2, 9], "setup": 2, "judg": 2, "care": 2, "form": [2, 4, 5, 8], "ignoreaddr": 2, "usag": [2, 3], "ban": 2, "debug": [2, 7], "t": [2, 5, 9, 10], "verbos": 2, "basic": 2, "level": [2, 5], "20": [2, 7], "json": 2, "dictconfig": 2, "format": [2, 5, 7, 10], "extrem": 2, "low": 2, "read": [2, 6], "valid": [2, 8], "exit": 2, "w": [2, 5], "stdout": 2, "readonli": 2, "theclient": 2, "bcastport": 2, "5076": [2, 9], "theserv": 2, "serverport": 2, "5075": 2, "getholdoff": 2, "somefilenam": 2, "refer": [2, 3, 6], "here": [2, 8, 10], "scheme": [2, 5], "boolean": 2, "flag": 2, "global": [2, 6, 7], "reject": 2, "rpc": [2, 3, 4, 5, 6, 8, 10], "take": [2, 7, 10], "preced": [2, 7, 10], "over": [2, 10], "ani": [2, 4, 5, 6, 7, 8, 10], "within": [2, 8, 10], "channelprovid": 2, "unicast": [2, 9], "popul": 2, "caution": 2, "udp": 2, "port": [2, 8], "zero": [2, 9, 10], "bind": 2, "explicit": [2, 4, 10], "random": 2, "bound": 2, "well": [2, 3, 10], "greater": [2, 10], "than": [2, 8, 10], "hold": [2, 5, 10], "off": 2, "after": [2, 4, 8], "issu": [2, 3, 4, 8], "delai": 2, "concurr": [2, 3, 7], "combin": [2, 5, 6], "text": 2, "prefix": [2, 7, 10], "construct": [2, 7, 8, 10], "commun": 2, "report": 2, "overal": 2, "regardless": 2, "typic": 2, "delimit": 2, "your": 2, "convent": 2, "decis": 2, "rel": 2, "relat": [2, 3, 4, 6, 7], "directori": 2, "contain": [2, 8, 10], "acf_client": 2, "unambigu": 2, "inp": 2, "condit": [2, 5, 7], "aggreg": 2, "across": 2, "astest": 2, "pvcall": [2, 7], "user": [2, 7], "xx": 2, "peer": [2, 8], "12345": 2, "role": [2, 8], "yy": 2, "ref": [2, 4], "tabl": [2, 5, 10], "count": 2, "detect": 2, "leak": 2, "while": [2, 4, 6, 8], "troubleshoot": [2, 3], "descript": [2, 5], "bandwidth": 2, "downstream": 2, "respons": [2, 4, 6], "upstream": 2, "bypv": 2, "byhost": 2, "rx": 2, "tx": 2, "transmit": 2, "perspect": 2, "sinc": [2, 5], "often": 2, "small": [2, 3], "sort": 2, "highest": 2, "lowest": 2, "origin": 2, "abl": 2, "record": 2, "associ": [2, 4, 5, 7, 8], "destin": 2, "consol": 2, "devic": 2, "aid": 2, "develop": [2, 4], "encount": 2, "stop": [2, 8], "One": [2, 7, 9], "logger": 2, "interest": [2, 10], "audit": 2, "aris": 2, "info": [2, 9], "wors": 2, "warn": 2, "versu": 2, "instruct": 2, "maintain": [2, 8, 10], "daili": 2, "subdirectori": 2, "bl3": 2, "midnight": 2, "keep": 2, "dai": 2, "fix": [2, 7, 8], "width": [2, 10], "column": [2, 5], "sequenc": 2, "like": [2, 5, 9, 10], "15": [2, 9], "4d": 2, "similar": [2, 5], "printf": 2, "disable_existing_logg": 2, "formatt": 2, "fileformat": 2, "asctim": 2, "lineno": 2, "levelnam": 2, "consoleformat": 2, "handler": [2, 4], "filemessag": 2, "timedrotatingfilehandl": 2, "filenam": 2, "dmz": 2, "interv": 2, "backupcount": 2, "consolemessag": 2, "streamhandl": 2, "stream": 2, "ext": 2, "sy": 2, "propag": 2, "appli": [2, 7, 8, 9], "individu": 2, "simplest": 2, "direct": [2, 10], "logic": 2, "both": [2, 5, 8, 9, 10], "monitor": [2, 4, 5, 6, 8, 9, 10], "polici": [2, 3], "being": [2, 4, 6, 8], "permit": 2, "chang": [2, 4, 5, 6, 8], "granular": 2, "look": [2, 9], "deni": 2, "proce": 2, "alia": [2, 10], "asg": 2, "alwai": [2, 5, 7], "appropri": [2, 4, 8], "permiss": 2, "grant": 2, "secur": 2, "asl": 2, "mostli": 2, "compat": 2, "consist": [2, 10], "match": 2, "strict": 2, "lexic": 2, "order": [2, 5, 8], "blank": 2, "evalu": [2, 7, 9], "primarili": 2, "backward": 2, "Not": 2, "regexp": 2, "regular": 2, "hostname_or_ip": 2, "accompani": 2, "asl_0_or_1": 2, "pattern": 2, "translat": [2, 5, 10], "real": 2, "compar": 2, "consid": [2, 4, 9, 10], "last": [2, 4, 8, 9], "effect": [2, 5, 8, 10], "accl": 2, "cryo": 2, "misconfig": 2, "rf": 2, "estop": 2, "would": [2, 6, 7, 10], "fpwr": 2, "arc": 2, "cnt": 2, "becaus": 2, "ident": [2, 8], "build": [2, 3, 5, 10], "overlap": 2, "therefor": 2, "hidden": 2, "unknown": 2, "incontrol": 2, "physic": [2, 3], "mcf": 2, "shorthand": [2, 10], "uncach": 2, "bypass": 2, "dedupl": 2, "pvrequest": [2, 7, 8], "_option": 2, "numer": 2, "resolv": [2, 8], "onc": 2, "startup": 2, "map": [2, 5, 10], "visibl": 2, "restart": [2, 9], "weakli": 2, "authent": 2, "identif": 2, "usernam": 2, "nsswitch": 2, "appear": [2, 5, 8], "root": 2, "admin": 2, "And": [2, 8, 9], "identifi": [2, 6, 10], "unix": 2, "membership": [2, 8], "item": [2, 4, 10], "asitem": 2, "z": [2, 10], "pvname": [2, 7, 8], "priv": 2, "rule_cond": 2, "trap": 2, "notrapwrit": 2, "cond": 2, "calc": 2, "expr": 2, "begin": [2, 4, 6, 7], "topologi": 2, "question": 2, "place": [2, 8], "boundari": 2, "complic": [2, 6], "mani": [2, 6, 8], "pair": 2, "cross": 2, "link": 2, "bi": 2, "meaning": 2, "summari": 2, "known": [2, 4, 8], "impli": 2, "hybrid": [2, 6], "code": [2, 5, 7, 8, 10], "slow": 2, "extern": 2, "api": [2, 3, 6, 9], "stabl": [2, 4], "public": [2, 4], "document": 2, "testchannel": [2, 8], "reconnect": [2, 8], "three": [2, 8, 9, 10], "criteria": 2, "manner": [2, 10], "pva2pva": 2, "cagatewai": 2, "definit": [2, 3, 5, 6], "could": [2, 10], "execut": [2, 3], "flow": 2, "clientprovid": 2, "referenc": 2, "accord": 2, "_gw": 2, "providerhandl": [2, 8], "deal": 2, "possibli": 2, "claim": [2, 8], "banhost": 2, "banpv": 2, "banhostpv": 2, "usnam": 2, "byte": [2, 10], "sweep": 2, "period": 2, "forceban": 2, "preemptiv": 2, "clearban": 2, "cachepeek": 2, "stat": 2, "statist": 2, "variou": [2, 4], "tupl": [2, 5, 7, 8, 10], "optx": 2, "oprx": 2, "trtx": 2, "trrx": 2, "infobas": 2, "account": [2, 8, 10], "createop": 2, "handl": [2, 5, 7, 8], "creation": [2, 8], "given": [2, 6, 7, 8, 10], "self": [2, 4, 7, 8, 10], "hook": 2, "phase": 2, "later": [2, 4, 8], "makechannel": [2, 8], "futur": 2, "op": [2, 4, 8], "track": 2, "Or": [2, 8], "due": 2, "continu": 2, "natur": 2, "re": [2, 3, 8], "inabl": 2, "stage": 2, "treat": 2, "hard": 2, "failur": 2, "reset": 2, "step": [2, 10], "ongo": 2, "wrapper": [3, 5, 6, 10], "around": 3, "aka": [3, 4, 8], "experiment": 3, "industri": 3, "ecosystem": 3, "scale": 3, "distribut": 3, "acqisit": 3, "sytem": 3, "anl": [3, 6], "gov": [3, 6], "gatewai": 3, "enforc": 3, "osx": 3, "window": 3, "point": [3, 5, 7, 8], "virtualenv": [3, 9], "vc": 3, "doc": 3, "io": 3, "content": 3, "quick": 3, "overview": 3, "sharedpv": [3, 4, 5, 10], "exampl": [3, 6, 10], "ownership": 3, "statu": [3, 5, 10], "log": [3, 7], "model": [3, 8], "pvlist": 3, "acf": 3, "rule": [3, 10], "applic": [3, 4, 8], "implement": [3, 4, 8], "page": 3, "intend": [4, 6], "help": [4, 7], "notic": 4, "diagram": 4, "blue": 4, "oval": 4, "black": 4, "box": 4, "red": 4, "shared_ptr": 4, "green": 4, "weak_ptr": 4, "pyobject": 4, "dash": 4, "break": [4, 7], "notif": [4, 6], "abort": 4, "fifo": 4, "put": [4, 5, 6, 8, 9, 10], "success": [4, 8, 9], "fill": 4, "interfac": [4, 9], "poll": [4, 6], "pop": 4, "again": 4, "forthcom": 4, "normal": 4, "skeleton": [4, 8], "onfirstconnect": [4, 8], "onlastdisconnect": [4, 8], "serveroper": 4, "wrap": [4, 8, 10], "state": [4, 5, 6, 8], "open": [4, 5, 6, 8, 9], "decor": [4, 7, 8], "syntax": [4, 8], "meth": 4, "ntscalar": [4, 5, 7, 8], "transform": [4, 5, 8], "post": [4, 5, 6, 8, 10], "myhandl": [4, 8], "onput": [4, 8], "convienc": 4, "mark": [4, 7, 8, 10], "begun": [4, 8], "began": [4, 8], "keyword": [4, 5, 7, 8], "forward": [4, 8], "timestamp": [4, 5, 7, 8], "standard": [5, 6], "pvdata": 5, "sourceforg": 5, "net": 5, "alpha": 5, "normativetyp": 5, "html": 5, "sure": 5, "reason": 5, "top": 5, "structur": [5, 6, 10], "id": [5, 10], "conform": 5, "wrapperinterfac": 5, "pv1": 5, "expect": 5, "pv2": 5, "displai": 5, "my": [5, 9], "ntndarrai": 5, "defaultnt": 5, "copi": [5, 10], "classmethod": 5, "buildtyp": [5, 7], "__init__": [5, 8], "instanti": 5, "dure": [5, 10], "assign": 5, "where": [5, 7, 8, 10], "valtyp": 5, "scalar": [5, 8, 10], "arrai": [5, 10], "meta": 5, "stype": 5, "doubl": [5, 7, 8, 10], "assert": [5, 10], "isinst": 5, "vector": 5, "augment": 5, "ntwrappercommon": 5, "ndarrai": [5, 10], "agument": 5, "attribut": 5, "repres": [5, 6], "jan": 5, "1970": 5, "utc": 5, "raw_stamp": 5, "nanosecond": 5, "integ": [5, 8, 10], "rang": 5, "raw": 5, "underli": [5, 10], "extra": [5, 8], "non": [5, 8, 9, 10], "valuealarm": 5, "alarm": [5, 7, 10], "deprec": [5, 10], "pack": 5, "unpack": 5, "represent": [5, 10], "dimension": 5, "nttabl": 5, "columna": 5, "ai": [5, 10], "columnb": 5, "cola": 5, "iter": [5, 10], "42": [5, 10], "43": [5, 10], "ordereddict": [5, 10], "nturi": [5, 7], "queri": [5, 7, 8], "pvd": 5, "arg_a": 5, "arg_two": 5, "author": [5, 7], "ntmultichannel": 5, "ntfloat": 5, "x": [5, 10], "ntint": 5, "ntstr": 5, "ntnumericarrai": 5, "ntstringarrai": 5, "attrib": 5, "ntattribut": 5, "discard": 5, "publish": 6, "ca": 6, "along": [6, 7], "supersed": 6, "four": 6, "world": 6, "idea": 6, "compos": 6, "million": 6, "facil": 6, "via": 6, "hardwar": 6, "measur": 6, "temperatur": 6, "sensor": 6, "electro": 6, "relai": 6, "perhap": 6, "toggl": 6, "precis": [6, 10], "convention": 6, "relationship": 6, "url": 6, "hierarch": 6, "hostnam": 6, "namespac": 6, "ip": 6, "though": 6, "abil": 6, "goe": 6, "strongli": [6, 10], "quickrpcserv": 7, "summer": 7, "lh": 7, "rh": 7, "adder": 7, "turn": [7, 10], "basicconfig": 7, "At": 7, "2018": [7, 9], "30": 7, "19": [7, 9], "49": 7, "34": 7, "834": 7, "eget": 7, "alarm_t": 7, "no_alarm": 7, "no_statu": 7, "time_t": 7, "2017": 7, "05": 7, "20t08": 7, "31": 7, "917": 7, "assist": 7, "encod": 7, "rpcproxi": 7, "rpccall": 7, "myproxi": 7, "sadd": 7, "contructor": 7, "illustr": 7, "actual": [7, 8, 10], "schema": 7, "rtype": 7, "export": 7, "flost": 7, "spec": 7, "func": 7, "rpcall": 7, "tst": 7, "rpcproxybas": 7, "sequenti": 7, "pend": [7, 8], "queu": 7, "nturidispatch": 7, "al": 7, "installprovid": [7, 8], "cli": [7, 8, 9], "interrupt": 7, "staticprovid": 8, "mix": 8, "mailbox": 8, "just": 8, "forev": 8, "demo": 8, "keyboardinterrupt": 8, "shell": 8, "inspect": 8, "fail": 8, "oop": 8, "epics_pvas_": 8, "suitabl": 8, "localhost": [8, 9], "randomli": 8, "chosen": 8, "determin": 8, "serv": 8, "someth": 8, "els": 8, "cf": [8, 10], "ambigu": 8, "lower": 8, "clearli": 8, "choos": 8, "ahead": 8, "show": [8, 9, 10], "fact": 8, "better": 8, "fit": 8, "dynhandl": 8, "notyet": 8, "blah": 8, "fall": 8, "next": 8, "nocach": 8, "permen": 8, "disclaim": 8, "temporarili": 8, "neg": 8, "defeat": 8, "behavour": 8, "lazi": 8, "src": 8, "unsuccess": 8, "oncancel": 8, "lost": 8, "There": 8, "distinct": 8, "carri": 8, "out": 8, "destroi": 8, "sync": 8, "perman": 8, "closur": 8, "otherwis": 8, "destori": 8, "succeed": 8, "__first__": 8, "outsid": 8, "removeprovid": 8, "dispos": 9, "termin": [9, 10], "feel": 9, "free": 9, "everywher": 9, "mon": 9, "jul": 9, "9": 9, "01": 9, "0l": 9, "third": 9, "preceed": 9, "didn": 9, "problem": 9, "09": 9, "27t17": 9, "00": 9, "44": 9, "164": 9, "65": 9, "210": 9, "were": 9, "discov": 9, "firewal": 9, "least": 9, "beyond": 9, "scope": 9, "correspond": 10, "conceptu": 10, "struct": 10, "concret": 10, "bit": 10, "mask": 10, "subset": 10, "transfer": 10, "sign": 10, "32": 10, "111": 10, "invalid": 10, "newli": 10, "asset": 10, "unmark": 10, "unicod": 10, "s8": 10, "u8": 10, "s16": 10, "u16": 10, "i32": 10, "u32": 10, "l": 10, "i64": 10, "u64": 10, "f32": 10, "f64": 10, "discrimin": 10, "nest": 10, "fulli": 10, "ival": 10, "sval": 10, "hello": 10, "bewar": 10, "still": 10, "surpris": 10, "action": 10, "long": 10, "64": 10, "infer": 10, "val": 10, "previous": 10, "magic": 10, "instanci": 10, "unsign": 10, "tolist": 10, "todict": 10, "tostr": 10, "truncat": 10, "length": 10, "charactor": 10, "getid": 10, "fld": 10, "doesn": 10, "selector": 10, "__getattr__": 10, "__setattr__": 10, "__getitem__": 10, "__setitem__": 10, "parent": 10, "child": 10, "changedset": 10, "expand": 10, "leaf": 10, "fake": 10, "transmiss": 10, "redund": 10, "bitset": 10, "whole": 10, "compress": 10, "anyth": 10, "intersect": 10, "label": 10, "amend": 10, "aspi": 10, "__iter__": 10, "familiar": 10, "typedef": 10}, "objects": {"": [[10, 0, 0, "-", "p4p"]], "p4p": [[10, 1, 1, "", "Type"], [10, 1, 1, "", "Value"], [2, 0, 0, "-", "_gw"]], "p4p.Type": [[10, 2, 1, "", "__getattr__"], [10, 2, 1, "", "__iter__"], [10, 2, 1, "", "aspy"], [10, 2, 1, "", "getID"], [10, 2, 1, "", "has"], [10, 2, 1, "", "items"], [10, 2, 1, "", "keys"], [10, 2, 1, "", "values"]], "p4p.Value": [[10, 2, 1, "", "__getattr__"], [10, 2, 1, "", "__getitem__"], [10, 2, 1, "", "__setattr__"], [10, 2, 1, "", "__setitem__"], [10, 2, 1, "", "asSet"], [10, 2, 1, "", "changed"], [10, 2, 1, "", "changedSet"], [10, 2, 1, "", "get"], [10, 2, 1, "", "getID"], [10, 2, 1, "", "has"], [10, 2, 1, "", "items"], [10, 2, 1, "", "mark"], [10, 2, 1, "", "select"], [10, 2, 1, "", "todict"], [10, 2, 1, "", "tolist"], [10, 2, 1, "", "tostr"], [10, 2, 1, "", "type"], [10, 2, 1, "", "unmark"]], "p4p._gw": [[2, 1, 1, "", "Channel"], [2, 1, 1, "", "CreateOp"], [2, 1, 1, "", "InfoBase"], [2, 1, 1, "", "Provider"], [2, 1, 1, "", "ProviderHandler"]], "p4p._gw.Channel": [[2, 2, 1, "", "access"], [2, 3, 1, "", "expired"], [2, 3, 1, "", "name"]], "p4p._gw.CreateOp": [[2, 2, 1, "", "create"], [2, 3, 1, "", "name"]], "p4p._gw.InfoBase": [[2, 3, 1, "", "account"], [2, 3, 1, "", "peer"], [2, 3, 1, "", "roles"]], "p4p._gw.Provider": [[2, 3, 1, "", "BanHost"], [2, 3, 1, "", "BanHostPV"], [2, 3, 1, "", "BanPV"], [2, 3, 1, "", "Claim"], [2, 3, 1, "", "Ignore"], [2, 2, 1, "", "cachePeek"], [2, 2, 1, "", "clearBan"], [2, 2, 1, "", "forceBan"], [2, 2, 1, "", "report"], [2, 2, 1, "", "stats"], [2, 2, 1, "", "sweep"], [2, 2, 1, "", "testChannel"]], "p4p._gw.ProviderHandler": [[2, 2, 1, "", "audit"], [2, 2, 1, "", "makeChannel"], [2, 2, 1, "", "testChannel"]], "p4p.client": [[4, 0, 0, "-", "raw"], [1, 0, 0, "-", "thread"]], "p4p.client.raw": [[4, 1, 1, "", "Context"], [4, 4, 1, "", "RemoteError"], [4, 1, 1, "", "Subscription"]], "p4p.client.raw.Context": [[4, 2, 1, "", "disconnect"], [4, 2, 1, "", "get"], [4, 2, 1, "", "monitor"], [4, 2, 1, "", "put"], [4, 2, 1, "", "rpc"]], "p4p.client.thread": [[1, 1, 1, "", "Cancelled"], [1, 1, 1, "", "Context"], [1, 1, 1, "", "Disconnected"], [1, 1, 1, "", "Finished"], [1, 1, 1, "", "RemoteError"], [1, 1, 1, "", "Subscription"], [1, 1, 1, "", "TimeoutError"]], "p4p.client.thread.Context": [[1, 2, 1, "", "close"], [1, 2, 1, "", "disconnect"], [1, 2, 1, "", "get"], [1, 2, 1, "", "monitor"], [1, 3, 1, "", "name"], [1, 2, 1, "", "providers"], [1, 2, 1, "", "put"], [1, 2, 1, "", "rpc"], [1, 2, 1, "", "set_debug"]], "p4p.client.thread.Subscription": [[1, 2, 1, "", "close"]], "p4p.nt": [[5, 1, 1, "", "NTMultiChannel"], [5, 1, 1, "", "NTNDArray"], [5, 1, 1, "", "NTScalar"], [5, 1, 1, "", "NTTable"], [5, 1, 1, "", "NTURI"], [5, 1, 1, "", "WrapperInterface"], [5, 5, 1, "", "defaultNT"]], "p4p.nt.NTMultiChannel": [[5, 2, 1, "", "buildType"]], "p4p.nt.NTNDArray": [[5, 2, 1, "", "assign"], [5, 2, 1, "", "buildType"], [5, 2, 1, "", "unwrap"], [5, 2, 1, "", "wrap"]], "p4p.nt.NTScalar": [[5, 2, 1, "", "assign"], [5, 2, 1, "", "buildType"], [5, 2, 1, "", "unwrap"], [5, 2, 1, "", "wrap"]], "p4p.nt.NTTable": [[5, 2, 1, "", "buildType"], [5, 2, 1, "", "unwrap"], [5, 2, 1, "", "wrap"]], "p4p.nt.NTURI": [[5, 2, 1, "", "buildType"], [5, 2, 1, "", "wrap"]], "p4p.nt.WrapperInterface": [[5, 2, 1, "", "__init__"], [5, 2, 1, "", "assign"], [5, 2, 1, "", "buildtype"], [5, 2, 1, "", "unwrap"], [5, 2, 1, "", "wrap"]], "p4p.nt.ndarray": [[5, 1, 1, "", "ntndarray"]], "p4p.nt.scalar": [[5, 1, 1, "", "ntfloat"], [5, 1, 1, "", "ntint"], [5, 1, 1, "", "ntnumericarray"], [5, 1, 1, "", "ntstr"], [5, 1, 1, "", "ntstringarray"]], "p4p.rpc": [[7, 1, 1, "", "NTURIDispatcher"], [7, 1, 1, "", "RPCProxyBase"], [7, 1, 1, "", "RemoteError"], [7, 1, 1, "", "WorkQueue"], [7, 5, 1, "", "quickRPCServer"], [7, 5, 1, "", "rpc"], [7, 5, 1, "", "rpccall"], [7, 5, 1, "", "rpcproxy"]], "p4p.rpc.RPCProxyBase": [[7, 3, 1, "", "authority"], [7, 3, 1, "", "context"], [7, 3, 1, "", "throw"], [7, 3, 1, "", "timeout"]], "p4p.rpc.WorkQueue": [[7, 2, 1, "", "handle"], [7, 2, 1, "", "interrupt"]], "p4p.server": [[8, 1, 1, "", "DynamicProvider"], [8, 1, 1, "", "ProviderHandler"], [8, 1, 1, "", "Server"], [8, 1, 1, "", "ServerOperation"], [8, 1, 1, "", "StaticProvider"], [8, 5, 1, "", "installProvider"], [4, 0, 0, "-", "raw"], [8, 5, 1, "", "removeProvider"]], "p4p.server.DynamicProvider": [[8, 3, 1, "", "NotYet"]], "p4p.server.ProviderHandler": [[8, 2, 1, "", "testChannel"]], "p4p.server.Server": [[8, 2, 1, "", "conf"], [8, 2, 1, "", "stop"]], "p4p.server.ServerOperation": [[8, 2, 1, "", "account"], [8, 2, 1, "", "done"], [8, 2, 1, "", "name"], [8, 2, 1, "", "onCancel"], [8, 2, 1, "", "peer"], [8, 2, 1, "", "pvRequest"], [8, 2, 1, "", "roles"], [8, 2, 1, "", "value"]], "p4p.server.StaticProvider": [[8, 2, 1, "", "add"], [8, 2, 1, "", "close"], [8, 2, 1, "", "keys"], [8, 2, 1, "", "remove"]], "p4p.server.asyncio": [[8, 1, 1, "", "SharedPV"]], "p4p.server.cothread": [[8, 1, 1, "", "SharedPV"]], "p4p.server.raw": [[4, 1, 1, "", "Handler"], [4, 1, 1, "", "SharedPV"]], "p4p.server.raw.Handler": [[4, 2, 1, "", "onFirstConnect"], [4, 2, 1, "", "onLastDisconnect"], [4, 2, 1, "", "put"], [4, 2, 1, "", "rpc"]], "p4p.server.raw.SharedPV": [[4, 2, 1, "", "open"], [4, 2, 1, "", "post"]], "p4p.server.thread": [[8, 1, 1, "", "Handler"], [8, 1, 1, "", "SharedPV"]], "p4p.server.thread.Handler": [[8, 2, 1, "", "onFirstConnect"], [8, 2, 1, "", "onLastDisconnect"], [8, 2, 1, "", "put"], [8, 2, 1, "", "rpc"]], "p4p.server.thread.SharedPV": [[8, 2, 1, "", "close"], [8, 2, 1, "", "current"], [8, 2, 1, "", "open"], [8, 2, 1, "", "post"]]}, "objtypes": {"0": "py:module", "1": "py:class", "2": "py:method", "3": "py:attribute", "4": "py:exception", "5": "py:function"}, "objnames": {"0": ["py", "module", "Python module"], "1": ["py", "class", "Python class"], "2": ["py", "method", "Python method"], "3": ["py", "attribute", "Python attribute"], "4": ["py", "exception", "Python exception"], "5": ["py", "function", "Python function"]}, "titleterms": {"build": 0, "local": 0, "re": 0, "python": [0, 3], "packag": 0, "bootstrap": 0, "virtualenv": 0, "offlin": 0, "epic": [0, 6], "modul": 0, "multipl": 0, "version": 0, "depend": 0, "cli": 0, "unittest": 0, "client": [1, 4, 7], "api": [1, 4, 5, 7, 8, 10], "usag": 1, "get": 1, "put": [1, 2], "monitor": 1, "rpc": [1, 7], "refer": [1, 4, 5, 7, 10], "qt": 1, "pva": [2, 8], "gatewai": 2, "quick": [2, 9], "start": [2, 9], "background": 2, "exampl": [2, 7, 8], "command": 2, "line": 2, "argument": 2, "posit": 2, "name": 2, "configur": 2, "file": 2, "keyword": 2, "statu": 2, "pv": [2, 6], "log": 2, "access": 2, "control": [2, 5], "model": 2, "pvlist": 2, "acf": 2, "rule": 2, "privileg": 2, "hag": 2, "hostnam": 2, "ip": 2, "uag": 2, "credenti": 2, "trapwrit": 2, "syntax": 2, "applic": 2, "note": 2, "differ": 2, "from": 2, "ca": 2, "implement": 2, "detail": 2, "neg": 2, "result": 2, "cach": 2, "p4p": [2, 3], "gw": 2, "frontend": 2, "c": [2, 10], "extens": 2, "interfac": [2, 5, 8], "pvaccess": [3, 6], "indic": 3, "tabl": 3, "intern": 4, "ownership": 4, "type": [4, 5, 10], "valu": [4, 5, 6, 10], "raw": 4, "server": [4, 7, 8], "common": 5, "automat": 5, "unwrap": 5, "un": 5, "wrap": 5, "nt": 5, "overview": 6, "what": 6, "i": 6, "helper": 7, "us": 7, "low": 7, "level": 7, "run": 8, "dynamicprovid": 8, "handler": 8, "serveroper": 8, "sharedpv": 8, "concurr": 8, "option": 8, "asyncio": 8, "cothread": 8, "global": 8, "provid": 8, "registri": 8, "troubleshoot": 9, "network": 9, "issu": 9, "work": 10, "chang": 10, "track": 10, "definit": 10, "assign": 10, "variant": 10, "union": 10, "relat": 10}, "envversion": {"sphinx.domains.c": 2, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 8, "sphinx.domains.index": 1, "sphinx.domains.javascript": 2, "sphinx.domains.math": 2, "sphinx.domains.python": 3, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.viewcode": 1, "sphinx": 57}, "alltitles": {"Building": [[0, "building"]], "Local (re)build as Python package": [[0, "local-re-build-as-python-package"]], "Bootstrap a virtualenv offline": [[0, "bootstrap-a-virtualenv-offline"]], "Build as EPICS Module": [[0, "build-as-epics-module"]], "Multiple Python Versions": [[0, "multiple-python-versions"]], "Building EPICS dependencies": [[0, "building-epics-dependencies"]], "CLI and unittests": [[0, "cli-and-unittests"]], "Client API": [[1, "client-api"]], "Usage": [[1, "usage"]], "Get/Put": [[1, "get-put"]], "Monitor": [[1, "monitor"]], "RPC": [[1, "rpc"]], "API Reference": [[1, "module-p4p.client.thread"], [4, "api-reference"], [5, "api-reference"], [7, "api-reference"], [10, "module-p4p"]], "Qt Client": [[1, "qt-client"]], "PVA Gateway": [[2, "pva-gateway"]], "Quick Start": [[2, "quick-start"], [9, "quick-start"]], "Background": [[2, "background"]], "Example": [[2, "example"], [8, "example"]], "Command Line Arguments": [[2, "command-line-arguments"]], "Positional Arguments": [[2, "Positional Arguments"]], "Named Arguments": [[2, "Named Arguments"]], "Configuration File": [[2, "configuration-file"]], "Configuration File Keywords": [[2, "configuration-file-keywords"]], "Status PVs": [[2, "status-pvs"]], "Log File Configuration": [[2, "log-file-configuration"]], "Access Control Model": [[2, "access-control-model"]], "PVList File": [[2, "pvlist-file"]], "ACF Rules File": [[2, "acf-rules-file"]], "Privileges": [[2, "privileges"]], "HAG Hostnames and IPs": [[2, "hag-hostnames-and-ips"]], "UAG and Credentials": [[2, "uag-and-credentials"]], "TRAPWRITE and Put logging": [[2, "trapwrite-and-put-logging"]], "ACF Syntax": [[2, "acf-syntax"]], "Application Notes": [[2, "application-notes"]], "Differences from CA gateway": [[2, "differences-from-ca-gateway"]], "Implementation Details": [[2, "implementation-details"]], "Negative Results Cache": [[2, "negative-results-cache"]], "p4p.gw Frontend": [[2, "p4p-gw-frontend"]], "C++ Extension": [[2, "c-extension"]], "Interfaces": [[2, "interfaces"]], "PVAccess for Python (P4P)": [[3, "pvaccess-for-python-p4p"]], "Indices and tables": [[3, "indices-and-tables"]], "Internal API": [[4, "internal-api"]], "Ownership": [[4, "ownership"]], "Type and Value": [[4, "type-and-value"]], "Raw client API": [[4, "module-p4p.client.raw"]], "Raw server API": [[4, "module-p4p.server.raw"]], "Common Types": [[5, "common-types"]], "Automatic Value unwrapping": [[5, "automatic-value-unwrapping"]], "Controlling (Un)wrapping": [[5, "controlling-un-wrapping"]], "NT wrap/unwrap interface": [[5, "nt-wrap-unwrap-interface"]], "Overview": [[6, "overview"]], "What is EPICS?": [[6, "what-is-epics"]], "What is PVAccess?": [[6, "what-is-pvaccess"]], "What is a PV?": [[6, "what-is-a-pv"]], "What is a Value?": [[6, "what-is-a-value"]], "RPC Server Helpers": [[7, "rpc-server-helpers"]], "Server Example": [[7, "server-example"]], "Client Example": [[7, "client-example"]], "Using Low Level Client API": [[7, "using-low-level-client-api"]], "Server API": [[8, "server-api"], [8, "id1"]], "Running a PVA Server": [[8, "running-a-pva-server"]], "DynamicProvider Handler Interface": [[8, "dynamicprovider-handler-interface"]], "ServerOperation": [[8, "serveroperation"]], "SharedPV concurrency options": [[8, "sharedpv-concurrency-options"]], "SharedPV API": [[8, "sharedpv-api"]], "SharedPV Handler Interface": [[8, "sharedpv-handler-interface"]], "asyncio or cothread": [[8, "asyncio-or-cothread"]], "Global Provider registry": [[8, "global-provider-registry"]], "Troubleshooting network issues": [[9, "troubleshooting-network-issues"]], "Working with Value and Type": [[10, "working-with-value-and-type"]], "Working with Type and Value": [[10, "working-with-type-and-value"]], "Change tracking": [[10, "change-tracking"]], "Type definitions": [[10, "type-definitions"]], "Assigning variant and union": [[10, "assigning-variant-and-union"]], "Relation to C++ API": [[10, "relation-to-c-api"]]}, "indexentries": {"cancelled (class in p4p.client.thread)": [[1, "p4p.client.thread.Cancelled"]], "context (class in p4p.client.thread)": [[1, "p4p.client.thread.Context"]], "disconnected (class in p4p.client.thread)": [[1, "p4p.client.thread.Disconnected"]], "finished (class in p4p.client.thread)": [[1, "p4p.client.thread.Finished"]], "remoteerror (class in p4p.client.thread)": [[1, "p4p.client.thread.RemoteError"]], "subscription (class in p4p.client.thread)": [[1, "p4p.client.thread.Subscription"]], "timeouterror (class in p4p.client.thread)": [[1, "p4p.client.thread.TimeoutError"]], "close() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.close"]], "close() (p4p.client.thread.subscription method)": [[1, "p4p.client.thread.Subscription.close"]], "disconnect() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.disconnect"]], "get() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.get"]], "module": [[1, "module-p4p.client.thread"], [2, "module-p4p._gw"], [4, "module-p4p.client.raw"], [4, "module-p4p.server.raw"], [10, "module-p4p"]], "monitor() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.monitor"]], "name (p4p.client.thread.context attribute)": [[1, "p4p.client.thread.Context.name"]], "p4p.client.thread": [[1, "module-p4p.client.thread"]], "providers() (p4p.client.thread.context static method)": [[1, "p4p.client.thread.Context.providers"]], "put() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.put"]], "rpc() (p4p.client.thread.context method)": [[1, "p4p.client.thread.Context.rpc"]], "set_debug() (p4p.client.thread.context static method)": [[1, "p4p.client.thread.Context.set_debug"]], "banhost (p4p._gw.provider attribute)": [[2, "p4p._gw.Provider.BanHost"]], "banhostpv (p4p._gw.provider attribute)": [[2, "p4p._gw.Provider.BanHostPV"]], "banpv (p4p._gw.provider attribute)": [[2, "p4p._gw.Provider.BanPV"]], "channel (class in p4p._gw)": [[2, "p4p._gw.Channel"]], "claim (p4p._gw.provider attribute)": [[2, "p4p._gw.Provider.Claim"]], "createop (class in p4p._gw)": [[2, "p4p._gw.CreateOp"]], "ignore (p4p._gw.provider attribute)": [[2, "p4p._gw.Provider.Ignore"]], "infobase (class in p4p._gw)": [[2, "p4p._gw.InfoBase"]], "provider (class in p4p._gw)": [[2, "p4p._gw.Provider"]], "providerhandler (class in p4p._gw)": [[2, "p4p._gw.ProviderHandler"]], "access() (p4p._gw.channel method)": [[2, "p4p._gw.Channel.access"]], "account (p4p._gw.infobase attribute)": [[2, "p4p._gw.InfoBase.account"]], "audit() (p4p._gw.providerhandler method)": [[2, "p4p._gw.ProviderHandler.audit"]], "cachepeek() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.cachePeek"]], "clearban() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.clearBan"]], "create() (p4p._gw.createop method)": [[2, "p4p._gw.CreateOp.create"]], "expired (p4p._gw.channel attribute)": [[2, "p4p._gw.Channel.expired"]], "forceban() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.forceBan"]], "makechannel() (p4p._gw.providerhandler method)": [[2, "p4p._gw.ProviderHandler.makeChannel"]], "name (p4p._gw.channel attribute)": [[2, "p4p._gw.Channel.name"]], "name (p4p._gw.createop attribute)": [[2, "p4p._gw.CreateOp.name"]], "p4p._gw": [[2, "module-p4p._gw"]], "peer (p4p._gw.infobase attribute)": [[2, "p4p._gw.InfoBase.peer"]], "report() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.report"]], "roles (p4p._gw.infobase attribute)": [[2, "p4p._gw.InfoBase.roles"]], "stats() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.stats"]], "sweep() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.sweep"]], "testchannel() (p4p._gw.provider method)": [[2, "p4p._gw.Provider.testChannel"]], "testchannel() (p4p._gw.providerhandler method)": [[2, "p4p._gw.ProviderHandler.testChannel"]], "context (class in p4p.client.raw)": [[4, "p4p.client.raw.Context"]], "handler (class in p4p.server.raw)": [[4, "p4p.server.raw.Handler"]], "remoteerror": [[4, "p4p.client.raw.RemoteError"]], "sharedpv (class in p4p.server.raw)": [[4, "p4p.server.raw.SharedPV"]], "subscription (class in p4p.client.raw)": [[4, "p4p.client.raw.Subscription"]], "disconnect() (p4p.client.raw.context method)": [[4, "p4p.client.raw.Context.disconnect"]], "get() (p4p.client.raw.context method)": [[4, "p4p.client.raw.Context.get"]], "monitor() (p4p.client.raw.context method)": [[4, "p4p.client.raw.Context.monitor"]], "onfirstconnect() (p4p.server.raw.handler method)": [[4, "p4p.server.raw.Handler.onFirstConnect"]], "onlastdisconnect() (p4p.server.raw.handler method)": [[4, "p4p.server.raw.Handler.onLastDisconnect"]], "open() (p4p.server.raw.sharedpv method)": [[4, "p4p.server.raw.SharedPV.open"]], "p4p.client.raw": [[4, "module-p4p.client.raw"]], "p4p.server.raw": [[4, "module-p4p.server.raw"]], "post() (p4p.server.raw.sharedpv method)": [[4, "p4p.server.raw.SharedPV.post"]], "put() (p4p.client.raw.context method)": [[4, "p4p.client.raw.Context.put"]], "put() (p4p.server.raw.handler method)": [[4, "p4p.server.raw.Handler.put"]], "rpc() (p4p.client.raw.context method)": [[4, "p4p.client.raw.Context.rpc"]], "rpc() (p4p.server.raw.handler method)": [[4, "p4p.server.raw.Handler.rpc"]], "ntmultichannel (class in p4p.nt)": [[5, "p4p.nt.NTMultiChannel"]], "ntndarray (class in p4p.nt)": [[5, "p4p.nt.NTNDArray"]], "ntscalar (class in p4p.nt)": [[5, "p4p.nt.NTScalar"]], "nttable (class in p4p.nt)": [[5, "p4p.nt.NTTable"]], "nturi (class in p4p.nt)": [[5, "p4p.nt.NTURI"]], "wrapperinterface (class in p4p.nt)": [[5, "p4p.nt.WrapperInterface"]], "__init__() (p4p.nt.wrapperinterface method)": [[5, "p4p.nt.WrapperInterface.__init__"]], "assign() (p4p.nt.ntndarray method)": [[5, "p4p.nt.NTNDArray.assign"]], "assign() (p4p.nt.ntscalar method)": [[5, "p4p.nt.NTScalar.assign"]], "assign() (p4p.nt.wrapperinterface method)": [[5, "p4p.nt.WrapperInterface.assign"]], "buildtype() (p4p.nt.ntmultichannel static method)": [[5, "p4p.nt.NTMultiChannel.buildType"]], "buildtype() (p4p.nt.ntndarray class method)": [[5, "p4p.nt.NTNDArray.buildType"]], "buildtype() (p4p.nt.ntscalar static method)": [[5, "p4p.nt.NTScalar.buildType"]], "buildtype() (p4p.nt.nttable static method)": [[5, "p4p.nt.NTTable.buildType"]], "buildtype() (p4p.nt.nturi static method)": [[5, "p4p.nt.NTURI.buildType"]], "buildtype() (p4p.nt.wrapperinterface class method)": [[5, "p4p.nt.WrapperInterface.buildtype"]], "defaultnt() (in module p4p.nt)": [[5, "p4p.nt.defaultNT"]], "ntfloat (class in p4p.nt.scalar)": [[5, "p4p.nt.scalar.ntfloat"]], "ntint (class in p4p.nt.scalar)": [[5, "p4p.nt.scalar.ntint"]], "ntndarray (class in p4p.nt.ndarray)": [[5, "p4p.nt.ndarray.ntndarray"]], "ntnumericarray (class in p4p.nt.scalar)": [[5, "p4p.nt.scalar.ntnumericarray"]], "ntstr (class in p4p.nt.scalar)": [[5, "p4p.nt.scalar.ntstr"]], "ntstringarray (class in p4p.nt.scalar)": [[5, "p4p.nt.scalar.ntstringarray"]], "unwrap() (p4p.nt.ntndarray class method)": [[5, "p4p.nt.NTNDArray.unwrap"]], "unwrap() (p4p.nt.ntscalar class method)": [[5, "p4p.nt.NTScalar.unwrap"]], "unwrap() (p4p.nt.nttable static method)": [[5, "p4p.nt.NTTable.unwrap"]], "unwrap() (p4p.nt.wrapperinterface method)": [[5, "p4p.nt.WrapperInterface.unwrap"]], "wrap() (p4p.nt.ntndarray method)": [[5, "p4p.nt.NTNDArray.wrap"]], "wrap() (p4p.nt.ntscalar method)": [[5, "p4p.nt.NTScalar.wrap"]], "wrap() (p4p.nt.nttable method)": [[5, "p4p.nt.NTTable.wrap"]], "wrap() (p4p.nt.nturi method)": [[5, "p4p.nt.NTURI.wrap"]], "wrap() (p4p.nt.wrapperinterface method)": [[5, "p4p.nt.WrapperInterface.wrap"]], "nturidispatcher (class in p4p.rpc)": [[7, "p4p.rpc.NTURIDispatcher"]], "rpcproxybase (class in p4p.rpc)": [[7, "p4p.rpc.RPCProxyBase"]], "remoteerror (class in p4p.rpc)": [[7, "p4p.rpc.RemoteError"]], "workqueue (class in p4p.rpc)": [[7, "p4p.rpc.WorkQueue"]], "authority (p4p.rpc.rpcproxybase attribute)": [[7, "p4p.rpc.RPCProxyBase.authority"]], "context (p4p.rpc.rpcproxybase attribute)": [[7, "p4p.rpc.RPCProxyBase.context"]], "handle() (p4p.rpc.workqueue method)": [[7, "p4p.rpc.WorkQueue.handle"]], "interrupt() (p4p.rpc.workqueue method)": [[7, "p4p.rpc.WorkQueue.interrupt"]], "quickrpcserver() (in module p4p.rpc)": [[7, "p4p.rpc.quickRPCServer"]], "rpc() (in module p4p.rpc)": [[7, "p4p.rpc.rpc"]], "rpccall() (in module p4p.rpc)": [[7, "p4p.rpc.rpccall"]], "rpcproxy() (in module p4p.rpc)": [[7, "p4p.rpc.rpcproxy"]], "throw (p4p.rpc.rpcproxybase attribute)": [[7, "p4p.rpc.RPCProxyBase.throw"]], "timeout (p4p.rpc.rpcproxybase attribute)": [[7, "p4p.rpc.RPCProxyBase.timeout"]], "dynamicprovider (class in p4p.server)": [[8, "p4p.server.DynamicProvider"]], "handler (class in p4p.server.thread)": [[8, "p4p.server.thread.Handler"]], "notyet (p4p.server.dynamicprovider attribute)": [[8, "p4p.server.DynamicProvider.NotYet"]], "providerhandler (class in p4p.server)": [[8, "p4p.server.ProviderHandler"]], "server (class in p4p.server)": [[8, "p4p.server.Server"]], "serveroperation (class in p4p.server)": [[8, "p4p.server.ServerOperation"]], "sharedpv (class in p4p.server.asyncio)": [[8, "p4p.server.asyncio.SharedPV"]], "sharedpv (class in p4p.server.cothread)": [[8, "p4p.server.cothread.SharedPV"]], "sharedpv (class in p4p.server.thread)": [[8, "p4p.server.thread.SharedPV"]], "staticprovider (class in p4p.server)": [[8, "p4p.server.StaticProvider"]], "account() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.account"]], "add() (p4p.server.staticprovider method)": [[8, "p4p.server.StaticProvider.add"]], "close() (p4p.server.staticprovider method)": [[8, "p4p.server.StaticProvider.close"]], "close() (p4p.server.thread.sharedpv method)": [[8, "p4p.server.thread.SharedPV.close"]], "conf() (p4p.server.server method)": [[8, "p4p.server.Server.conf"]], "current() (p4p.server.thread.sharedpv method)": [[8, "p4p.server.thread.SharedPV.current"]], "done() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.done"]], "installprovider() (in module p4p.server)": [[8, "p4p.server.installProvider"]], "keys() (p4p.server.staticprovider method)": [[8, "p4p.server.StaticProvider.keys"]], "name() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.name"]], "oncancel() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.onCancel"]], "onfirstconnect() (p4p.server.thread.handler method)": [[8, "p4p.server.thread.Handler.onFirstConnect"]], "onlastdisconnect() (p4p.server.thread.handler method)": [[8, "p4p.server.thread.Handler.onLastDisconnect"]], "open() (p4p.server.thread.sharedpv method)": [[8, "p4p.server.thread.SharedPV.open"]], "peer() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.peer"]], "post() (p4p.server.thread.sharedpv method)": [[8, "p4p.server.thread.SharedPV.post"]], "put() (p4p.server.thread.handler method)": [[8, "p4p.server.thread.Handler.put"]], "pvrequest() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.pvRequest"]], "remove() (p4p.server.staticprovider method)": [[8, "p4p.server.StaticProvider.remove"]], "removeprovider() (in module p4p.server)": [[8, "p4p.server.removeProvider"]], "roles() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.roles"]], "rpc() (p4p.server.thread.handler method)": [[8, "p4p.server.thread.Handler.rpc"]], "stop() (p4p.server.server method)": [[8, "p4p.server.Server.stop"]], "testchannel() (p4p.server.providerhandler method)": [[8, "p4p.server.ProviderHandler.testChannel"]], "value() (p4p.server.serveroperation method)": [[8, "p4p.server.ServerOperation.value"]], "type (class in p4p)": [[10, "p4p.Type"]], "value (class in p4p)": [[10, "p4p.Value"]], "__getattr__() (p4p.type method)": [[10, "p4p.Type.__getattr__"]], "__getattr__() (p4p.value method)": [[10, "p4p.Value.__getattr__"]], "__getitem__() (p4p.value method)": [[10, "p4p.Value.__getitem__"]], "__iter__() (p4p.type method)": [[10, "p4p.Type.__iter__"]], "__setattr__() (p4p.value method)": [[10, "p4p.Value.__setattr__"]], "__setitem__() (p4p.value method)": [[10, "p4p.Value.__setitem__"]], "asset() (p4p.value method)": [[10, "p4p.Value.asSet"]], "aspy() (p4p.type method)": [[10, "p4p.Type.aspy"]], "changed() (p4p.value method)": [[10, "p4p.Value.changed"]], "changedset() (p4p.value method)": [[10, "p4p.Value.changedSet"]], "get() (p4p.value method)": [[10, "p4p.Value.get"]], "getid() (p4p.type method)": [[10, "p4p.Type.getID"]], "getid() (p4p.value method)": [[10, "p4p.Value.getID"]], "has() (p4p.type method)": [[10, "p4p.Type.has"]], "has() (p4p.value method)": [[10, "p4p.Value.has"]], "items() (p4p.type method)": [[10, "p4p.Type.items"]], "items() (p4p.value method)": [[10, "p4p.Value.items"]], "keys() (p4p.type method)": [[10, "p4p.Type.keys"]], "mark() (p4p.value method)": [[10, "p4p.Value.mark"]], "p4p": [[10, "module-p4p"]], "select() (p4p.value method)": [[10, "p4p.Value.select"]], "todict() (p4p.value method)": [[10, "p4p.Value.todict"]], "tolist() (p4p.value method)": [[10, "p4p.Value.tolist"]], "tostr() (p4p.value method)": [[10, "p4p.Value.tostr"]], "type() (p4p.value method)": [[10, "p4p.Value.type"]], "unmark() (p4p.value method)": [[10, "p4p.Value.unmark"]], "values() (p4p.type method)": [[10, "p4p.Type.values"]]}}) \ No newline at end of file diff --git a/server.html b/server.html new file mode 100644 index 00000000..bde3c91a --- /dev/null +++ b/server.html @@ -0,0 +1,611 @@ + + + + + + + + + Server API — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Server API

+
+

Running a PVA Server

+

A Server instance starts/stops a PVAccess server. +In order to be useful, a Server must be associated with one or more Providers.

+

Two Provider containers are available: StaticProvider or DynamicProvider. +Both are used with one of the SharedPV classes:, +thread.SharedPV, asyncio.SharedPV, and/or cothread.SharedPV. +Instances of these different concurrency models may be mixed into a single Provider.

+
+

Example

+

A server with a single “mailbox” PV.

+
import time
+from p4p.nt import NTScalar
+from p4p.server import Server
+from p4p.server.thread import SharedPV
+
+pv = SharedPV(nt=NTScalar('d'), # scalar double
+              initial=0.0)      # setting initial value also open()'s
+@pv.put
+def handle(pv, op):
+    pv.post(op.value()) # just store and update subscribers
+    op.done()
+
+Server.forever(providers=[{
+    'demo:pv:name':pv, # PV name only appears here
+}]) # runs until KeyboardInterrupt
+
+
+

This server can be tested using the included command line tools. eg.

+
$ python -m p4p.client.cli get demo:pv:name
+$ python -m p4p.client.cli put demo:pv:name
+$ python -m p4p.client.cli get demo:pv:name
+
+
+

And in another shell.

+
$ python -m p4p.client.cli monitor demo:pv:name
+
+
+

Note that this example allows clients to change any field, not just ‘.value’. +This may be restricted by inspecting the Value returned by ‘op.value()’ +to see which fields are marked as changed with eg. Value.changed().

+

A client put operation can be failed with eg. ‘op.done(error=”oops”)’.

+

In the put handler function ‘pv’ is the SharedPV and ‘op’ is a ServerOperation.

+
+
+
+

Server API

+
+
+class p4p.server.Server(conf=None, useenv=True, providers=[''])[source]
+
+
Parameters:
+
    +
  • providers – A list of provider names or instances. See below.

  • +
  • conf (dict) – Configuration keys for the server. Uses same names as environment variables (aka. EPICS_PVAS_*)

  • +
  • useenv (bool) – Whether to use process environment in addition to provided config.

  • +
  • isolate (bool) – If True, override conf= and useenv= to select a configuration suitable for isolated testing. +eg. listening only on localhost with a randomly chosen port number. Use conf() to determine +which port is being used.

  • +
+
+
+

Run a PVAccess server serving Channels from the listed providers. +The server is running after construction, until stop().

+
S = Server(providers=["example"])
+# do something else
+S.stop()
+
+
+

As a convenience, a Server may be used as a context manager to automatically stop().

+
with Server(providers=["example"]) as S:
+    # do something else
+
+
+

When configuring a Server, conf keys provided to the constructor have the same name as the environment variables. +If both are given, then the provided conf dict is used.

+

Call Server.conf() to see a list of valid server (EPICS_PVAS_*) key names and the actual values.

+

The providers list may contain: name strings (cf. installProvider()), +StaticProvider or DynamicProvider instances, or a dict “{‘pv:name’:SharedPV}” to implicitly creat a StaticProvider. +Each entry may also be a tuple “(provider, order)” where “provider” is any of the allowed types, +and “order” is an integer used to resolve ambiguity if more than one provider may claim a PV name. +(lower numbers are queried first, the default order is 0)

+
+
+conf()[source]
+

Return a dict() with the effective configuration this server is using.

+

Suitable to pass to another Server to duplicate this configuration, +or to a client Context to allow it to connect to this server.

+
with Server(providers=["..."], isolate=True) as S:
+    with p4p.client.thread.Context('pva', conf=S.conf(), useenv=False) as C:
+        print(C.get("pv:name"))
+
+
+
+ +
+
+stop()[source]
+

Force server to stop serving, and close connections to existing clients.

+
+ +
+ +
+
+class p4p.server.StaticProvider(name=None)[source]
+

A channel provider which servers from a clearly defined list of names. +This list may change at any time.

+
+
Parameters:
+

name (str) – Provider name. Must be unique within the local context in which it is used. +None, the default, will choose an appropriate value.

+
+
+
+
+close()
+
+ +
+
+add()
+
+ +
+
+remove()
+
+ +
+
+keys()
+
+ +
+ +

For situations where PV names are not known ahead of time, +or when PVs are “created” only as requested, DynamicProvider should be used.

+
+
+class p4p.server.DynamicProvider(name, handler)[source]
+

A channel provider which does not maintain a list of provided channel names.

+

The following example shows a simple case, in fact so simple that StaticProvider +is a better fit.

+
class DynHandler(object):
+    def __init__(self):
+        self.pv = SharedPV()
+    def testChannel(self, name): # return True, False, or DynamicProvider.NotYet
+        return name=="blah"
+    def makeChannel(self, name, peer):
+        if name=="blah":
+            return self.pv
+        # return None falls through to next source
+provider = DynamicProvider("arbitrary", DynHandler())
+server = Server(providers=[provider])
+
+
+
+
+NotYet = b'nocache'
+
+ +
+ +
+

DynamicProvider Handler Interface

+

A DynamicProvider Handler class will define the following:

+
+
+class p4p.server.ProviderHandler
+
+
+testChannel(pvname)
+

Called with a PV name which some client is searching for.

+
+
Returns:
+

True to claim this PV. False to “permenently” disclaim this PV. Or DynamicProvider.NotYet to temporarily disclaim.

+
+
+

Each DynamicProvider maintains a cache of negative search results (when `testChannel()==False`) +to avoid extra work on a subnet with many clients searching for non-existant PVs. +If it is desirable to defeat this behavour, for example as part of lazy pv creation, +then testChannel() can return DynamicProvider.NotYet instead of False.

+
+ +
+
+makeChannel(pvname, src):
+

Called when a client attempts to create a Channel for some PV. +The object which is returned will not be collected until +the client closes the Channel or becomes disconnected.

+
+
Returns:
+

A SharedPV instance.

+
+
+
+ +
+ +
+
+

ServerOperation

+

This class is passed to SharedPV handler Handler.put() and Handler.rpc() methods.

+
+
+class p4p.server.ServerOperation
+

An in-progress Put or RPC operation from a client.

+
+
+done(value=None, error=None)
+

Signal completion of the operation.

+
# successful completion without result (Put or RPC)
+done()
+# successful completion with result (RPC only)
+done(Value)
+# unsuccessful completion (Put or RPC)
+done(error="msg")
+
+
+
+ +
+
+pvRequest() Value
+

Access the request Value provided by the client, which may ignored, or used to modify handling.

+
+ +
+
+value() Value
+

For an RPC operation, the argument Value provided

+
+ +
+
+name() str
+

The PV name used by the client

+
+ +
+
+peer() str
+

Client address

+
+ +
+
+account() str
+

Client identity

+
+ +
+
+roles() {str}
+

Client group memberships

+
+ +
+
+onCancel(callable|None)
+

Set callable which will be invoked if the remote operation is +cancelled by the client, or if client connection is lost.

+
+ +
+ +
+
+
+

SharedPV concurrency options

+

There is a SharedPV class for each of other three concurrency models +supported: OS threading, asyncio coroutines, and cothreads. +All have the same methods as thread.SharedPV.

+

The difference between thread.SharedPV, asyncio.SharedPV, and cothread.SharedPV +is the context in which the handler methods are called (an OS thread, an asyncio coroutine, or a cothread). +This distinction determines how blocking operations may be carried out.

+

Note that thread.SharedPV uses a fixed size thread pool. +This limits the number of concurrent callbacks.

+
+
+

SharedPV API

+
+
+class p4p.server.thread.SharedPV(queue=None, **kws)[source]
+

Shared state Process Variable. Callback based implementation.

+
+

Note

+

if initial=None, the PV is initially closed and +must be open()’d before any access is possible.

+
+
+
Parameters:
+
    +
  • handler – A object which will receive callbacks when eg. a Put operation is requested. +May be omitted if the decorator syntax is used.

  • +
  • initial (Value) – An initial Value for this PV. If omitted, open() s must be called before client access is possible.

  • +
  • nt – An object with methods wrap() and unwrap(). eg p4p.nt.NTScalar.

  • +
  • wrap (callable) – As an alternative to providing ‘nt=’, A callable to transform Values passed to open() and post().

  • +
  • unwrap (callable) – As an alternative to providing ‘nt=’, A callable to transform Values returned Operations in Put/RPC handlers.

  • +
  • queue (WorkQueue) – The threaded WorkQueue on which handlers will be run.

  • +
  • options (dict) – A dictionary of configuration options.

  • +
+
+
+

Creating a PV in the open state, with no handler for Put or RPC (attempts will error).

+
from p4p.nt import NTScalar
+pv = SharedPV(nt=NTScalar('d'), value=0.0)
+# ... later
+pv.post(1.0)
+
+
+

The full form of a handler object is:

+
class MyHandler:
+    def put(self, op):
+        pass
+    def rpc(self, op):
+        pass
+    def onFirstConnect(self): # may be omitted
+        pass
+    def onLastDisconnect(self): # may be omitted
+        pass
+pv = SharedPV(MyHandler())
+
+
+

Alternatively, decorators may be used.

+
pv = SharedPV()
+@pv.put
+def onPut(pv, op):
+    pass
+
+
+
+
+open(value, nt=None, wrap=None, unwrap=None, **kws)[source]
+

Mark the PV as opened an provide its initial value. +This initial value is later updated with post().

+
+
Parameters:
+

value – A Value, or appropriate object (see nt= and wrap= of the constructor).

+
+
+

Any clients which have begun connecting which began connecting while +this PV was in the close’d state will complete connecting.

+

Only those fields of the value which are marked as changed will be stored.

+
+ +
+
+close(destroy=False, sync=False, timeout=None)[source]
+

Close PV, disconnecting any clients.

+
+
Parameters:
+
    +
  • destroy (bool) – Indicate “permanent” closure. Current clients will not see subsequent open().

  • +
  • sync (bool) – When block until any pending onLastDisconnect() is delivered (timeout applies).

  • +
  • timeout (float) – Applies only when sync=True. None for no timeout, otherwise a non-negative floating point value.

  • +
+
+
+

close() with destory=True or sync=True will not prevent clients from re-connecting. +New clients may prevent sync=True from succeeding. +Prevent reconnection by __first__ stopping the Server, removing with StaticProvider.remove(), +or preventing a DynamicProvider from making new channels to this SharedPV.

+
+ +
+
+post(value, **kws)[source]
+

Provide an update to the Value of this PV.

+
+
Parameters:
+

value – A Value, or appropriate object (see nt= and wrap= of the constructor).

+
+
+

Only those fields of the value which are marked as changed will be stored.

+

Any keyword arguments are forwarded to the NT wrap() method (if applicable). +Common arguments include: timestamp= , severity= , and message= .

+
+ +
+
+current()[source]
+
+ +
+ +
+

SharedPV Handler Interface

+
+
+class p4p.server.thread.Handler[source]
+

Skeleton of SharedPV Handler

+

Use of this as a base class is optional.

+
+
+put(pv, op)[source]
+

Called each time a client issues a Put +operation on this Channel.

+
+
Parameters:
+
+
+
+
+ +
+
+rpc(pv, op)[source]
+

Called each time a client issues a Remote Procedure Call +operation on this Channel.

+
+
Parameters:
+
+
+
+
+ +
+
+onFirstConnect(pv)[source]
+

Called when the first Client channel is created.

+
+
Parameters:
+

pv (SharedPV) – The SharedPV which this Handler is associated with.

+
+
+
+ +
+
+onLastDisconnect(pv)[source]
+

Called when the last Client channel is closed.

+
+
Parameters:
+

pv (SharedPV) – The SharedPV which this Handler is associated with.

+
+
+
+ +
+ +
+
+

asyncio or cothread

+
+
+class p4p.server.asyncio.SharedPV[source]
+

Same arguments as thread.SharedPV except that queue= is replaced with loop= .

+
+
Parameters:
+

loop – An asyncio event loop, or None to use the default.

+
+
+
+ +
+
+class p4p.server.cothread.SharedPV
+
+ +
+
+

Global Provider registry

+

If it becomes necessary for a Provider to be included in a server which is started +outside of Python code, then it must be placed in the global provider registry +with installProvider().

+
+
+p4p.server.installProvider(name, provider)[source]
+
+ +
+
+p4p.server.removeProvider(name)[source]
+
+ +
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/starting.html b/starting.html new file mode 100644 index 00000000..08a5e119 --- /dev/null +++ b/starting.html @@ -0,0 +1,184 @@ + + + + + + + + + Quick Start — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Quick Start

+

For testing and evaluation, it is recommended to install from pypi.org into a (disposable) virtualenv.

+
python -m virtualenv p4ptest
+. p4ptest/bin/activate
+python -m pip install -U pip
+python -m pip install p4p nose2
+python -m nose2 p4p   # Optional: runs automatic tests
+
+
+

With this complete, open three terminal instances. +One to run a PVA client, and two more to run PVA clients. +In the first run a PVA server. Feel free to replace ‘my:pv:name’ +with an arbitrary name string everywhere it occurs.

+
$ . p4ptest/bin/activate
+$ python -m p4p.server.cli my:pv:name=int
+...
+INFO:p4p.server:Running server
+
+
+

In a second terminal run the following. If successful, the last line will end with a zero value.

+
$ . p4ptest/bin/activate
+$ python -m p4p.client.cli monitor my:pv:name
+...
+my:pv:name Mon Jul  9 19:24:01 2018 0L
+
+
+

And finally, in a third terminal run the following. If successful, the second terminal should show the new value.

+
$ . p4ptest/bin/activate
+$ python -m p4p.client.cli put my:pv:name=5
+my:pv:name=5
+
+
+

Alternately, using the Client API.

+
from p4p.client.thread import Context
+ctxt = Context('pva')
+print(ctxt.get('my:pv:name'))
+ctxt.put('my:pv:name', 6)
+print(ctxt.get('my:pv:name'))
+
+
+
+

Troubleshooting network issues

+

If the preceeding didn’t work as described, there is likely a networking problem. +Restart both server and client with an added argument ‘-d’. +Look for lines like:

+
...
+2018-09-27T17:00:44.164 Broadcast address #0: 10.65.15.255:5076. (not unicast)
+2018-09-27T17:00:44.164 Broadcast address #1: 192.168.210.255:5076. (not unicast)
+...
+
+
+

This indicates the two network interfaces were discovered on this host. +Localhost is not included by default. +If no interfaces are found, then check the system network configuration. +If interfaces are found, ensure that no firewalls are applied.

+

By default, both client and server must share at least one discovered +local broadcast address.

+

Non-default configuration involves the use of the $EPICS_PVA_ADDR_LIST +environment variable, or configuration options specifically passed +to conf= p4p.client.thread.Context(). This is considered beyond the +scope of a “quick start”.

+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/values.html b/values.html new file mode 100644 index 00000000..23862b68 --- /dev/null +++ b/values.html @@ -0,0 +1,750 @@ + + + + + + + + + Working with Value and Type — P4P 4.1.12 documentation + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Working with Value and Type

+

Each Value corresponds conceptually with a C/C++ struct in that it consists +of zero or more data fields. Values are strongly typed, with each Value having a corresponding +Type. Each field has a concrete type, which may in turn be a sub-structure.

+

Further, each Value holds a bit mask which identifies fields which have “changed”. +This bit mask is used during PVA protocol operations to select a subset of fields +which will actually be transfered over the network.

+
+

Working with Type and Value

+

Value is initialized in two steps. +First a Type describing the data structure is created, +then the Value container is built, and optionally initialized.

+
>>> from p4p import Type, Value
+>>> T = Type([('value', 'i')])
+>>> V = Value(T, {'value':42})
+
+
+

Here a simple structure is defined with a single field ‘value’ which is a signed 32-bit integer. +The created value initializes ‘value’ to 42. +This Value can then be accessed with:

+
>>> V.value
+42
+>>> V['value']
+42
+>>> V.get('value', 111)
+42
+>>> V.get('invalid', 111) # uses default
+111
+
+
+

Field values can also be changed

+
>>> V.value = 43
+>>> V['value'] = 43
+
+
+
+

Change tracking

+

Each Value maintains a mask marking which of its field have been initialized/changed.

+

A newly created Value has no fields marked (empty mask).

+
V = Value(T)
+assert V.asSet()==set()
+
+
+

Initial values can be provided at construction.

+
V = Value(T, {'value': 42})
+assert V.changed('value')
+assert V.asSet()==set('value')
+
+
+

Assignment of a new value automatically marks a field as changed.

+
V = Value(T)
+assert not V.changed('value')
+V.value = 42
+assert V.changed('value')
+
+
+

The change mask can be cleared if necessary. eg. when passing the same Value to SharedPV.post() several times.

+
V = Value(T, {'value': 42})
+assert V.changed('value')
+V.unmark()
+assert not V.changed('value')
+
+
+
+
+
+

Type definitions

+

The p4p.nt module contains helpers to build common Type definitions.

+

Structures are strongly typed. +The type is specified with a code. +Supported codes are given in the table below.

+

Type specifier codes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Code

Type

?

bool

s

unicode

b

s8

B

u8

h

s16

H

u16

i

i32

I

u32

l

i64

L

u64

f

f32

d

f64

v

variant

U

union

S

struct

+
+

Note

+

Prefix with ‘a’ for “array of”. For example, ‘ai’ is an array of signed 32-bit integers.

+
+

A Type is build with a list of tuples, +where each tuple defines a field.

+

For all type codes except struct ‘S’ and discriminating union ‘U’ only the type code is needed.

+
T = Type([
+   ('value', 's'), # string
+   ('other', 'ad'), # array of double floating
+])
+
+
+

sub-structures and discriminating union have a nested tuple to fully define the field type.

+
>>> T = Type([
+   ('value', 's'), # string
+   ('alarm', ('S', None, [
+       ('severity', 'i'),
+       ('status', 'i'),
+       ('message', 's'),
+   ])),
+])
+>>> V = Value(T, {'alarm':{'severity':0}})
+>>> V.alarm.severity
+0
+>>> V.alarm['severity']
+0
+>>> V['alarm.severity']
+0
+
+
+

Here a sub-structure ‘alarm’ is defined with three fields.

+

A discriminating union is defined in the same manner.

+
>>> V = Type([
+   ('value', ('u', None, [
+       ('ival', 'i'),
+       ('sval', 's'),
+   ])),
+])()
+>>> V.value
+None
+>>> V.value = ('ival', 42) # explicitly select union field name
+>>> V.value
+42
+>>> V.value = ('sval', 'hello')
+>>> V.value
+u'hello'
+>>> V.value = 43   # beware still using 'sval' !!
+>>> V.value
+u'43'
+
+
+
+

Assigning variant and union

+

As the preceding example suggests, the rules for assigning values +to variant and union fields can be surprising.

+

The rules for assigning a variant are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

value type

Action

None

clears current value

Value

Stores a structure

int

signed 32-bit (python 2.x only)

long

signed 64-bit

float

64-bit floating

bytes|unicode

string

ndarray

array of integer or floating

+

Further, a variant union may be explicitly assigned with a specific scalar/array type +using a tuple of a type specifier code and value.

+

Other types throw an Exception.

+
>>> V = Type([('x','v')])()
+>>> V.x = 4.2 # inferred 64-bit floating
+>>> V.x = ('f', 4.2) # explicit 32-bit floating
+
+
+

The rules for assigning a discriminating union are as follows:

+ + + + + + + + + + + + + + + + + + + + +

value type

Action

None

clears current value

(‘field’, val)

explicitly specify the union field name

val

If a union field has previously been selected, coerce assigned value

val

If no union field previously select, attempt magic selection and coerce.

+

Other types throw an Exception.

+
+
+
+

API Reference

+
+
+class p4p.Value(type[, initial])[source]
+
+
Parameters:
+
    +
  • type (Type) – The Type describing the structure to be instanciated

  • +
  • initial (dict) – A dictionary (or any mapping) which gives initial values for fields.

  • +
+
+
+

Representation of a data structure of a particular Type.

+

Can be created using a Type, with an optional dict containing initial values.

+
A = Value(Type([
+    ('value', 'I'),
+]), {
+    'value': 42,
+})
+
+
+

Defines a structure with a single field named ‘value’ with type u32 (unsigned integer width 32-bit).

+

An example of defining a sub-structure.

+
A = Value(Type([
+    ('value', ('S', None, [
+        ('index', 'i'),
+    ])),
+]), {
+    'value': {'index', 5},
+    # 'value.index': 5,  # equivalent
+})
+
+
+

Defines a structure containing a sub-structure ‘value’ which has a single field ‘index’ which is +a signed 32-bit integer.

+
+
+tolist(name=None) List[Tuple[str, Value]]
+

Return this Value (or the named sub-field) translated into a list of tuples

+
+ +
+
+todict(name=None, wrapper=None) Mapping[str, Value]
+

Return this Value (or the named sub-field) translated into a dict

+
+
Parameters:
+
    +
  • name (str) – Sub-field name, or None

  • +
  • wrapper (callable) – Passed an iterable of name,value tuples. By default dict eg. could be OrderedDict

  • +
+
+
+
+ +
+
+tostr(limit: int = 0) str
+

Return a string representation, optionally truncated to a length limit

+
+
Parameters:
+

limit (int) – If greater than zero, formatting is terminated at limit charactors.

+
+
+
+ +
+
+items(key: str = None) Iterable[Value | Any]
+
+
Parameters:
+

key (str) – Sub-field name

+
+
+
+ +
+
+getID() str
+

Return Type id= string

+
+ +
+
+type(fld: str = None) Type
+

Return the Type of this Value, or the named sub-field.

+
+
Parameters:
+

fld (str) – Sub-field name, or None

+
+
+
+ +
+
+has(name: str) bool
+

Test for sub-field existance

+
+
Parameters:
+

name (str) – Sub-field name

+
+
+
+ +
+
+get(key: str, default=None) Value | Any
+

dict-like access to sub-field

+
+
Parameters:
+
    +
  • key (str) – Sub-field name

  • +
  • default – returned if sub-field doesn’t exist

  • +
+
+
+
+ +
+
+select(name: str, selector: str)
+

Explicitly select Union member

+
+
Parameters:
+

name (str) – Sub-field name

+
+
+
+ +
+
+__getattr__(field)
+

Access a sub-field. If the sub-field value.

+
+ +
+
+__setattr__(field, value)
+

Assign sub-field.

+
+ +
+
+__getitem__(field)
+

Same as __getattr__

+
+ +
+
+__setitem__(field, value)
+

Same as __setattr__

+
+ +
+
+changed(*fields) bool[source]
+

Test if one or more named fields have changed.

+

A field is considered to have changed if it is marked as changed, +or if its parent, or any child, field is marked as changed.

+
+ +
+
+changedSet(expand=False, parents=False) set[source]
+
+
Parameters:
+
    +
  • expand (bool) – Whether to expand when entire sub-structures are marked as changed. +If True, then sub-structures are expanded and only leaf fields will be included. +If False, then a direct translation is made, which may include both leaf and sub-structure fields.

  • +
  • parents (bool) – If True, include fake entries for parent sub-structures with leaf fields marked as changed.

  • +
+
+
Returns:
+

A set of names of those fields marked as changed.

+
+
+

Return a set containing the names of all changed fields.

+
A = Value(Type([
+    ('x', 'i'),
+    ('z', ('S', None, [
+        ('a', 'i'),
+        ('b', 'i'),
+    ])),
+]), {
+})
+
+A.mark('z')
+assert A.changedSet(expand=False) == {'z'}         # only shows fields explicitly marked
+assert A.changedSet(expand=True) == {'z.a', 'z.b'} # actually used during network transmission
+A.mark('z.a') # redundant
+assert A.changedSet(expand=False) == {'z', 'z.a'}
+assert A.changedSet(expand=True) == {'z.a', 'z.b'}
+A.unmark('z')
+assert A.changedSet(expand=False) == {'z.a'}
+assert A.changedSet(expand=True) == {'z.a'}
+assert A.changedSet(expand=False, parents=True) == {'z', 'z.a'}
+assert A.changedSet(expand=True, parents=True) == {'z', 'z.a'}
+
+
+
    +
  • expand=False, parents=False gives a direct mapping of the underlying BitSet as it would (get/monitor), +or have been (put/rpc), moved over the network.

  • +
  • expand=True, parents=False gives the effective set of leaf fields which will be moved over the network. +taking into account the use of whole sub-structure compress/shorthand bits.

  • +
  • expand=False, parents=True gives a way of testing if anything changed within a set of interesting fields +(cf. set.intersect).

  • +
+
+ +
+
+mark(field=None, val=True)
+

Mark (or unmark) the this field, or the named sub-field.

+
+
Parameters:
+
    +
  • field (str) – Sub-field name

  • +
  • val (bool) – To mark, or unmark

  • +
+
+
+
+ +
+
+unmark()
+

Unmark Value and all sub-fields.

+
+ +
+
+asSet()
+

Deprecated alias for asSet()

+
+ +
+ +
+
+class p4p.Type(fields, id=None, base=None)[source]
+
+
Parameters:
+
    +
  • fields (list) – A list of tuples describing members of this data structure.

  • +
  • id (str) – Type label string.

  • +
  • base (Type) – Copy the fields of Type, then amend with the provided fields.

  • +
+
+
+

A definition of a data structure consisting of a list of field names and types, +as well as an optional type name string (id=””). +Field type specifications are either a string eg. “d” (double precision float), +or a tuple (“S”, None, [fields…) defining a sub-structure.

+
T = Type([
+    ('value', 'I'),
+])
+
+
+

Defines a structure with a single field named ‘value’ with type u32 (unsigned integer width 32-bit).

+

An example of defining a sub-structure.

+
T = Type([
+    ('value', ('S', None, [
+        ('index', 'i'),
+    ])),
+])
+
+
+

Type specifier codes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Code

Type

?

bool

s

unicode

b

s8

B

u8

h

s16

H

u16

i

i32

I

u32

l

i64

L

u64

f

f32

d

f64

v

variant

U

union

S

struct

+
+
+getID()
+

getId() -> str +Return Type id= string

+
+ +
+
+aspy(str=None) list
+

Return a Type specification list equivalent to the one passed to the constructor.

+
+ +
+
+has(str) bool
+

Does this Type include the named member field?

+
+ +
+
+__getattr__(field)
+

Return Type of field. Same as self.aspy(field) for non-structure fields.

+
+ +
+
+keys() Iterable[str]
+

Return child field names

+
+ +
+
+values()[source]
+
+ +
+
+items()[source]
+
+ +
+
+__iter__()[source]
+
+ +
+ +
+
+

Relation to C++ API

+

For those familiar with the PVXS API. +A Type wraps a TypeDef. +Value wraps a Value.

+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file