From fe840c529898c17b1db01ac400aced3a1fe5105f Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Wed, 28 Aug 2019 13:03:04 +0200 Subject: [PATCH 1/7] Generate gh-pages Added a doc/ dir in the root where generated documentation will be created. This will be done by Sphinx, see python/Makefile. --- docs/.gitignore | 4 ++++ python/Makefile | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 docs/.gitignore diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 00000000..a0eccca0 --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,4 @@ +# This file is here to force the docs/ dir to be included. +# Autogenerated documentation is created here by the CI. +* +!.gitignore diff --git a/python/Makefile b/python/Makefile index 567fbe40..a7faafcd 100644 --- a/python/Makefile +++ b/python/Makefile @@ -17,7 +17,7 @@ dazl_docs_markdown := dist/dazl-docs-$(version)-markdown.tar.gz build_dir := build/.dir poetry_build_marker := build/.poetry.build poetry_install_marker := build/.poetry.install -dazl_docs_html_dir := $(basename $(basename $(dazl_docs_html))) +dazl_docs_html_dir := ../docs # Required for Github pages dazl_docs_markdown_dir := $(basename $(basename $(dazl_docs_markdown))) export PYTHONPATH:=.:${PYTHONPATH} @@ -113,7 +113,7 @@ $(dazl_sdist): $(poetry_build_marker) $(dazl_docs_html): $(poetry_install_marker) $(dazl_files) poetry run python3 scripts/docs.py build --format html -o $(dazl_docs_html_dir) - (cd dist && tar czf $(@F) $(notdir $(dazl_docs_html_dir))) + (cd dist && tar czf $(@F) -C ../.. docs) #FIXME: use variables for this $(dazl_docs_markdown): $(poetry_install_marker) $(dazl_files) poetry run python3 scripts/docs.py build --format markdown -o $(dazl_docs_markdown_dir) From 82c2507e88a75496f618c4cbf873ba21a03d832e Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Wed, 28 Aug 2019 13:30:20 +0200 Subject: [PATCH 2/7] Add generated documentation --- .gitignore | 2 + docs/.gitignore | 4 - docs/.nojekyll | 0 docs/_modules/dazl/cli.html | 181 + docs/_modules/dazl/cli/ls.html | 147 + docs/_modules/dazl/client/api.html | 1556 +++ docs/_modules/dazl/client/bots.html | 593 + docs/_modules/dazl/model/core.html | 357 + docs/_modules/dazl/model/types.html | 1077 ++ docs/_modules/dazl/model/writing.html | 790 ++ docs/_modules/dazl/pretty.html | 150 + docs/_modules/index.html | 108 + docs/_sources/basics.rst.txt | 67 + docs/_sources/dazl.cli.rst.txt | 22 + docs/_sources/dazl.client.rst.txt | 30 + docs/_sources/dazl.damlast.rst.txt | 3 + docs/_sources/dazl.damlsdk.rst.txt | 3 + docs/_sources/dazl.model.rst.txt | 3 + docs/_sources/dazl.pretty.rst.txt | 3 + docs/_sources/dazl.protocols.rst.txt | 30 + docs/_sources/dazl.rst.txt | 24 + docs/_sources/dazl.util.rst.txt | 3 + docs/_sources/glossary.rst.txt | 7 + docs/_sources/index.rst.txt | 70 + docs/_sources/migrating.rst.txt | 89 + docs/_sources/tutorials.rst.txt | 9 + .../tutorials_message_ingester.rst.txt | 108 + docs/_sources/tutorials_post_office.rst.txt | 147 + .../_sources/tutorials_workflow_state.rst.txt | 114 + docs/_static/basic.css | 763 ++ docs/_static/css/theme.css | 39 + docs/_static/doctools.js | 314 + docs/_static/documentation_options.js | 10 + docs/_static/file.png | Bin 0 -> 286 bytes docs/_static/jquery-3.2.1.js | 10253 +++++++++++++++ docs/_static/jquery-3.4.1.js | 10598 ++++++++++++++++ docs/_static/jquery.js | 4 + docs/_static/language_data.js | 297 + docs/_static/minus.png | Bin 0 -> 90 bytes docs/_static/plus.png | Bin 0 -> 90 bytes docs/_static/pygments.css | 69 + docs/_static/searchtools.js | 506 + docs/_static/underscore-1.3.1.js | 999 ++ docs/_static/underscore.js | 31 + docs/basics.html | 182 + docs/dazl.cli.html | 171 + docs/dazl.client.html | 1554 +++ docs/dazl.damlast.html | 119 + docs/dazl.damlsdk.html | 120 + docs/dazl.html | 162 + docs/dazl.model.html | 379 + docs/dazl.pretty.html | 125 + docs/dazl.protocols.html | 139 + docs/dazl.util.html | 120 + docs/genindex.html | 715 ++ docs/glossary.html | 107 + docs/index.html | 232 + docs/migrating.html | 189 + docs/objects.inv | Bin 0 -> 1820 bytes docs/py-modindex.html | 225 + docs/search.html | 124 + docs/searchindex.js | 1 + docs/tutorials.html | 133 + docs/tutorials_message_ingester.html | 396 + docs/tutorials_post_office.html | 499 + docs/tutorials_workflow_state.html | 605 + 66 files changed, 35873 insertions(+), 4 deletions(-) delete mode 100644 docs/.gitignore create mode 100644 docs/.nojekyll create mode 100644 docs/_modules/dazl/cli.html create mode 100644 docs/_modules/dazl/cli/ls.html create mode 100644 docs/_modules/dazl/client/api.html create mode 100644 docs/_modules/dazl/client/bots.html create mode 100644 docs/_modules/dazl/model/core.html create mode 100644 docs/_modules/dazl/model/types.html create mode 100644 docs/_modules/dazl/model/writing.html create mode 100644 docs/_modules/dazl/pretty.html create mode 100644 docs/_modules/index.html create mode 100644 docs/_sources/basics.rst.txt create mode 100644 docs/_sources/dazl.cli.rst.txt create mode 100644 docs/_sources/dazl.client.rst.txt create mode 100644 docs/_sources/dazl.damlast.rst.txt create mode 100644 docs/_sources/dazl.damlsdk.rst.txt create mode 100644 docs/_sources/dazl.model.rst.txt create mode 100644 docs/_sources/dazl.pretty.rst.txt create mode 100644 docs/_sources/dazl.protocols.rst.txt create mode 100644 docs/_sources/dazl.rst.txt create mode 100644 docs/_sources/dazl.util.rst.txt create mode 100644 docs/_sources/glossary.rst.txt create mode 100644 docs/_sources/index.rst.txt create mode 100644 docs/_sources/migrating.rst.txt create mode 100644 docs/_sources/tutorials.rst.txt create mode 100644 docs/_sources/tutorials_message_ingester.rst.txt create mode 100644 docs/_sources/tutorials_post_office.rst.txt create mode 100644 docs/_sources/tutorials_workflow_state.rst.txt create mode 100644 docs/_static/basic.css create mode 100644 docs/_static/css/theme.css create mode 100644 docs/_static/doctools.js create mode 100644 docs/_static/documentation_options.js create mode 100644 docs/_static/file.png create mode 100644 docs/_static/jquery-3.2.1.js create mode 100644 docs/_static/jquery-3.4.1.js create mode 100644 docs/_static/jquery.js create mode 100644 docs/_static/language_data.js create mode 100644 docs/_static/minus.png create mode 100644 docs/_static/plus.png create mode 100644 docs/_static/pygments.css create mode 100644 docs/_static/searchtools.js create mode 100644 docs/_static/underscore-1.3.1.js create mode 100644 docs/_static/underscore.js create mode 100644 docs/basics.html create mode 100644 docs/dazl.cli.html create mode 100644 docs/dazl.client.html create mode 100644 docs/dazl.damlast.html create mode 100644 docs/dazl.damlsdk.html create mode 100644 docs/dazl.html create mode 100644 docs/dazl.model.html create mode 100644 docs/dazl.pretty.html create mode 100644 docs/dazl.protocols.html create mode 100644 docs/dazl.util.html create mode 100644 docs/genindex.html create mode 100644 docs/glossary.html create mode 100644 docs/index.html create mode 100644 docs/migrating.html create mode 100644 docs/objects.inv create mode 100644 docs/py-modindex.html create mode 100644 docs/search.html create mode 100644 docs/searchindex.js create mode 100644 docs/tutorials.html create mode 100644 docs/tutorials_message_ingester.html create mode 100644 docs/tutorials_post_office.html create mode 100644 docs/tutorials_workflow_state.html diff --git a/.gitignore b/.gitignore index cc3972b9..e21097dc 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,8 @@ .mypy_cache .poetry.ready .pytest_cache +docs/.buildinfo +docs/.doctrees python/build python/dazl.egg-info python/dist diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index a0eccca0..00000000 --- a/docs/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# This file is here to force the docs/ dir to be included. -# Autogenerated documentation is created here by the CI. -* -!.gitignore diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/docs/_modules/dazl/cli.html b/docs/_modules/dazl/cli.html new file mode 100644 index 00000000..0d363624 --- /dev/null +++ b/docs/_modules/dazl/cli.html @@ -0,0 +1,181 @@ + + + + + + + + dazl.cli + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.cli

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+Simple command-line handlers.
+"""
+
+import logging
+import sys
+from typing import List, Sequence
+
+from .. import setup_default_logger
+from ..model.core import ConfigurationError
+from ._base import CliCommand
+from .fetch import FetchComponentCommand
+from .ls import ListAllCommand
+from .metadata import PrintMetadataCommand
+from .package import PackageDarCommand
+from .sandbox import SandboxCommand
+from .tail import TailCommand
+from .upload import UploadCommand
+from .version import VersionCommand
+
+COMMANDS = [
+    FetchComponentCommand(),
+    ListAllCommand(),
+    PrintMetadataCommand(),
+    PackageDarCommand(),
+    SandboxCommand(),
+    TailCommand(),
+    UploadCommand(),
+    VersionCommand(),
+]  # type: List[CliCommand]
+
+
+
[docs]def main(): + """ + Executes one of the known commands. + """ + from sys import argv, exit + exit(_main(argv))
+ + +def _main(argv: 'Sequence[str]') -> int: + if len(argv) > 1: + command = argv[1] + command_args = argv[2:] + + for cmd in COMMANDS: + if cmd.name == command: + try: + return run(cmd, command_args) + except ConfigurationError as error: + for reason in error.reasons: + print(reason) + return -1 + + print("Unknown command: " + command) + + print_cmd_help() + return -2 + + +
[docs]def run(cmd, args) -> int: + parser = cmd.parser() + parsed_args = parser.parse_args(args) + + log_level = getattr(parsed_args, 'log_level', logging.WARNING) + if log_level is None: + log_level = logging.WARNING + + setup_default_logger(level=log_level) + return cmd.execute(parsed_args)
+ + + +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/cli/ls.html b/docs/_modules/dazl/cli/ls.html new file mode 100644 index 00000000..8f4a54f5 --- /dev/null +++ b/docs/_modules/dazl/cli/ls.html @@ -0,0 +1,147 @@ + + + + + + + + dazl.cli.ls + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.cli.ls

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+
+from asyncio import gather
+from argparse import ArgumentParser
+from .. import LOG, Network, write_acs
+from ._base import CliCommand
+from ..plugins import LedgerCapturePlugin
+from ..client.config import configure_parser, NetworkConfig
+
+
+
[docs]class ListAllCommand(CliCommand): + name = 'ls' + +
[docs] def parser(self) -> ArgumentParser: + arg_parser = ArgumentParser('dazl ls') + + configure_parser(arg_parser, config_file_support=True) + arg_parser.add_argument('--format', '--fmt', '-F', type=str, default=LedgerCapturePlugin.DEFAULT_FORMATTER_NAME) + arg_parser.add_argument('--template-filter', '-T', type=str) + arg_parser.add_argument('--all', '-A', action='store_true') + return arg_parser
+ +
[docs] def execute(self, args) -> int: + fmt = args.format + template_filter = [template.strip() for template in args.template_filter.split(',')] \ + if args.template_filter is not None else None + include_archived = bool(args.all) + LOG.debug('Executing an ls...') + + final_config = NetworkConfig.get_config(args) + + network = Network() + network.set_config(final_config) + + global_ready = gather(*[network.aio_party(party).ready() for party in args.parties]) + network.run_until_complete(self._main(network, global_ready, fmt, include_archived)) + return 0
+ + async def _main(self, network, global_ready, fmt, include_archived): + import sys + await global_ready + + write_acs(sys.stdout, network, fmt=fmt, include_archived=include_archived) + network.shutdown()
+
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/client/api.html b/docs/_modules/dazl/client/api.html new file mode 100644 index 00000000..b04b494a --- /dev/null +++ b/docs/_modules/dazl/client/api.html @@ -0,0 +1,1556 @@ + + + + + + + + dazl.client.api + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.client.api

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+This module contains the public API for interacting with the ledger from the perspective of a
+specific party.
+"""
+
+# NOTE TO IMPLEMENTORS
+#
+# This file contains only public API definitions, overloads, and documentation. (This file should
+# be treated more like a C header file than anything else.) The bulk of the implementation is kept
+# in _party_client.py.
+#
+# This file is repetitive and tedious, but written this way primarily so that static typing tools
+# do the right thing. Python's ``typing`` library (and mypy) aren't quite expressive enough to allow
+# for a more concise representation of the various flavors of the API. The unit test
+# ``test_api_consistency.py`` verifies that these implementations are generally in sync with each
+# other the way that the documentation says they are.
+import signal
+from asyncio import get_event_loop
+from contextlib import contextmanager, ExitStack
+from datetime import datetime
+from functools import wraps
+from logging import INFO
+from pathlib import Path
+from uuid import uuid4
+from threading import current_thread, main_thread
+from typing import Any, Awaitable, BinaryIO, Collection, ContextManager, List, Optional, \
+    Tuple, Union
+from urllib.parse import urlparse
+
+from .. import LOG
+from .bots import Bot, BotCollection
+from .config import AnonymousNetworkConfig, NetworkConfig, PartyConfig
+from ._base_model import IfMissingPartyBehavior, CREATE_IF_MISSING
+from ..damlsdk.sandbox import sandbox
+from ..metrics import MetricEvents
+from ..model.core import ContractId, ContractData, ContractsState, ContractMatch, \
+    ContractContextualData, ContractContextualDataCollection, Party, RunLevel
+from ..model.ledger import LedgerMetadata
+from ..model.reading import InitEvent, ReadyEvent, ContractCreateEvent, ContractExercisedEvent, \
+    ContractArchiveEvent, TransactionStartEvent, TransactionEndEvent, PackagesAddedEvent, EventKey
+from ..model.types import TemplateNameLike
+from ..model.writing import EventHandlerResponse
+from ..util.asyncio_util import await_then
+from ..util.io import get_bytes
+from ..util.prim_types import TimeDeltaConvertible
+from ._events import EventHandler, AEventHandler, EventHandlerDecorator, AEventHandlerDecorator, \
+    fluentize
+from ._network_client_impl import _NetworkImpl
+from ._party_client_impl import _PartyClientImpl
+from ._run_level import RunState
+
+
+DEFAULT_TIMEOUT_SECONDS = 30
+
+
+
[docs]@contextmanager +def simple_client(url: 'Optional[str]' = None, party: 'Union[None, str, Party]' = None, + log_level: 'Optional[int]' = INFO) \ + -> 'ContextManager[SimplePartyClient]': + """ + Start up a single client connecting to a single specific party. + + :param url: + The URL of the client to connect to. Defaults to the value of the ``DAML_LEDGER_URL`` + environment variable (if set). + :param party: + The party to connect as. Defaults to the value of the ``DAML_LEDGER_PARTY`` environment + variable if it is set. + :param log_level: + If non-``None``, configure a default logger that logs output at the specified level. The + default value is ``INFO``. + :return: + A :class:`SimplePartyClient` that can be used in a completely blocking, synchronous + fashion. + """ + if log_level is not None: + from .. import setup_default_logger + setup_default_logger(log_level) + + import os + if url is None: + url = os.getenv('DAML_LEDGER_URL') + if party is None: + party = os.getenv('DAML_LEDGER_PARTY') or uuid4().hex + if not url: + raise ValueError('url must be specified, or the DAML_LEDGER_URL environment variable ' + 'must be set') + if not party: + raise ValueError('party must be specified, or the DAML_LEDGER_PARTY environment variable ' + 'must be set') + + with ExitStack() as context_manager: + LOG.info('Starting a simple_client with to %s with party %r...', url, party) + parsed_url = urlparse(url) + if parsed_url.scheme is not None and parsed_url.scheme == 'sandbox': + # start a local in-memory sandbox first + daml_path = Path(os.getenv('DAML_LEDGER_DAR_PATH', 'target')) + + daml_artifacts = [] # type: List[Path] + daml_artifacts.extend(daml_path.glob('**/*.dar')) + daml_artifacts.extend(daml_path.glob('**/*.dalf')) + + sandbox_proc = sandbox(daml_path=daml_artifacts) + url = context_manager.enter_context(sandbox_proc).url + + network = Network() + network.set_config(url=url) + client = network.simple_party(party) + + network.start_in_background() + + yield client + + network.shutdown() + network.join()
+ + +
[docs]class Network: + """ + Manages network connection/scheduling logic on behalf of one or more :class:`PartyClient` + instances. + """ + + def __init__(self, metrics: 'Optional[MetricEvents]' = None): + self._impl = _NetworkImpl(metrics) + +
[docs] def set_config( + self, + *config: 'Union[NetworkConfig, AnonymousNetworkConfig]', + url: 'Optional[str]' = None, + admin_url: 'Optional[str]' = None, + **kwargs): + self._impl.set_config(*config, url=url, admin_url=admin_url, **kwargs)
+ +
[docs] def resolved_config(self) -> 'NetworkConfig': + """ + Calculate the configuration that will be used for this client when it is instantiated. + """ + return self._impl.resolved_config()
+ + # <editor-fold desc="Global/Party client creation"> + +
[docs] def simple_global(self) -> 'SimpleGlobalClient': + """ + Return a :class:`GlobalClient` that exposes thread-safe, synchronous (blocking) methods for + communicating with a ledger. Callbacks are dispatched to background threads. + """ + return self._impl.global_impl(SimpleGlobalClient)
+ +
[docs] def aio_global(self) -> 'AIOGlobalClient': + """ + Return a :class:`GlobalClient` that works on an asyncio event loop. + """ + return self._impl.global_impl(AIOGlobalClient)
+ +
[docs] def simple_party(self, party: 'Union[str, Party]') -> 'SimplePartyClient': + """ + Return a :class:`PartyClient` that exposes thread-safe, synchronous (blocking) methods for + communicating with a ledger. Callbacks are dispatched to background threads. + + :param party: The party to get a client for. + """ + return self._impl.party_impl(Party(party), SimplePartyClient)
+ +
[docs] def aio_party(self, party: 'Union[str, Party]') -> 'AIOPartyClient': + """ + Return a :class:`PartyClient` that works on an asyncio event loop. + + :param party: The party to get a client for. + """ + return self._impl.party_impl(Party(party), AIOPartyClient)
+ +
[docs] def party_bots( + self, + party: 'Union[str, Party]', + if_missing: IfMissingPartyBehavior = CREATE_IF_MISSING) -> 'BotCollection': + """ + Return the collection of bots associated with a party. + + :param party: The party to get bots for. + :param if_missing: + Specify the behavior to use in the case where no client has been yet requested for this + party. The default behavior is CREATE_IF_MISSING. + """ + party_impl = self._impl.party_impl(party, if_missing=if_missing) + return party_impl.bots if party_impl is not None else None
+ + # </editor-fold> + + # <editor-fold desc="Daemon thread-based scheduling API"> + +
[docs] def start_in_background( + self, daemon: bool = True, install_signal_handlers: Optional[bool] = None) -> None: + """ + Connect to the ledger in a background thread. + + The current thread does NOT block. Operations on instances of :class:`SimplePartyClient` + are allowed, and operations on instances of :class:`AIOPartyClient` are allowed as long as + they are made from the correct thread. + """ + if install_signal_handlers is None: + if current_thread() is main_thread(): + install_signal_handlers = True + elif install_signal_handlers: + if current_thread() is not main_thread(): + raise RuntimeError('tried to install signal handlers when not on the main thread') + + run_state = RunState(RunLevel.RUN_FOREVER) + if install_signal_handlers: + # the main loop will be run from a background thread, so do NOT use asyncio directly + try: + signal.signal(signal.SIGINT, lambda *_: self._impl.shutdown()) + signal.signal(signal.SIGQUIT, lambda *_: self._impl.abort()) + except (NotImplementedError, AttributeError, ValueError): + # SIGINIT and SIGQUIT handlers are not supported on Windows. + pass + + return self._impl.start(run_state, daemon)
+ +
[docs] def shutdown(self) -> None: + """ + Gracefully shut down all network connections and notify all clients that they are about to + be terminated. + + The current thread does NOT block. + """ + return self._impl.shutdown()
+ +
[docs] def join(self, timeout: 'Optional[float]' = None) -> None: + """ + Block the current thread until the client is shut down. + + :param timeout: + Number of seconds to wait before timing out the join, or ``None`` to wait indefinitely. + """ + return self._impl.join(timeout=timeout)
+ + # </editor-fold> + + # <editor-fold desc="asyncio-based scheduling API"> + + def _run(self, initial_run_level, *coroutines: 'Awaitable[None]', + install_signal_handlers: 'Optional[bool]' = None) -> None: + if install_signal_handlers is None: + if current_thread() is main_thread(): + install_signal_handlers = True + elif install_signal_handlers: + if current_thread() is not main_thread(): + raise RuntimeError('tried to install signal handlers when not on the main thread') + + run_state = RunState(initial_run_level) + loop = get_event_loop() + if install_signal_handlers: + try: + loop.add_signal_handler(signal.SIGINT, run_state.handle_sigint) + loop.add_signal_handler(signal.SIGQUIT, run_state.handle_sigquit) + except (NotImplementedError, AttributeError, ValueError): + # SIGINT and SIGQUIT are not supported on Windows. + pass + + loop.run_until_complete(self.aio_run(*coroutines, run_state=run_state)) + +
[docs] def run_until_complete( + self, *coroutines: 'Awaitable[None]', + install_signal_handlers: 'Optional[bool]' = None) \ + -> None: + """ + Block the main thread and run the application in an event loop on the main thread. The loop + terminates when the given (optional) coroutines terminate OR :meth:`shutdown` is called AND + all active command submissions and event handlers' follow-ups have successfully returned. + + :param coroutines: + Coroutines to run alongside event handlers and command submissions. When these + coroutines are done running and the + :param install_signal_handlers: + ``True`` to install SIGINT and SIGQUIT event handlers (CTRL+C and CTRL+\\); + ``False`` to skip installation. The default value is ``None``, which installs signal + handlers only when called from the main thread (default). If signal handlers are + requested to be installed and the thread is NOT the main thread, this method throws. + """ + self._run(RunLevel.RUN_UNTIL_IDLE, *coroutines, + install_signal_handlers=install_signal_handlers) + LOG.info('The internal run_until_complete event loop has now completed.')
+ +
[docs] def run_forever( + self, *coroutines: 'Awaitable[None]', + install_signal_handlers: 'Optional[bool]' = None) \ + -> None: + """ + Block the main thread and run the application in an event loop on the main thread. The loop + terminates when :meth:`shutdown` is called AND all active command submissions and event + handlers' follow-ups have successfully returned. + """ + self._run(RunLevel.RUN_FOREVER, *coroutines, + install_signal_handlers=install_signal_handlers) + LOG.info('The internal run_forever event loop has been shut down.')
+ +
[docs] async def aio_run(self, *coroutines, run_state: 'Optional[RunState]' = None) -> None: + """ + Coroutine where all network activity is scheduled from. This coroutine exits when + :meth:`shutdown` is called, and can be used directly as an asyncio-native alternative to + :meth:`start_in_background` and :meth:`join`. + + You would normally call this method directly only if you are trying to incorporate + the client into an already-running event loop. Prefer :meth:`run_until_complete` or + :meth:`run_forever` if you can block the current thread, or :meth:`start_in_background` + with :meth:`join` if you wish to run the entire client on background threads. + """ + await self._impl.aio_run(*coroutines, run_state=run_state) + LOG.info('The aio_run coroutine has completed.')
+ + # </editor-fold> + +
[docs] def parties(self) -> 'Collection[Party]': + """ + Return a snapshot of the set of parties that exist right now. + """ + return self._impl.parties()
+ +
[docs] def bots(self) -> 'Collection[Bot]': + return self._impl.bots()
+ + +
[docs]class GlobalClient: + """ + Public interface for either an async-based or a thread-safe version of an API for interacting + with a Ledger API implementation that manages global ledger data, such as package store + management and current time. + """ + + def __init__(self, impl: '_NetworkImpl'): + self._impl = impl
+ + +
[docs]class AIOGlobalClient(GlobalClient): + +
[docs] async def ensure_dar( + self, + contents: 'Union[str, Path, bytes, BinaryIO]', + timeout: 'TimeDeltaConvertible' = DEFAULT_TIMEOUT_SECONDS) -> None: + """ + Validate that the ledger has the packages specified by the given contents (as a byte array). + Throw an exception if the specified DARs do not exist within the specified timeout. + + :param contents: The DAR or DALF to ensure. + :param timeout: The maximum length of time to wait before giving up. + """ + raw_bytes = get_bytes(contents) + return await self._impl.upload_package(raw_bytes, timeout)
+ +
[docs] async def ensure_packages( + self, + package_ids: 'Collection[str]', + timeout: 'TimeDeltaConvertible' = DEFAULT_TIMEOUT_SECONDS) -> None: + """ + Validate that packages with the specified package IDs exist on the ledger. Throw an + exception if the specified packages do not exist within the specified timeout. + + :param package_ids: The set of package IDs to check for. + :param timeout: The maximum length of time to wait before giving up. + """ + return await self._impl.ensure_package_ids(package_ids, timeout)
+ +
[docs] async def metadata(self) -> LedgerMetadata: + """ + Return the current set of known packages. + """ + return await self._impl.aio_metadata()
+ +
[docs] async def get_time(self) -> datetime: + return await self._impl.get_time()
+ +
[docs] async def set_time(self, new_datetime: datetime) -> None: + await self._impl.set_time(new_datetime)
+ + +
[docs]class SimpleGlobalClient(GlobalClient): + +
[docs] def ensure_dar( + self, + contents: 'Union[str, Path, bytes, BinaryIO]', + timeout: 'TimeDeltaConvertible' = DEFAULT_TIMEOUT_SECONDS) -> None: + """ + Validate that the ledger has the packages specified by the given contents (as a byte array). + Throw an exception if the specified DARs do not exist within the specified timeout. + + :param contents: The DAR or DALF to ensure. + :param timeout: The maximum length of time to wait before giving up. + """ + raw_bytes = get_bytes(contents) + return self._impl.run_in_loop_threadsafe( + lambda: self._impl.upload_package(raw_bytes, timeout))
+ +
[docs] def ensure_packages( + self, + package_ids: 'Collection[str]', + timeout: 'TimeDeltaConvertible' = DEFAULT_TIMEOUT_SECONDS) -> None: + """ + Validate that packages with the specified package IDs exist on the ledger. Throw an + exception if the specified packages do not exist within the specified timeout. + + :param package_ids: The set of package IDs to check for. + :param timeout: The maximum length of time to wait before giving up. + """ + return self._impl.run_in_loop_threadsafe( + lambda: self._impl.ensure_package_ids(package_ids, timeout))
+ +
[docs] def metadata(self, timeout: 'TimeDeltaConvertible' = DEFAULT_TIMEOUT_SECONDS) \ + -> 'LedgerMetadata': + """ + Return the current set of known packages. + """ + return self._impl.simple_metadata(timeout)
+ +
[docs] def get_time(self) -> datetime: + return self._impl.run_in_loop_threadsafe(self._impl.get_time)
+ +
[docs] def set_time(self, new_datetime: datetime) -> None: + self._impl.run_in_loop_threadsafe(lambda: self._impl.set_time(new_datetime))
+ + +
[docs]class PartyClient: + """ + Public interface for either an async-based or a thread-safe version of an API for interacting + with a Ledger API implementation from the perspective of a single client. + """ + + def __init__(self, impl: '_PartyClientImpl'): + self._impl = impl + + # <editor-fold desc="Ledger/client metadata"> + + @property + def party(self) -> 'Party': + """ + Return the party serviced by this client. + """ + return self._impl.party + +
[docs] def resolved_config(self) -> 'PartyConfig': + """ + Calculate the configuration that will be used for this client when it is instantiated. + """ + return self._impl.resolved_config()
+ + # </editor-fold> + + +
[docs]class AIOPartyClient(PartyClient): + """ + Implementation of a :class:`PartyClient` that exposes an `async`/`await`-style API that runs on + an event loop. + """ + + # <editor-fold desc="Event handler registration"> + +
[docs] def ledger_init(self) -> 'AEventHandlerDecorator[InitEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has been + instructed to begin, but before any network activity is started. + """ + return fluentize(self.add_ledger_init)
+ +
[docs] def add_ledger_init(self, handler: 'AEventHandler[InitEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has been instructed to + begin, but before any network activity is started. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + for key in EventKey.init(): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_ready(self) -> 'AEventHandlerDecorator[ReadyEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has caught + up to the head of the ledger, but before any :meth:`ledger_create` or :meth:`ledger_archive` + callbacks are invoked. + """ + return fluentize(self.add_ledger_ready)
+ +
[docs] def add_ledger_ready(self, handler: 'AEventHandler[ReadyEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has caught up to the head of + the ledger, but before any :meth:`ledger_create` or :meth:`ledger_archive` callbacks are + invoked. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + for key in EventKey.ready(): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_packages_added(self, initial: bool = False) \ + -> 'AEventHandlerDecorator[PackagesAddedEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has + detected new packages added to the ledger. + + :param initial: + ``True`` to call the handler when the client is ready. This can be useful if you want + to handle package additions identically whether they were already in the ledger when + the client started up or only after a package has been added. The default value is + ``False``, which means that this handler is only called on NEW packages that have been + uploaded after this client has started. + :return: + """ + return fluentize(self.add_ledger_packages_added, initial=initial)
+ +
[docs] def add_ledger_packages_added( + self, handler: 'AEventHandler[PackagesAddedEvent]', initial: bool = False) -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has detected new packages + added to the ledger. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + :param initial: + ``True`` to call the handler when the client is ready. This can be useful if you want + to handle package additions identically whether they were already in the ledger when + the client started up or only after a package has been added. The default value is + ``False``, which means that this handler is only called on NEW packages that have been + uploaded after this client has started. + :return: + """ + for key in EventKey.packages_added(initial=initial, changed=True): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_transaction_start(self) -> 'AEventHandlerDecorator[TransactionStartEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` receives a + new transaction. Called before individual :meth:`ledger_create` and :meth:`ledger_archive` + callbacks. + """ + return fluentize(self.add_ledger_transaction_start)
+ +
[docs] def add_ledger_transaction_start(self, handler: 'AEventHandler[TransactionStartEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` receives a new transaction. + Called before individual :meth:`ledger_create` and :meth:`ledger_archive` callbacks. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + for key in EventKey.transaction_start(): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_transaction_end(self) -> 'AEventHandlerDecorator[TransactionEndEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` receives a + new transaction. Called after individual :meth:`ledger_create` and :meth:`ledger_archive` + callbacks. + """ + return fluentize(self.add_ledger_transaction_end)
+ +
[docs] def add_ledger_transaction_end(self, handler: 'AEventHandler[TransactionEndEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` receives a new transaction. + Called after individual :meth:`ledger_create` and :meth:`ledger_archive` callbacks. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + for key in EventKey.transaction_end(): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_created(self, template: Any, match: 'Optional[ContractMatch]' = None) \ + -> 'AEventHandlerDecorator[ContractCreateEvent]': + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly created + template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + def _register_created(cb: 'AEventHandler[ContractCreateEvent]') \ + -> 'AEventHandler[ContractCreateEvent]': + self.add_ledger_created(template, match=match, handler=cb) + return cb + + return _register_created
+ +
[docs] def add_ledger_created( + self, template: Any, handler: 'AEventHandler[ContractCreateEvent]', + match: 'Optional[ContractMatch]' = None) -> 'Bot': + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly created + contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param handler: + The callback to invoke whenever a matching template is created. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + bot = self._impl.bots.add_new(party_client=self, name=handler.__name__) + bot.add_event_handler(EventKey.contract_created(True, template), handler, match) + return bot
+ +
[docs] def ledger_exercised(self, template: Any, choice: str) \ + -> 'AEventHandlerDecorator[ContractExercisedEvent]': + """ + Register a callback to be invoked when the :class:`PartyClient` encounters an exercised + choice event. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param choice: + The name of the choice to listen for exercises on. + """ + def _register_exercised(cb: 'AEventHandler[ContractExercisedEvent]') \ + -> 'AEventHandler[ContractExercisedEvent]': + self.add_ledger_exercised(template, choice, handler=cb) + return cb + + return _register_exercised
+ +
[docs] def add_ledger_exercised( + self, template: Any, choice: str, handler: 'AEventHandler[ContractExercisedEvent]') \ + -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` encounters an exercised + choice event. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param choice: + The name of the choice to listen for exercises on. + :param handler: + The callback to invoke whenever a matching template is exercised. + """ + for key in EventKey.contract_exercised(True, template, choice): + self._impl.add_event_handler(key, handler, None, self)
+ +
[docs] def ledger_archived(self, template: Any, match: 'Optional[ContractMatch]' = None) \ + -> 'AEventHandlerDecorator[ContractArchiveEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` encounters + a newly archived contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + def _register_archived(cb: 'AEventHandler[ContractArchiveEvent]') \ + -> 'AEventHandler[ContractArchiveEvent]': + self.add_ledger_archived(template, match=match, handler=cb) + return cb + + return _register_archived
+ +
[docs] def add_ledger_archived( + self, template: Any, handler: 'AEventHandler[ContractArchiveEvent]', + match: 'Optional[ContractMatch]' = None) -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly archived + contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param handler: + The callback to invoke whenever a matching template is created. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + for key in EventKey.contract_archived(True, template): + self._impl.add_event_handler(key, handler, match, self)
+ + # </editor-fold> + + # <editor-fold desc="Command submission"> + +
[docs] def submit(self, commands: 'EventHandlerResponse', workflow_id: 'Optional[str]' = None) \ + -> 'Awaitable[None]': + """ + Submit commands to the ledger. + + :param commands: + An object that can be converted to a command. + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + :return: + A future that resolves when the command has made it to the ledger _or_ an error + occurred when trying to process them. + """ + return self._impl.write_commands(commands, workflow_id=workflow_id)
+ +
[docs] def submit_create( + self, + template_name: str, + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> 'Awaitable[None]': + """ + Submit a single create command. Equivalent to calling :meth:`submit` with a single + ``create``. + + :param template_name: + The name of the template. + :param arguments: + The arguments to the create (as a ``dict``). + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + :return: + A future that resolves when the command has made it to the ledger _or_ an error + occurred when trying to process them. + """ + from .. import create + return self.submit(create(template_name, arguments), workflow_id=workflow_id)
+ +
[docs] def submit_exercise( + self, + cid: 'ContractId', + choice_name: str, + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> 'Awaitable[None]': + """ + Submit a single exercise choice. Equivalent to calling :meth:`submit` with a single + ``exercise``. + + :param cid: + The :class:`ContractId` on which a choice is being exercised. + :param choice_name: + The name of the choice to exercise. + :param arguments: + The arguments to the exercise (as a ``dict``). Can be omitted (``None``) for no-argument + choices. + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + :return: + A future that resolves when the command has made it to the ledger _or_ an error + occurred when trying to process them. + """ + from .. import exercise + return self.submit(exercise(cid, choice_name, arguments), workflow_id=workflow_id)
+ +
[docs] def submit_exercise_by_key( + self, + template_name: 'TemplateNameLike', + contract_key: 'Any', + choice_name: str, + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> 'Awaitable[None]': + """ + Synchronously submit a single exercise choice. Equivalent to calling :meth:`submit` with a + single ``exercise_by_key``. + + :param template_name: + The name of the template on which to do an exercise-by-key. + :param contract_key: + The value that should uniquely identify a contract for the specified template. + :param choice_name: + The name of the choice to exercise. + :param arguments: + The arguments to the create (as a ``dict``). Can be omitted (``None``) for no-argument + choices. + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import exercise_by_key + return self.submit( + exercise_by_key(template_name, contract_key, choice_name, arguments), workflow_id=workflow_id)
+ +
[docs] def submit_create_and_exercise( + self, + template_name: 'TemplateNameLike', + arguments: 'dict', + choice_name: str, + choice_arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> 'Awaitable[None]': + """ + Synchronously submit a single create-and-exercise command. Equivalent to calling + :meth:`submit` with a single ``create_and_exercise``. + + :param template_name: + The name of the template on which to do an exercise-by-key. + :param arguments: + The arguments to the create (as a ``dict``). + :param choice_name: + The name of the choice to exercise. + :param choice_arguments: + The arguments to the exercise (as a ``dict``). Can be omitted (``None``) for no-argument + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import create_and_exercise + return self.submit( + create_and_exercise(template_name, arguments, choice_name, choice_arguments), + workflow_id=workflow_id)
+ + # </editor-fold> + + # <editor-fold desc="Active contract set"> + +
[docs] def find_by_id(self, cid: 'Union[str, ContractId]') -> 'Optional[ContractContextualData]': + return self._impl.find_by_id(cid)
+ +
[docs] def find(self, + template: Any, + match: 'ContractMatch' = None, + include_archived: bool = False) \ + -> ContractContextualDataCollection: + return self._impl.find(template, match, include_archived=include_archived)
+ +
[docs] def find_active(self, template: Any, match: 'ContractMatch' = None) -> 'ContractsState': + """ + Immediately return data from the current active contract set. + + The contents of this ACS are guaranteed to be present (or removed) in the current + transaction _before_ processing any corresponding ``on_created`` or ``on_archived`` + callbacks for this party. The ACS is populated _before_ processing any ``on_ready`` + callbacks. + + This method raises an error if ACS tracking has been disabled on this client. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :return: + A ``dict`` whose keys are :class:`ContractId` and values are corresponding contract + data that match the current query. + """ + return self._impl.find_active(template, match)
+ +
[docs] def find_historical(self, template: Any, match: 'ContractMatch' = None) \ + -> 'ContractContextualDataCollection': + """ + Immediately return data from the current active and historical contract set as + a contextual data collection + + The contents of this set are guaranteed to be up-to-date in the current transaction _before_ + processing any corresponding ``on_created`` or ``on_archived`` callbacks for this party. The + set is up-to-date _before_ processing any ``on_ready`` callbacks. + + This method raises an error if historical tracking has been disabled on this client. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :return: + A ``ContractContextualDataCollection`` whose values correspond to the contract + data for active and archived contracts matching the current query. + """ + return self._impl.find_historical(template, match)
+ +
[docs] def find_one(self, template: Any, match: 'ContractMatch' = None, + timeout: float = DEFAULT_TIMEOUT_SECONDS) \ + -> 'Awaitable[Tuple[ContractId, ContractData]]': + """ + Return data from the current active contract set when at least some amount of rows exist in + the active contract set. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :param timeout: + Number of seconds in which to time out the search. + :return: + A ``Future`` that is resolved with a ``dict`` whose keys are :class:`ContractId` and + values are corresponding contract data that match the current query. + """ + return await_then( + self.find_nonempty(template, match, min_count=1, timeout=timeout), + lambda state: next(iter(state.items())))
+ +
[docs] def find_nonempty( + self, template: 'Any', match: 'ContractMatch', min_count: int = 1, + timeout: float = DEFAULT_TIMEOUT_SECONDS) \ + -> 'Awaitable[ContractsState]': + """ + Return data from the current active contract set when at least some amount of rows exist in + the active contract set. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :param min_count: + The minimum number of rows to return. The default value is 1. + :param timeout: + Number of seconds in which to time out the search. + :return: + A ``Future`` that is resolved with a ``dict`` whose keys are :class:`ContractId` and + values are corresponding contract data that match the current query. + """ + return self._impl.find_nonempty(template, match, min_count, timeout)
+ + # </editor-fold> + + # <editor-fold desc="Ledger/client metadata"> + +
[docs] def set_config(self, url: 'Optional[str]', **kwargs): + self._impl.set_config(url=url, **kwargs)
+ +
[docs] def get_time(self) -> 'Awaitable[datetime]': + """ + Return the current time on the remote server. Also advance the local notion of time if + required. + """ + return self._impl.get_time()
+ +
[docs] def set_time(self, new_datetime: datetime) -> 'Awaitable[None]': + """ + Set the current time on the ledger. This is only supported if the ledger supports time + manipulation. + """ + return self._impl.set_time(new_datetime)
+ +
[docs] def ready(self) -> 'Awaitable[None]': + """ + Block until the ledger client has caught up to the current head and is ready to send + commands. + """ + return self._impl.ready()
+ + # </editor-fold> + + +
[docs]class SimplePartyClient(PartyClient): + """ + Implementation of a :class:`PartyClient` that exposes blocking calls, but can be used from any + thread. + + Use this implementation if any of these apply: + * you wish to interact with libraries that do not natively support asyncio + * you are comfortable with the trade-off of having to block threads in order to write code + """ + + # <editor-fold desc="Event handler registration"> + +
[docs] def ledger_init(self) -> 'EventHandlerDecorator[InitEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has been + instructed to begin, but before any network activity is started. + """ + return fluentize(self.add_ledger_init)
+ +
[docs] def add_ledger_init(self, handler: 'EventHandler[InitEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has been instructed to + begin, but before any network activity is started. + + :param handler: + The handler to register. May return anything that can be successfully coerced into a + :class:`CommandPayload`. + """ + @wraps(handler) + def _background_ledger_init(event: 'InitEvent') -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.init(): + self._impl.add_event_handler(key, _background_ledger_init, None, self)
+ +
[docs] def ledger_ready(self) -> 'EventHandlerDecorator[ReadyEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has caught + up to the head of the ledger, but before any :meth:`ledger_create` or :meth:`ledger_archive` + callbacks are invoked. + """ + return fluentize(self.add_ledger_ready)
+ +
[docs] def add_ledger_ready(self, handler: 'EventHandler[ReadyEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has caught up to the head of + the ledger, but before any :meth:`ledger_create` or :meth:`ledger_archive` callbacks are + invoked. + + :param handler: + The handler to register. May return anything that can be successfully coerced into a + :class:`CommandPayload`. + """ + @wraps(handler) + def _background_ledger_ready(event: 'ReadyEvent') -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.ready(): + self._impl.add_event_handler(key, _background_ledger_ready, None, self)
+ +
[docs] def ledger_packages_added(self, initial: bool = False) \ + -> 'EventHandlerDecorator[PackagesAddedEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` has + detected new packages added to the ledger. + + :param initial: + ``True`` to call the handler when the client is ready. This can be useful if you want + to handle package additions identically whether they were already in the ledger when + the client started up or only after a package has been added. The default value is + ``False``, which means that this handler is only called on NEW packages that have been + uploaded after this client has started. + :return: + """ + return fluentize(self.add_ledger_packages_added, initial=initial)
+ +
[docs] def add_ledger_packages_added( + self, handler: 'EventHandler[PackagesAddedEvent]', initial: bool = False) -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` has detected new packages + added to the ledger. + + :param handler: + The handler to register. May return anything that can be successfully coerced into a + :class:`CommandPayload`. + :param initial: + ``True`` to call the handler when the client is ready. This can be useful if you want + to handle package additions identically whether they were already in the ledger when + the client started up or only after a package has been added. The default value is + ``False``, which means that this handler is only called on NEW packages that have been + uploaded after this client has started. + :return: + """ + @wraps(handler) + def _background_ledger_packages_added(event: 'PackagesAddedEvent') \ + -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.packages_added(initial=initial, changed=True): + self._impl.add_event_handler(key, _background_ledger_packages_added, None, self)
+ +
[docs] def ledger_transaction_start(self) -> 'EventHandlerDecorator[TransactionStartEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` receives a + new transaction. Called before individual :meth:`ledger_create` and :meth:`ledger_archive` + callbacks. + """ + return fluentize(self.add_ledger_transaction_start)
+ +
[docs] def add_ledger_transaction_start(self, handler: 'EventHandler[TransactionStartEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` receives a new transaction. + Called before individual :meth:`ledger_create` and :meth:`ledger_archive` callbacks. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + @wraps(handler) + def _background_ledger_transaction_start(event: TransactionStartEvent) \ + -> Awaitable[EventHandlerResponse]: + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.transaction_start(): + self._impl.add_event_handler(key, _background_ledger_transaction_start, None, self)
+ +
[docs] def ledger_transaction_end(self) -> 'EventHandlerDecorator[TransactionEndEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` receives a + new transaction. Called after individual :meth:`ledger_create` and :meth:`ledger_archive` + callbacks. + """ + + def _register_transaction_end(cb: 'EventHandler[TransactionEndEvent]') \ + -> 'EventHandler[TransactionEndEvent]': + self.add_ledger_transaction_end(cb) + return cb + + return _register_transaction_end
+ +
[docs] def add_ledger_transaction_end(self, handler: 'EventHandler[TransactionEndEvent]') -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` receives a new transaction. + Called after individual :meth:`ledger_create` and :meth:`ledger_archive` callbacks. + + :param handler: + The handler to register. This can either be a coroutine or a normal function, and may + return anything that can be successfully coerced into a :class:`CommandPayload`. + """ + @wraps(handler) + def _background_ledger_transaction_end(event: 'TransactionEndEvent') \ + -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.transaction_end(): + self._impl.add_event_handler(key, _background_ledger_transaction_end, None, self)
+ +
[docs] def ledger_created(self, template: Any, match: 'Optional[ContractMatch]' = None) \ + -> 'EventHandlerDecorator[ContractCreateEvent]': + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly created + template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + + def _register_created(cb: 'EventHandler[ContractCreateEvent]') \ + -> 'EventHandler[ContractCreateEvent]': + self.add_ledger_created(template, match=match, handler=cb) + return cb + + return _register_created
+ +
[docs] def add_ledger_created( + self, template: 'Any', handler: 'EventHandler[ContractCreateEvent]', + match: 'Optional[ContractMatch]' = None) -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly created + contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param handler: + The callback to invoke whenever a matching template is created. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + @wraps(handler) + def _background_ledger_contract_create(event: 'ContractCreateEvent') \ + -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.contract_created(True, template): + self._impl.add_event_handler(key, _background_ledger_contract_create, match, self)
+ +
[docs] def ledger_exercised(self, template: 'Any', choice: str) \ + -> 'EventHandlerDecorator[ContractExercisedEvent]': + """ + Register a callback to be invoked when the :class:`PartyClient` encounters an exercised + choice event. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param choice: + The name of the choice to listen for exercises on. + """ + + def _register_exercised(cb: 'EventHandler[ContractExercisedEvent]') \ + -> 'EventHandler[ContractExercisedEvent]': + self.add_ledger_exercised(template, choice, handler=cb) + return cb + + return _register_exercised
+ +
[docs] def add_ledger_exercised( + self, template: Any, choice: str, handler: 'EventHandler[ContractExercisedEvent]') \ + -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` encounters an exercised + choice event. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param choice: + The name of the choice to listen for exercises on. + :param handler: + The callback to invoke whenever a matching template is exercised. + """ + @wraps(handler) + def _background_ledger_contract_exercised(event: 'ContractExercisedEvent') \ + -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.contract_exercised(True, template, choice): + self._impl.add_event_handler(key, _background_ledger_contract_exercised, None, self)
+ +
[docs] def ledger_archived(self, template: 'Any', match: 'Optional[ContractMatch]' = None) \ + -> 'EventHandlerDecorator[ContractArchiveEvent]': + """ + Decorator for registering a callback to be invoked when the :class:`PartyClient` encounters + a newly archived contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + + def _register_archived(cb: 'EventHandler[ContractArchiveEvent]') \ + -> 'EventHandler[ContractArchiveEvent]': + self.add_ledger_archived(template, match=match, handler=cb) + return cb + + return _register_archived
+ +
[docs] def add_ledger_archived( + self, template: 'Any', handler: 'EventHandler[ContractArchiveEvent]', + match: 'Optional[ContractMatch]' = None) -> None: + """ + Register a callback to be invoked when the :class:`PartyClient` encounters a newly archived + contract instance of a template. + + :param template: + A template name to subscribe to, or '*' to subscribe on all templates. + :param handler: + The callback to invoke whenever a matching template is created. + :param match: + An (optional) parameter that filters the templates to be received by the callback. + """ + @wraps(handler) + def _background_ledger_contract_archived(event: 'ContractArchiveEvent') \ + -> 'Awaitable[EventHandlerResponse]': + return self._impl.invoker.run_in_executor(lambda: handler(event)) + + for key in EventKey.contract_archived(True, template): + self._impl.add_event_handler(key, _background_ledger_contract_archived, match, self)
+ + # </editor-fold> + + # region Command submission + +
[docs] def submit_create( + self, + template_name: 'TemplateNameLike', + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) -> None: + """ + Synchronously submit a single create command. Equivalent to calling :meth:`submit` with a + single ``create``. + + :param template_name: + The name of the template. + :param arguments: + The arguments to the create (as a ``dict``). + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import create + return self.submit(create(template_name, arguments), workflow_id=workflow_id)
+ +
[docs] def submit_exercise( + self, + cid: 'ContractId', + choice_name: str, + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> None: + """ + Synchronously submit a single exercise choice. Equivalent to calling :meth:`submit` with a + single ``exercise``. + + :param cid: + The :class:`ContractId` on which a choice is being exercised. + :param choice_name: + The name of the choice to exercise. + :param arguments: + The arguments to the exercise (as a ``dict``). Can be omitted (``None``) for no-argument + choices. + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import exercise + return self.submit(exercise(cid, choice_name, arguments), workflow_id=workflow_id)
+ +
[docs] def submit_exercise_by_key( + self, + template_name: 'TemplateNameLike', + contract_key: 'Any', + choice_name: str, + arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> None: + """ + Synchronously submit a single exercise choice. Equivalent to calling :meth:`submit` with a + single ``exercise_by_key``. + + :param template_name: + The name of the template on which to do an exercise-by-key. + :param contract_key: + The value that should uniquely identify a contract for the specified template. + :param choice_name: + The name of the choice to exercise. + :param arguments: + The arguments to the create (as a ``dict``). Can be omitted (``None``) for no-argument + choices. + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import exercise_by_key + return self.submit( + exercise_by_key(template_name, contract_key, choice_name, arguments), + workflow_id=workflow_id)
+ +
[docs] def submit_create_and_exercise( + self, + template_name: 'TemplateNameLike', + arguments: 'dict', + choice_name: str, + choice_arguments: 'Optional[dict]' = None, + workflow_id: 'Optional[str]' = None) \ + -> None: + """ + Synchronously submit a single create-and-exercise command. Equivalent to calling + :meth:`submit` with a single ``create_and_exercise``. + + :param template_name: + The name of the template on which to do an exercise-by-key. + :param arguments: + The arguments to the create (as a ``dict``). + :param choice_name: + The name of the choice to exercise. + :param choice_arguments: + The arguments to the exercise (as a ``dict``). Can be omitted (``None``) for no-argument + :param workflow_id: + The optional workflow ID to stamp on the outgoing command. + """ + from .. import create_and_exercise + return self.submit( + create_and_exercise(template_name, arguments, choice_name, choice_arguments), + workflow_id=workflow_id)
+ + # endregion + + # <editor-fold desc="Active contract set"> + +
[docs] def find_by_id(self, cid: 'Union[str, ContractId]') -> 'Optional[ContractContextualData]': + return self._impl.invoker.run_in_loop(lambda: self._impl.find_by_id(cid))
+ +
[docs] def find(self, + template: Any, + match: ContractMatch = None, + include_archived: bool = False) \ + -> ContractContextualDataCollection: + return self._impl.invoker.run_in_loop( + lambda: self._impl.find(template, match, include_archived=include_archived))
+ +
[docs] def find_active(self, template: Any, match: ContractMatch = None) -> ContractsState: + """ + Immediately return data from the current active contract set. + + The contents of this ACS are guaranteed to be present (or removed) in the current + transaction _before_ processing any corresponding ``on_created`` or ``on_archived`` + callbacks for this party. The ACS is populated _before_ processing any ``on_ready`` + callbacks. + + This method raises an error if ACS tracking has been disabled on this client. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :return: + A ``dict`` whose keys are :class:`ContractId` and values are corresponding contract + data that match the current query. + :return: + A ``dict`` whose keys are :class:`ContractId` and values are corresponding contract + data that match the current query. + """ + return self._impl.invoker.run_in_loop(lambda: self._impl.find_active(template, match))
+ +
[docs] def find_historical(self, template: Any, match: ContractMatch = None) \ + -> ContractContextualDataCollection: + """ + Immediately return data from the current active and historical contract set. + + The contents of this set are guaranteed to be up-to-date in the current transaction _before_ + processing any corresponding ``on_created`` or ``on_archived`` callbacks for this party. The + set is up-to-date _before_ processing any ``on_ready`` callbacks. + + This method raises an error if historical tracking has been disabled on this client. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :return: + A ``dict`` whose keys are :class:`ContractId` and values are corresponding contract + data that match the current query. + :return: + A ``dict`` whose keys are :class:`ContractId` and values are corresponding contract + data that match the current query. + """ + return self._impl.invoker.run_in_loop(lambda: self._impl.find_historical(template, match))
+ +
[docs] def find_one(self, template: Any, match: ContractMatch = None, + timeout: float = DEFAULT_TIMEOUT_SECONDS) \ + -> Tuple[ContractId, ContractData]: + """ + Return data from the current active contract set when at least some amount of rows exist in + the active contract set. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :param timeout: + Number of seconds in which to time out the search. + :return: + A ``Future`` that is resolved with a ``dict`` whose keys are :class:`ContractId` and + values are corresponding contract data that match the current query. + """ + state = self.find_nonempty(template, match, min_count=1, timeout=timeout) + return next(iter(state.items()))
+ +
[docs] def find_nonempty(self, template: Any, match: ContractMatch, min_count: int = 1, + timeout: float = DEFAULT_TIMEOUT_SECONDS) \ + -> ContractsState: + """ + Return data from the current active contract set when at least some amount of rows exist in + the active contract set. + + :param template: + The name of the template to fetch data from. + :param match: + An optional dictionary whose keys are matched against corresponding field values. + :param min_count: + The minimum number of rows to return. The default value is 1. + :param timeout: + Number of seconds in which to time out the search. + :return: + A ``Future`` that is resolved with a ``dict`` whose keys are :class:`ContractId` and + values are corresponding contract data that match the current query. + """ + return self._impl.invoker.run_in_loop( + lambda: self._impl.find_nonempty(template, match, min_count=min_count, timeout=timeout))
+ + # </editor-fold> + + # <editor-fold desc="Ledger/client metadata"> + +
[docs] def set_config(self, url: Optional[str], **kwargs): + self._impl.set_config(url=url, **kwargs)
+ +
[docs] def get_time(self) -> datetime: + return self._impl.invoker.run_in_loop(lambda: self._impl.get_time())
+ +
[docs] def set_time(self, new_datetime: datetime) -> None: + return self._impl.invoker.run_in_loop(lambda: self._impl.set_time(new_datetime))
+ +
[docs] def submit(self, commands, workflow_id: str = None) -> None: + return self._impl.invoker.run_in_loop(lambda: self._impl.write_commands(commands, workflow_id=workflow_id))
+ +
[docs] def ready(self) -> None: + """ + Block until the underlying infrastructure has connected to all necessary services. + """ + # TODO: Improve on this implementation; this spin loop is unnecessarily ugly + from time import sleep + while self._impl.invoker.get_loop() is None: + sleep(0.1) + + LOG.debug('Waiting for the underlying implementation to be ready...') + return self._impl.invoker.run_in_loop(lambda: self._impl.ready())
+ + # </editor-fold> +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/client/bots.html b/docs/_modules/dazl/client/bots.html new file mode 100644 index 00000000..da09bf50 --- /dev/null +++ b/docs/_modules/dazl/client/bots.html @@ -0,0 +1,593 @@ + + + + + + + + dazl.client.bots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.client.bots

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+import inspect
+import operator
+from abc import abstractmethod
+from asyncio import ensure_future, Future, gather, get_event_loop, InvalidStateError
+from collections import defaultdict
+from dataclasses import dataclass, field, replace
+from datetime import timedelta
+from enum import auto, Enum
+from functools import wraps
+from threading import RLock
+from typing import overload, AbstractSet, Any, Awaitable, Callable, Collection, DefaultDict, List, \
+    Optional, Sequence, TypeVar, Union, TYPE_CHECKING
+from uuid import uuid4
+
+from .. import LOG
+from ..model.core import Party, SourceLocation
+from ..model.reading import BaseEvent, EventKey
+from ..model.writing import Command, CommandBuilder
+from ..util.asyncio_util import LongRunningAwaitable, completed, propagate, failed, Signal
+
+if TYPE_CHECKING:
+    from .api import PartyClient
+
+DEFAULT_BOT_STOP_TIMEOUT = timedelta(seconds=30)
+
+
+E = TypeVar('E', bound=BaseEvent)
+BotCallback = Callable[[E], Any]
+BotFilter = Callable[[E], bool]
+
+
+class _BotRunLevel(Enum):
+    CONTINUE = auto()
+    SUSPEND = auto()
+    TERMINATE = auto()
+
+
+
[docs]class Bot: + def __init__(self, party_client: 'Optional[PartyClient]', name: str): + self._handlers: DefaultDict[str, List[BotEntry]] = defaultdict(list) + self._party_client = party_client + self._id = uuid4().hex + self._name = name + self._queue = [] + self._signal = None # type: Optional[Signal] + self._idle = True + self._run_level = _BotRunLevel.CONTINUE + +
[docs] def event_keys(self) -> 'AbstractSet[str]': + """ + Return the set of keys that event handlers in this bot are configured to handle. + """ + return frozenset(self._handlers)
+ +
[docs] def wants_any_keys(self, keys: 'Collection[str]') -> bool: + return bool(set(keys).intersection(self._handlers))
+ +
[docs] def add_event_handler( + self, keys: 'Union[str, Collection[str]]', handler: 'BotCallback', + filter_fn: 'Optional[BotFilter]' = None) -> None: + """ + Add a new event handler to this bot for the specified event. + + :param keys: + The key(s) of the event (as returned by :meth:`EventKey.from_event`). + :param filter_fn: + An optional callback that returns `True` or `False` on whether the corresponding + callback should be invoked. This cannot be a coroutine function. + :param handler: + An event handler to be invoked when an event with the specified key is raised. + """ + if isinstance(keys, str): + keys = [keys] + else: + keys = tuple(keys) + for key in keys: + if not isinstance(key, str): + raise ValueError('expected a string key') + if not callable(handler): + raise ValueError('handler must be callable') + + # noinspection PyBroadException + try: + source_file = inspect.getsourcefile(inspect.unwrap(handler)) + lines, start_line = inspect.getsourcelines(handler) + end_line = start_line + len(lines) + source_loc = SourceLocation(source_file, start_line, end_line) + except Exception: # noqa + LOG.warning('Could not compute original source information for %r', handler, exc_info=True) + source_loc = None + + if self._party_client is not None: + # noinspection PyProtectedMember + impl = self._party_client._impl + handler = wrap_as_command_submission(impl.write_commands, handler, filter_fn) + + for key in keys: + self._handlers[key].append(BotEntry(key, handler, filter_fn, source_loc))
+ +
[docs] def ledger_created(self, template: Any): + def _register_created(fn): + self.add_event_handler(EventKey.contract_created(True, template), fn) + return _register_created
+ + async def _main(self): + """ + The "main" coroutine of the bot. Invokes handlers on each event as they come in. + """ + # noinspection PyBroadException + try: + self._signal = Signal() + while self._run_level != _BotRunLevel.TERMINATE: + # the main queue contains either events we have not yet processed yet or ``None`` + # markers that merely indicate running status should be "re-checked" + self._idle = False + while self._queue: + invocation = self._queue.pop(0) + # noinspection PyBroadException + try: + fut = ensure_future(self._handle_event(invocation.event)) + propagate(fut, invocation.future) + await invocation.future + except Exception: # noqa + LOG.exception(f'An event handler in a bot has thrown an exception! ' + f'(offending event: {invocation.event})') + self._idle = True + await self._signal.wait() + self._signal = None + except Exception: # noqa + LOG.exception('A bot thread died abnormally.') + + async def _handle_event(self, event: 'BaseEvent') -> None: + """ + Process an event, mostly by calling appropriate callbacks. + + :param event: The event to process. + """ + # The _PartyClientImpl and Bot classes are the ones raising events, but to the user, they + # registered from the perspective of a client with a certain thread affinity. Replace the + # "source" of the event with the client that the user originally used. + if self._party_client is not None: + new_event = replace(event, client=self._party_client) + else: + new_event = event + + for event_key in EventKey.from_event(new_event): + LOG.debug('Party %s dispatching event %r to its bots...', self.party, event_key) + handlers = self._handlers.get(event_key) + if handlers is not None: + for handler in handlers: + # noinspection PyBroadException + try: + if handler.filter is None or handler.filter(new_event): + await handler.callback(new_event) + except Exception: # noqa + LOG.exception('An event handler in a bot has thrown an exception!') + +
[docs] def notify(self, event: 'BaseEvent') -> 'Awaitable[None]': + """ + Notifies handler(s) associated with this bot that the given event has occurred. Note that + this notification is asynchronous: in other words, event handlers will not have processed + this event by the time this function returns. + + :param event: The event to raise. + """ + if not isinstance(event, BaseEvent): + raise ValueError('expected a BaseEvent') + + if self._queue is None: + raise InvalidStateError('Cannot notify on a bot whose main method is not running') + bot_invocation = BotInvocation(event) + self._queue.append(bot_invocation) + if self._signal is not None: + self._signal.notify_all() + return bot_invocation.future
+ + def _dispatch(self, event: 'BaseEvent') -> None: + for event_key in EventKey.from_event(event): + self._handlers.get(event_key) + + # <editor-fold desc="State control functions"> + +
[docs] def pause(self) -> None: + """ + Immediately change the state of this bot to ``PAUSING``, and pause event handler + invocations. The event handler currently running is allowed to complete. When that is + completed, the state is changed to ``PAUSED``. + """ + LOG.info('Pausing the bot thread for party %r...', self.party) + self._run_level = _BotRunLevel.SUSPEND + if self._signal is not None: + self._signal.notify_all()
+ +
[docs] def resume(self) -> None: + """ + Immediately change the state of this bot to ``RESUMING`` and process any events that have + queued up while the bot was paused. When this queue is fully drained, the state is changed + to ``RUNNING``. + """ + LOG.info('Resuming the bot thread for party %r...', self.party) + self._run_level = _BotRunLevel.CONTINUE + if self._signal is not None: + self._signal.notify_all()
+ +
[docs] def stop(self): + """ + Permanently stop this bot. If you need to be able to "restart" a stopped bot, use + :meth:`pause` and :meth:`resume` instead. + """ + LOG.info('Stopping the bot thread for party %r...', self.party) + self._run_level = _BotRunLevel.TERMINATE + if self._signal is not None: + self._signal.notify_all()
+ + # </editor-fold> + + # <editor-fold desc="State query properties/functions"> + + @property + def id(self) -> str: + """ + The ID of this bot, generated at runtime. + """ + return self._id + + @property + def name(self): + """ + The name of this bot. Defaults to the name of the original event handler if unspecified. + """ + return self._name + + @property + def party(self) -> 'Party': + """ + Primary party that this bot receives events for (and potentially generates commands for). + """ + return self._party_client.party if self._party_client is not None else None + +
[docs] def entries(self) -> 'Sequence[BotEntry]': + """ + The collection of individual event handlers in a bot, in the order that they will be + executed. + """ + return tuple(entry for collection in self._handlers.values() for entry in collection)
+ + @property + def state(self) -> 'BotState': + """ + Current running state of the bot. + """ + if self._run_level == _BotRunLevel.CONTINUE: + return BotState.RUNNING if self._signal is not None else BotState.STARTING + elif self._run_level == _BotRunLevel.TERMINATE: + return BotState.STOPPED if self._idle else BotState.STOPPING + elif self._run_level == _BotRunLevel.SUSPEND: + return BotState.PAUSED if self._idle else BotState.PAUSING + + @property + def running(self) -> bool: + """ + Return ``True`` if this bot is currently processing events. + """ + return self._signal is not None and \ + (self._run_level == _BotRunLevel.CONTINUE or not self._idle)
+ + # </editor-fold> + + +
[docs]class BotCollection(Sequence[Bot]): + """ + A collection of bots for a party. + + This class is thread-safe except for :meth:`notify` and :meth:`_main` in order to support adding + event handlers from any thread. The most common use of this is for ``SimplePartyClient`` + instances, where event registration is done from the main thread (from the perspective of the + caller) and event notifications are done on an asyncio event loop thread (hidden from the + caller). + """ + + def __init__(self, party: 'Optional[Party]'): + self.party = party + self._bots = [] # type: List[Bot] + self._fut = None # type: Optional[LongRunningAwaitable] + self._lock = RLock() + + def __len__(self) -> int: + with self._lock: + return len(self._bots) + + @overload + @abstractmethod + def __getitem__(self, i: int) -> Bot: ... + + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[Bot]: ... + + def __getitem__(self, i: int) -> Bot: + with self._lock: + return operator.getitem(self._bots, i) + + def __iter__(self): + with self._lock: + bots = list(self._bots) + return iter(bots) + +
[docs] def add_new(self, name: str, party_client: 'Optional[PartyClient]' = None) -> 'Bot': + bot = Bot(party_client, name) + with self._lock: + self._bots.append(bot) + if self._fut is not None: + # the _main coroutine has already started, so just add this bot's main method to the + # set of coroutines we track + # noinspection PyProtectedMember + self._fut.append(ensure_future(bot._main())) + return bot
+ +
[docs] def add_single( + self, + keys: 'Union[str, Sequence[str]]', + handler: 'BotCallback', + filter_fn: 'Optional[BotFilter]' = None, + name: 'Optional[str]' = None, + party_client: 'Optional[PartyClient]' = None) -> 'Bot': + """ + Convenience method for creating a bot with a single event handler. + """ + if name is None: + # by default, the name of a single-event-handler bot is simply the name of the passed + # in function + name = handler.__name__ + if isinstance(keys, str): + keys = [keys] + + bot = self.add_new(name, party_client) + for key in keys: + bot.add_event_handler(key, handler, filter_fn) + return bot
+ +
[docs] def notify(self, event: 'BaseEvent'): + futures = [] + try: + event_keys = EventKey.from_event(event) + for bot in self._bots: + if bot.wants_any_keys(event_keys): + futures.append(ensure_future(bot.notify(event))) + except: # noqa + # This exception indicates a problem with the scheduling code and not user bot code. + # Exceptions thrown by user code would be propagated through the Future + LOG.exception('Failed to notify event for party %s: %r', self.party, event) + raise + + if len(futures) == 0: + return completed(None) + elif len(futures) == 1: + return futures[0] + else: + return gather(*futures, return_exceptions=True)
+ + async def _main(self): + if self.party is not None: + LOG.info('Party %s bots coroutine started.', self.party) + else: + LOG.info('Network bots coroutine started.') + + with self._lock: + self._fut = LongRunningAwaitable() + # noinspection PyProtectedMember + self._fut.extend(ensure_future(bot._main()) for bot in self._bots) + + await self._fut + + with self._lock: + self._fut = None + + if self.party is not None: + LOG.info('Party %s bots coroutine finished.', self.party) + else: + LOG.info('Network bots coroutine finished.') + +
[docs] def stop_all(self): + with self._lock: + # LongRunningAwaitable suspends itself until all futures are completed. It also keeps + # itself open waiting for the very first future. In the case that no other futures have + # been added, take this opportunity to feed LongRunningAwaitable a future that + # immediately resolves, which will have the effect of resolving that overall future + # if there are no other futures (or the other futures are resolved as well); otherwise + # this has no effect. + self._fut.append(completed(None)) + for bot in list(self._bots): + bot.stop() + self._bots.clear()
+ + +
[docs]@dataclass(frozen=True) +class BotEntry: + event_key: str + callback: BotCallback + filter: Optional[BotFilter] = None + source_location: Optional[SourceLocation] = None
+ + +
[docs]@dataclass(frozen=True) +class BotInvocation: + event: BaseEvent + future: Future = field(default_factory=lambda: get_event_loop().create_future())
+ + +
[docs]class BotState(Enum): + """ + Possible states of a :class:`Bot`. + """ + + STARTING = 'STARTING' #: The bot is starting (has not yet received the "ready" event). + PAUSING = 'PAUSING' #: This bot has been told to pause, but has not yet completed processing events in flight. + PAUSED = 'PAUSED' #: + RESUMING = 'RESUMING' + RUNNING = 'RUNNING' + STOPPING = 'STOPPING' + STOPPED = 'STOPPED'
+ + +# noinspection PyShadowingBuiltins +
[docs]def wrap_as_command_submission(submit_fn, callback, filter) \ + -> Callable[[BaseEvent], Awaitable[Any]]: + """ + Normalize a callback to something that takes a single contract ID and contract data, and + return an awaitable that is resolved when the underlying command has been fully submitted. + """ + import inspect + + @wraps(callback) + def implementation(*args, **kwargs): + if filter is not None and not filter(*args, **kwargs): + return completed(None) + + try: + ret = callback(*args, **kwargs) + except BaseException as exception: + LOG.exception('The callback %r threw an exception!', callback) + return failed(exception) + + if ret is None: + return completed(None) + elif isinstance(ret, (CommandBuilder, Command, list, tuple)): + try: + ret_fut = submit_fn(ret) + except BaseException as exception: + LOG.exception('The callback %r returned commands that could not be submitted! (%s)', + callback, ret) + return failed(exception) + return ret_fut + elif inspect.isawaitable(ret): + # the user-provided callback returned an Awaitable + cmd_fut = ensure_future(ret) + if cmd_fut.done(): + if cmd_fut.cancelled() or cmd_fut.exception() is not None: + # a cancelled or failed user-provided callback Future is the same as the + # command submission itself failing + return cmd_fut + + # functionally equivalent to the non-Awaitable case if the Awaitable has already + # completed + return submit_fn(cmd_fut.result()) + else: + # create `fut`, which we'll give to the user; wait for `cmd_fut` to finish, then + # take the result of that awaitable and try to submit a command with that result + fut = get_event_loop().create_future() + + def cmd_future_finished(_): + ret = cmd_fut.result() + if ret is None: + fut.set_result(None) + elif isinstance(ret, (CommandBuilder, Command, list, tuple)): + propagate(ensure_future(submit_fn(ret)), fut) + elif inspect.isawaitable(ret): + LOG.error('A callback cannot return an Awaitable of an Awaitable') + raise InvalidStateError( + 'A callback cannot return an Awaitable of an Awaitable') + + cmd_fut.add_done_callback(cmd_future_finished) + + return fut + else: + LOG.error('the callback %r returned a value of an unexpected type: %s', callback, ret) + raise ValueError('unexpected return type from a callback') + + return implementation
+
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/model/core.html b/docs/_modules/dazl/model/core.html new file mode 100644 index 00000000..f1b4be47 --- /dev/null +++ b/docs/_modules/dazl/model/core.html @@ -0,0 +1,357 @@ + + + + + + + + dazl.model.core + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.model.core

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+Core types
+----------
+
+The :mod:`dazl.model.core` module contains classes used on both the read-side and the write-side of
+the Ledger API.
+
+.. autoclass:: ContractId
+   :members:
+"""
+import warnings
+from dataclasses import dataclass
+from typing import Any, Callable, Collection, Dict, List, NewType, Optional, Tuple, TypeVar, \
+    Union, TYPE_CHECKING
+from datetime import datetime
+
+from ..util.enum import OrderedEnum
+
+if TYPE_CHECKING:
+    from .types import Type
+
+T = TypeVar('T')
+
+
+
[docs]class ContractId: + """ + There are two kinds of contract IDs: those that know the template type of the underlying + contract instance and those that don't. Contract IDs that arise from event processing are always + tagged with their type when they are read off the event stream. Contract IDs that are + parameters to a template are not currently tagged with a template type. + + Instance attributes: + + .. attribute:: ContractId.contract_id + + A ``str`` reference to a contract. + + .. attribute:: ContractId.template_id + + An optional ``str`` template ID. + + Instance members: + """ + __slots__ = ('contract_id', 'template_id') + + def __init__(self, contract_id: str, template_id: 'Union[None, str, Type]' = None): + from .types import Type, UnresolvedTypeReference + if not isinstance(contract_id, str): + raise ValueError('contract_id must be a string') + + if template_id is None: + warnings.warn('Untyped ContractId support will be removed with the removal of ' + 'the deprecated REST API.', DeprecationWarning, stacklevel=2) + else: + if isinstance(template_id, str): + template_id = UnresolvedTypeReference(template_id) + elif not isinstance(template_id, Type): + raise ValueError(f'template_id must either be unspecified or a template identifier ' + f'(got {repr(template_id)})') + + self.contract_id = contract_id + self.template_id = template_id + + def __str__(self): + """ + Return the contract ID without a type adornment. + """ + return self.contract_id + + def __repr__(self): + if self.template_id is not None: + return '<ContractId("{}<{}>")>'.format(self.contract_id, self.template_id) + else: + return '<ContractId("{}")>'.format(self.contract_id) + + def __eq__(self, other): + """ + Returns whether this contract is the same as the other one. Template + type is NOT considered in equality. + """ + return isinstance(other, ContractId) and self.contract_id == other.contract_id + + def __format__(self, format_spec): + return ('{:' + format_spec + 's}').format(self.contract_id) + + def __hash__(self): + """ + Returns a hash of the ContractId (based on the value of ContractId). + """ + return hash(self.contract_id) + +
[docs] def exercise(self, choice_name, arguments=None): + """ + Create an :class:`ExerciseCommand` that represents the result of exercising a choice on this + contract with the specified choice. + + :param choice_name: + The name of the choice to exercise. + :param arguments: + (optional) A ``dict`` of named values to send as parameters to the choice exercise. + """ + from .writing import ExerciseCommand + return ExerciseCommand(self, choice_name, arguments=arguments)
+ +
[docs] def replace(self, contract_id=None, template_id=None): + """ + Return a new :class:`ContractId` instance replacing specified fields with values. + """ + return ContractId( + contract_id if contract_id is not None else self.contract_id, + template_id if template_id is not None else self.template_id)
+ +
[docs] def for_json(self): + """ + Return the JSON representation of this contract. This is currently just the contract ID + string itself. + """ + return self.contract_id
+ + +ContractData = Dict[str, Any] +ContractMatch = Union[None, Callable[[ContractData], bool], ContractData] +ContractsState = Dict[ContractId, ContractData] +ContractsHistoricalState = Dict[ContractId, Tuple[ContractData, bool]] +Party = NewType('Party', str) + + +class ContractContextualDataCollection(tuple): + + def __getitem__(self, index: Union[int, str, ContractId]): + if index is None: + raise ValueError('the index cannot be None') + elif isinstance(index, int): + return tuple.__getitem__(self, index) + elif isinstance(index, str): + for cxd in self: + if cxd.cid.contract_id == index: + return cxd + raise KeyError(index) + elif isinstance(index, ContractId): + for cxd in self: + if cxd.cid == index: + return cxd + raise KeyError(index) + else: + raise TypeError("cannot index into a ContractContextualDataCollection with {index!r}") + + +@dataclass(frozen=True) +class ContractContextualData: + cid: ContractId + cdata: 'Optional[ContractData]' + effective_at: datetime + archived_at: 'Optional[datetime]' + active: bool + + +@dataclass(frozen=True) +class SourceLocation: + file_name: str + start_line: int + end_line: int + + +class RunLevel(OrderedEnum): + RUN_FOREVER = 0 + RUN_UNTIL_IDLE = 1 + TERMINATE_GRACEFULLY = 2 + TERMINATE_IMMEDIATELY = 3 + STOPPED = 4 + + +class DazlError(Exception): + """ + Superclass of errors raised by dazl. + """ + + +class DazlWarning(Warning): + """ + Superclass of warnings raised by dazl. + """ + + +class DazlPartyMissingError(DazlError): + """ + Error raised when a party or some information about a party is requested, and that party is not + found. + """ + def __init__(self, party: Party): + super().__init__(f'party {party!r} does not have a defined client') + self.party = party + + +class DazlImportError(ImportError, DazlError): + """ + Import error raised when an optional dependency could not be found. + """ + def __init__(self, missing_module, message): + super().__init__(message) + self.missing_module = missing_module + + +class UserTerminateRequest(DazlError): + """ + Raised when the user has initiated a request to terminate the application. + """ + + +class ConnectionTimeoutError(DazlError): + """ + Raised when a connection failed to be established before the connection timeout elapsed. + """ + + +class CommandTimeoutError(DazlError): + """ + Raised when a corresponding event for a command was not seen in the appropriate time window. + """ + + +class ConfigurationError(DazlError): + """ + Raised when a configuration error prevents a client from being started. + + .. attribute:: ConfigurationError.reasons + + A collection of reasons for a failure. + """ + def __init__(self, reasons: 'Union[str, Collection[str]]'): + if reasons is None: + self.reasons = [] # type: List[str] + elif isinstance(reasons, str): + self.reasons = [reasons] + else: + self.reasons = reasons # type: List[str] + + +class ConnectionClosedError(DazlError): + """ + Raised when trying to do something that requires a connection after connection pools have been + closed. + """ + + +class UnknownTemplateWarning(DazlWarning): + """ + Raised when trying to do something with a template name that is unknown. + """ + + +class ProcessDiedException(DazlError): + pass +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/model/types.html b/docs/_modules/dazl/model/types.html new file mode 100644 index 00000000..f6b4988e --- /dev/null +++ b/docs/_modules/dazl/model/types.html @@ -0,0 +1,1077 @@ + + + + + + + + dazl.model.types + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.model.types

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+Type system types
+------------------
+
+The :mod:`dazl.model.types` module contains the Python classes used to represent the DAML type
+system.
+
++----------------------+---------------------------+
+| DAML type            | Python type               |
++======================+===========================+
+| ``Bool``             | ``bool``                  |
++----------------------+---------------------------+
+| ``Int``              | ``int``                   |
++----------------------+---------------------------+
+| ``Decimal``          | ``decimal.Decimal``       |
++----------------------+---------------------------+
+| ``[a]``              | ``list``                  |
++----------------------+---------------------------+
+
+.. autoclass:: Type
+.. autoclass:: ScalarType
+.. autoclass:: ListType
+.. autoclass:: RecordType
+.. autoclass:: VariantType
+.. autoclass:: UnsupportedType
+"""
+
+from enum import Flag
+from typing import Any, Callable, Collection, Dict, Optional, Sequence, Tuple, TypeVar, Union, \
+    TYPE_CHECKING
+
+from .. import LOG
+from ..model.core import ContractData, Party
+from ..util.typing import safe_cast, safe_dict_cast, safe_optional_cast
+
+DottedNameish = Union[str, Sequence[str]]
+
+T_co = TypeVar('T_co', covariant=True)
+
+if TYPE_CHECKING:
+    from .types_store import PackageStore
+    from ..damlast.daml_lf_1 import Expr
+
+
+def dotted_name(obj: DottedNameish) -> Sequence[str]:
+    """
+    Sanitize a string or a tuple of strings to a dotted name.
+
+    :param obj: A string or tuple of strings.
+    :return: A tuple of strings.
+    """
+    if obj is None:
+        raise ValueError('DottedName must be a non-None value')
+    if isinstance(obj, str):
+        return tuple(obj.split('.'))
+    if isinstance(obj, Collection):
+        for item in obj:
+            if not isinstance(item, str):
+                raise ValueError("DottedName's components must all be strings")
+        return tuple(obj)
+    else:
+        raise ValueError('could not convert to a sequence of str: {obj!r}')
+
+
+class NamedArgumentList(tuple):
+    """
+    A simple tuple to storing (name, value) pairs.
+    """
+
+    @property
+    def names(self):
+        return set(name for name, _ in self)
+
+
+def type_dispatch_table(
+        on_type_ref: Callable[['TypeReference'], T_co],
+        on_type_var: Callable[['TypeVariable'], T_co],
+        on_type_app: Callable[['TypeApp'], T_co],
+        on_scalar: Callable[['ScalarType'], T_co],
+        on_contract_id: Callable[['ContractIdType'], T_co],
+        on_optional: Callable[['OptionalType'], T_co],
+        on_list: Callable[['ListType'], T_co],
+        on_text_map: 'Callable[[TextMapType], T_co]',
+        on_record: Callable[['RecordType'], T_co],
+        on_variant: Callable[['VariantType'], T_co],
+        on_enum: 'Callable[[EnumType], T_co]',
+        on_unsupported: Callable[['UnsupportedType'], T_co]) -> Callable[['Type'], T_co]:
+    def _impl(tt: Type):
+        if isinstance(tt, TypeReference):
+            return on_type_ref(tt)
+        elif isinstance(tt, TypeVariable):
+            return on_type_var(tt)
+        elif isinstance(tt, TypeApp):
+            return on_type_app(tt)
+        elif isinstance(tt, ScalarType):
+            return on_scalar(tt)
+        elif isinstance(tt, ContractIdType):
+            return on_contract_id(tt)
+        elif isinstance(tt, OptionalType):
+            return on_optional(tt)
+        elif isinstance(tt, ListType):
+            return on_list(tt)
+        elif isinstance(tt, TextMapType):
+            return on_text_map(tt)
+        elif isinstance(tt, RecordType):
+            return on_record(tt)
+        elif isinstance(tt, VariantType):
+            return on_variant(tt)
+        elif isinstance(tt, EnumType):
+            return on_enum(tt)
+        elif isinstance(tt, UnsupportedType):
+            return on_unsupported(tt)
+        else:
+            # note to maintainers: if you modify the Type hierarchy, you must also maintain this
+            # poor man's pattern match over the hierarchy
+            LOG.error('Incomplete implementation of type_match! (when handling %r)', tt)
+            raise Exception(f'unknown Type subclass: {tt!r}')
+    return _impl
+
+
+def scalar_type_dispatch_table(
+        on_unit: 'Callable[[], T_co]',
+        on_bool: 'Callable[[], T_co]',
+        on_text: 'Callable[[], T_co]',
+        on_int: 'Callable[[], T_co]',
+        on_decimal: 'Callable[[], T_co]',
+        on_party: 'Callable[[], T_co]',
+        on_date: 'Callable[[], T_co]',
+        on_datetime: 'Callable[[], T_co]',
+        on_timedelta: 'Callable[[], T_co]') -> 'Callable[[ScalarType], T_co]':
+    def _impl(tt: ScalarType):
+        st = safe_cast(ScalarType, tt)
+        if st == SCALAR_TYPE_UNIT:
+            return on_unit()
+        elif tt == SCALAR_TYPE_BOOL:
+            return on_bool()
+        elif tt == SCALAR_TYPE_TEXT or tt == SCALAR_TYPE_CHAR:
+            return on_text()
+        elif tt == SCALAR_TYPE_INTEGER:
+            return on_int()
+        elif tt == SCALAR_TYPE_DECIMAL:
+            return on_decimal()
+        elif tt == SCALAR_TYPE_PARTY:
+            return on_party()
+        elif tt == SCALAR_TYPE_DATE:
+            return on_date()
+        elif tt == SCALAR_TYPE_DATETIME:
+            return on_datetime()
+        elif tt == SCALAR_TYPE_RELTIME:
+            return on_timedelta()
+        else:
+            # note to maintainers: if you modify the set of ScalarType instances, you must also
+            # maintain this poor man's pattern match over the hierarchy
+            LOG.error('Incomplete implementation of scalar_type_dispatch_table! (when handling %r)',
+                      tt)
+            raise Exception(f'unknown ScalarType: {tt!r}')
+    return _impl
+
+
+
[docs]class Type: + """ + A DAML-defined type. + """ + + def __str__(self): + from ..pretty import DAML_PRETTY_PRINTER + return DAML_PRETTY_PRINTER.visit_type(self)
+ + +class TypeApp(Type): + """ + An application of one or more types to an open type. + + This is basically Type.Con in the Protobuf declaration. + """ + + def __init__(self, body: Type, arguments: Sequence[Type]): + if not isinstance(body, Type): + raise ValueError(f'a Type is required here (got {body} instead)') + if not arguments: + raise ValueError('at least one type argument is required in a TypeApp') + self.body = body + self.arguments = tuple(arguments) + + def __repr__(self): + return f"<TypeApp(body={self.body}, arguments={self.arguments}>" + + +class _Reference: + """ + A reference to another type. + + This is basically TypeConName in the Protobuf declaration. + """ + __slots__ = ('module', 'name') + + module: 'ModuleRef' + name: 'Sequence[str]' + + def __init__(self, module: 'ModuleRef', name: 'Sequence[str]'): + from collections import Collection + if not isinstance(name, Collection): + raise TypeError(f'Tuple of strings required here (got {name!r} instead)') + + self.module = safe_cast(ModuleRef, module) + self.name = tuple(name) # type: Tuple[str, ...] + + @property + def full_name(self): + return '.'.join((*self.module.module_name, *self.name)) + + @property + def full_name_unambiguous(self): + return '.'.join(self.module.module_name) + ':' + '.'.join(self.name) + + def __eq__(self, other): + return isinstance(other, type(self)) and \ + self.module == other.module and self.name == other.name + + def __ne__(self, other): + return not isinstance(other, type(self)) or \ + self.module != other.module or self.name != other.name + + def __lt__(self, other): + return self.module < other.module or \ + (self.module == other.module and self.name < other.name) + + def __le__(self, other): + return self.module <= other.module or \ + (self.module == other.module and self.name <= other.name) + + def __gt__(self, other): + return self.module > other.module or \ + (self.module == other.module and self.name > other.name) + + def __ge__(self, other): + return self.module >= other.module or \ + (self.module == other.module and self.name >= other.name) + + def __hash__(self): + return hash(self.module) ^ hash(self.name) + + def __str__(self): + return self.full_name + + def __repr__(self): + return f"{self.full_name}@{self.module.package_id}" + + +class TypeReference(Type, _Reference): + pass + + +class ValueReference(_Reference): + pass + + +class TypeVariable(Type): + """ + An unbound type in a Type expression. + """ + __slots__ = 'name', + + def __init__(self, name: str): + self.name = safe_cast(str, name) + + def __str__(self): + return self.name + + def __repr__(self): + return f"TypeVariable({self.name})" + + def __eq__(self, other): + return isinstance(other, TypeVariable) and self.name == other.name + + def __hash__(self): + return hash(self.name) + + +class UnresolvedTypeReference(Type): + """ + A reference that may or may not ultimately resolve to a type. + """ + + def __init__(self, name: str): + self.name = safe_cast(str, name) + + def __str__(self): + return self.name + + def __repr__(self): + return f'<UnresolvedTypeReference({self.name!r})>' + + def __eq__(self, other): + return isinstance(other, UnresolvedTypeReference) and self.name == other.name + + def __hash__(self): + return hash((UnresolvedTypeReference, self.name)) + + +class ConcreteType(Type): + @property + def adjective(self) -> 'TypeAdjective': + raise NotImplementedError + + +
[docs]class ScalarType(ConcreteType): + """ + A DAML-defined type that represents a simple scalar value. You should not need to ever + construct instances of this directly; all scalar types are builtins. + """ + + __slots__ = 'name', + + def __init__(self, name: str): + """ + Construct an object that references a scalar DAML type. + + :param name: The name of this type as it is known in DAML. + """ + self.name = safe_cast(str, name) + + @property + def adjective(self): + return TypeAdjective.DAML_BUILTIN + + def __repr__(self): + """ + Return the DAML name of this type. + """ + return self.name + + def __hash__(self): + return hash((ScalarType, self.name)) + + def __eq__(self, other): + return isinstance(other, ScalarType) and self.name == other.name
+ + +class _BuiltInParameterizedType(ConcreteType): + """ + Convenience class that encapsulates commonalities for the built-in types that have one type + parameter. + """ + __slots__ = ('type_parameter',) + + def __init__(self, type_parameter: Type): + self.type_parameter = safe_cast(Type, type_parameter) + + @property + def adjective(self): + return TypeAdjective.DAML_BUILTIN + + def __repr__(self): + py_type = type(self).__name__ + return f'<{py_type}({self.type_parameter!r})>' + + +class ContractIdType(_BuiltInParameterizedType): + pass + + +
[docs]class ListType(_BuiltInParameterizedType): + pass
+ + +class TextMapType(ConcreteType): + """ + A DAML-defined TextMap. + + Instance attributes: + + .. attribute: TextMapType.value_type + + The type of values in this map. + """ + __slots__ = 'value_type', + + def __init__(self, value_type: Type): + self.value_type = safe_cast(Type, value_type) + + @property + def adjective(self): + return TypeAdjective.DAML_BUILTIN + + def __repr__(self): + py_type = type(self).__name__ + return f'<{py_type}({self.value_type!r})>' + + +class OptionalType(_BuiltInParameterizedType): + """ + A DAML-defined Optional. + + Instance attributes: + + .. attribute: OptionalType.type_parameter + + The type of value in the Optional. + """ + + +class UpdateType(_BuiltInParameterizedType): + pass + + +class ForAllType(Type): + def __init__(self, type_vars, body_type): + self.type_vars = type_vars + self.body_type = body_type + + def __repr__(self): + return f'<ForAllType({self.type_vars}, {self.body_type})>' + + +class _CompositeDataType(ConcreteType): + """ + Either a :class:`RecordType` (product type) or a :class:`VariantType` (sum type). + """ + + def __init__(self, + named_args: 'NamedArgumentList', + name: 'Optional[TypeReference]', + type_args: 'Sequence[TypeVariable]', + adjective: 'TypeAdjective'): + if type(self) == _CompositeDataType: + raise Exception('_CompositeDataType cannot be constructed') + if not isinstance(named_args, NamedArgumentList): + raise TypeError('NamedArgumentList required here') + if name is not None and not isinstance(name, TypeReference): + raise TypeError('name must be a TypeReference or None') + + self.named_args = named_args + self.name = name + self.type_args = tuple(type_args) + self._adjective = adjective + + @property + def adjective(self): + return self._adjective + + def field_type(self, name: str) -> Type: + for key, value_type in self.named_args: + if key == name: + return value_type + + raise ValueError(f'field or constructor {name!r} not found in {self}') + + def __repr__(self): + py_type = type(self).__name__ + + name = '(anonymous)' if self.name is None else self.name + full_name = ''.join(f' {v}' for v in ((name,) + self.type_args)) + + return f'<{py_type}:{full_name} {self.named_args}>' + + +class FunctionType(Type): + """ + Representation of a DAML function signature. + + Instances of this type aren't practically usable from this library. They are merely recorded in + order to faithfully pretty-print metadata. + """ + def __init__(self, parameters: Sequence[Type], result: Type): + self.parameters = tuple(parameters) + self.result = safe_cast(Type, result) + + def __str__(self): + from io import StringIO + with StringIO() as buf: + for param in self.parameters: + buf.write(str(param)) + buf.write(' -> ') + buf.write(str(self.result)) + return buf.getvalue() + + def __repr__(self): + return f'<FunctionType({self})>' + + +
[docs]class RecordType(_CompositeDataType): + + def as_args_list(self): + return self.named_args
+ + +
[docs]class VariantType(_CompositeDataType): + + def as_args_list(self): + return self.named_args + + def _find_ctor(self, constructor_name: str) -> Type: + return self.field_type(constructor_name)
+ + +class EnumType(ConcreteType): + + __slots__ = 'constructors', + + def __init__(self, name: 'Optional[TypeReference]', constructors: 'Collection[str]'): + self.name = name + self.constructors = constructors + + @property + def adjective(self) -> 'TypeAdjective': + return TypeAdjective.USER_DEFINED + + +
[docs]class UnsupportedType(Type): + """ + A DAML type that is currently unparseable by the Python client library. + """ + __slots__ = ('name',) + + def __init__(self, name): + self.name = safe_cast(str, name) + + def __repr__(self): + return f'<UnsupportedType({self.name})>'
+ + +class ModuleRef: + """ + A reference to a module. + """ + __slots__ = ('package_id', 'module_name') + + def __init__(self, package_id: str, module_name: DottedNameish): + self.package_id = safe_cast(str, package_id) + self.module_name = dotted_name(module_name) + + def __eq__(self, other): + return isinstance(other, ModuleRef) and \ + self.package_id == other.package_id and \ + self.module_name == other.module_name + + def __lt__(self, other): + return self.package_id < other.package_id or \ + (self.package_id == other.package_id and self.module_name < other.module_name) + + def __le__(self, other): + return self.package_id < other.package_id or \ + (self.package_id == other.package_id and self.module_name <= other.module_name) + + def __gt__(self, other): + return self.package_id > other.package_id or \ + (self.package_id == other.package_id and self.module_name > other.module_name) + + def __ge__(self, other): + return self.package_id > other.package_id or \ + (self.package_id == other.package_id and self.module_name >= other.module_name) + + def __hash__(self): + return hash(self.package_id) ^ hash(self.module_name) + + def __repr__(self): + return f'ModuleRef(package_id={self.package_id!r}, ' \ + f'module_name={".".join(self.module_name)!r})' + + +class Template: + """ + Definition of a contract template. + """ + + def __init__( + self, + data_type: 'RecordType', + key_type: 'Optional[Type]', + choices: 'Collection[TemplateChoice]', + observers: 'Expr', + signatories: 'Expr', + agreement: 'Expr', + ensure: 'Expr'): + if not isinstance(data_type, RecordType) or data_type.name is None: + raise ValueError(f'data_type is required and must be a named record type ' + f'(got {data_type})') + self.data_type = safe_cast(RecordType, data_type) + self.key_type = safe_optional_cast(Type, key_type) + self.choices = choices + self._observers = observers + self._signatories = signatories + self._agreement = agreement + self._ensure = ensure + + def signatories(self, store: 'PackageStore', cdata: ContractData) -> Collection[Party]: + from ..damlast.eval_scope import EvaluationScope + from ..damlast.eval2 import Evaluator + from ..damlast.pretty_print import pretty_print + + scope = EvaluationScope(store, {}) #{'this': cdata}) + print('Trying to evaluate:') + print(pretty_print(scope, self._signatories)) + print('-') + print(repr(self._signatories)) + print('-') + print('') + print('now here we go') + return Evaluator(store, {'this': Evaluator.Constant(cdata)}, {}).eval_Expr(self._signatories) + + def observers(self, store: 'PackageStore', cdata: ContractData) -> Collection[Party]: + from ..damlast import DamlPrettyPrintVisitor, CSharpPrettyPrintVisitor + from ..damlast.expand import ExpandVisitor, SimplifyVisitor + pp = CSharpPrettyPrintVisitor(store) + ex = ExpandVisitor(store, always_expand=False) + sp = SimplifyVisitor(store) + + expr = sp.visit_expr(ex.visit_expr(self._observers)) + print(pp.visit_expr(expr)) + + + return Evaluator(store, {'this': Evaluator.Constant(cdata)}, {}).eval_Expr(self._observers) + + def agreement(self, store: 'PackageStore', cdata: ContractData) -> str: + """ + Return ths text of the agreement of this :class:`Template` from a contract data. + + :param cdata: + An object that represents the record that describe the fields of this template. + :return: + The agreement string. + """ + from ..damlast.eval_scope import EvaluationScope + from ..damlast.eval2 import Evaluator + from ..damlast.pretty_print import pretty_print + + scope = EvaluationScope(store, {}) #{'this': cdata}) + print('Trying to evaluate:') + print(pretty_print(scope, self._signatories)) + print('-') + print(repr(self._signatories)) + print('-') + print('') + print('now here we go') + #fn = Evaluator(store, {}, {}).eval_Expr(self._agreement) + #return fn(Evaluator.Constant(cdata)) + expr = Evaluator(store, {'this': Evaluator.Constant(cdata)}, {}).eval_Expr(self._agreement) + return expr + + def ensure(self, store: 'PackageStore', cdata: 'ContractData') -> bool: + from ..damlast import DamlPrettyPrintVisitor + from ..damlast.expand import ExpandVisitor, SimplifyVisitor + pp = DamlPrettyPrintVisitor() + ex = ExpandVisitor( + store, + always_expand=True, + val_blacklist=[ValueReference( + module=ModuleRef('993b6de82f6297d2a618f0ac17e6c3c4173baf04f1903481f236dd8bf4c64554', + module_name=('DA', 'Internal', 'Prelude')), + name=('concat',))]) + sp = SimplifyVisitor(store) + + expr = sp.visit_expr(ex.visit_expr(self._ensure)) + print(pp.visit_expr(expr)) + + +class TemplateChoice: + __slots__ = ('name', 'consuming', 'data_type', '_controllers') + + def __init__(self, name: str, consuming: bool, data_type: Type, controllers: 'Expr'): + self.name = name + self.consuming = consuming + self.data_type = data_type + self._controllers = controllers + + @property + def type(self): + return self.data_type + + def controllers(self, cdata: ContractData) -> Collection[Party]: + """ + Return every :class:`Party` that can exercise this choice given the specified contract data. + """ + + +def as_commands(commands_ish, allow_callables=False): + """ + Converts something that is either ``None``, a single :class:`Command`, or an iterable over + :class:`Command` objects to a ``list`` of :class:`Command`. + + :param commands_ish: + Something that might be construed as either a :class:`Command` or an iterable over + :class:`Command`. + :param allow_callables: + If callables are encountered, invoke them and expect them to return something that can be + easily serialized to a :class:`Command`. + """ + from .writing import Command + + if commands_ish is None: + return () + elif isinstance(commands_ish, Command): + return (commands_ish,) + elif allow_callables and callable(commands_ish): + return as_commands(commands_ish(), allow_callables=False) + + # assume this is some kind of iterable structure, where everything needs to be a Command + cmds = [] + for command in commands_ish: + if allow_callables and callable(command): + cmds.extend(as_commands(command(), allow_callables=False)) + elif isinstance(command, Command): + cmds.append(command) + else: + raise TypeError(f'{command!r} is not a Command') + return tuple(cmds) + + +def as_contract_id(cid, template_id=None): + """ + Convert something that resembles a contract ID to a :class:`ContractId` or + :class:`RelativeContractRef`. + """ + from .core import ContractId + + if cid is None: + raise ValueError('cid is required') + elif isinstance(cid, str): + return ContractId(cid, template_id) + elif isinstance(cid, ContractId): + return cid + + raise TypeError('Could not serialize an object to a contract ID: {!r}'.format(cid)) + + +SCALAR_TYPE_UNIT = ScalarType('Unit') +SCALAR_TYPE_BOOL = ScalarType('Bool') +SCALAR_TYPE_CHAR = ScalarType('Char') +SCALAR_TYPE_INTEGER = ScalarType('Integer') +SCALAR_TYPE_DECIMAL = ScalarType('Decimal') +SCALAR_TYPE_TEXT = ScalarType('Text') +SCALAR_TYPE_PARTY = ScalarType('Party') +SCALAR_TYPE_RELTIME = ScalarType('RelTime') +SCALAR_TYPE_DATE = ScalarType('Date') +SCALAR_TYPE_TIME = ScalarType('Time') +SCALAR_TYPE_DATETIME = SCALAR_TYPE_TIME + +ScalarType.BUILTINS = [ + SCALAR_TYPE_BOOL, + SCALAR_TYPE_CHAR, + SCALAR_TYPE_INTEGER, + SCALAR_TYPE_DECIMAL, + SCALAR_TYPE_TEXT, + SCALAR_TYPE_PARTY, + SCALAR_TYPE_RELTIME, + SCALAR_TYPE_DATE, + SCALAR_TYPE_TIME, +] + + +class TypeEvaluationContext: + references: Dict[TypeReference, Type] + variables: Dict[TypeVariable, Type] + path: Sequence[Union[TypeReference, str]] + + __slots__ = ('references', 'variables', 'path') + + @classmethod + def from_store(cls, store: 'PackageStore') -> 'TypeEvaluationContext': + return cls(store.find_types(), {}, ()) + + def __init__(self, references, variables, path): + self.references = safe_dict_cast(TypeReference, Type, references) + self.variables = safe_dict_cast(TypeVariable, Type, variables) + self.path = path + + def append_path(self, component: Union[TypeReference, str]) -> 'TypeEvaluationContext': + return TypeEvaluationContext( + references=self.references, + variables=self.variables, + path=tuple((*self.path, component))) + + def resolve_var(self, var: TypeVariable) -> Type: + return self.variables[var] + + def with_vars(self, new_vars: Dict[TypeVariable, Type]) -> 'TypeEvaluationContext': + confirmed_new_vars = {} + for new_var, new_var_value in new_vars.items(): + if new_var == new_var_value: + # TODO: Why do these cases happen? + continue + confirmed_new_vars[new_var] = new_var_value + + return TypeEvaluationContext( + references=self.references, + variables={**self.variables, **confirmed_new_vars}, + path=self.path) + + +def type_evaluate_dispatch( + on_scalar: 'Callable[[TypeEvaluationContext, ScalarType], T_co]', + on_contract_id: 'Callable[[TypeEvaluationContext, ContractIdType], T_co]', + on_optional: 'Callable[[TypeEvaluationContext, OptionalType], T_co]', + on_list: 'Callable[[TypeEvaluationContext, ListType], T_co]', + on_text_map: 'Callable[[TypeEvaluationContext, TextMapType], T_co]', + on_record: 'Callable[[TypeEvaluationContext, RecordType], T_co]', + on_variant: 'Callable[[TypeEvaluationContext, VariantType], T_co]', + on_enum: 'Callable[[TypeEvaluationContext, EnumType], T_co]', + on_unsupported: 'Callable[[TypeEvaluationContext, UnsupportedType], T_co]') \ + -> 'Callable[[TypeEvaluationContext, Type], T_co]': + """ + Produce a function that defers handling of core types to the passed in functions. + + The cases of :class:`TypeReference, :class:`TypeApp`, and :class:`TypeVariable` are handled + automatically. Note, though that ultimately type evaluation is only performed at one level + deep, and the produced function may need to be called multiple types at multiple depths of an + object or type hierarchy. + """ + def _impl(context, tt): + resolve_depth = 0 + while isinstance(tt, (TypeReference, TypeVariable, TypeApp)): + context, tt = single_reduce(context, tt) + resolve_depth += 1 + if resolve_depth > 10: + raise Exception('hit our max resolve depth, which is probably not so great') + + def error(_: Any) -> 'T_co': raise Exception() + + context, tt = annotate_context(context, tt) + + return type_dispatch_table( + error, error, error, + lambda st: on_scalar(context, st), + lambda ct: on_contract_id(context, ct), + lambda ot: on_optional(context, ot), + lambda lt: on_list(context, lt), + lambda mt: on_text_map(context, mt), + lambda rt: on_record(context, rt), + lambda vt: on_variant(context, vt), + lambda et: on_enum(context, et), + lambda ut: on_unsupported(context, tt))(tt) + return _impl + + +def _type_evaluate_dispatch_error(_, __): + raise Exception() + + +def type_evaluate_dispatch_default_error( + on_scalar: 'Callable[[TypeEvaluationContext, ScalarType], T_co]' = _type_evaluate_dispatch_error, + on_contract_id: 'Callable[[TypeEvaluationContext, ContractIdType], T_co]' = _type_evaluate_dispatch_error, + on_optional: 'Callable[[TypeEvaluationContext, OptionalType], T_co]' = _type_evaluate_dispatch_error, + on_list: 'Callable[[TypeEvaluationContext, ListType], T_co]' = _type_evaluate_dispatch_error, + on_text_map: 'Callable[[TypeEvaluationContext, TextMapType], T_co]' = _type_evaluate_dispatch_error, + on_record: 'Callable[[TypeEvaluationContext, RecordType], T_co]' = _type_evaluate_dispatch_error, + on_variant: 'Callable[[TypeEvaluationContext, VariantType], T_co]' = _type_evaluate_dispatch_error, + on_enum: 'Callable[[TypeEvaluationContext, EnumType], T_co]' = _type_evaluate_dispatch_error, + on_unsupported: 'Callable[[TypeEvaluationContext, UnsupportedType], T_co]' = _type_evaluate_dispatch_error): + return type_evaluate_dispatch( + on_scalar, on_contract_id, on_optional, on_list, on_text_map, on_record, on_variant, + on_enum, on_unsupported) + + +def single_reduce(context: TypeEvaluationContext, tt: Type) -> 'Tuple[TypeEvaluationContext, Type]': + """ + Apply a single substitution/reduction/unwrapping. The context may be augmented with additional + variables if a TypeApp is encountered. + """ + def identity(t): return context, t + + def reduce_app(ta: TypeApp) -> 'Tuple[TypeEvaluationContext, Type]': + body = context.references[ta.body] if isinstance(ta.body, TypeReference) else ta.body + if not isinstance(body, (RecordType, VariantType)): + raise Exception("Can't apply types to non-generic data structures") + + return context.with_vars(dict(zip(body.type_args, ta.arguments))), ta.body + + return type_dispatch_table( + lambda tr: (context, context.references[tr]), + lambda tv: (context, context.resolve_var(tv)), + reduce_app, + identity, + identity, + identity, + identity, + identity, + identity, + identity, + identity, + identity)(tt) + + +def annotate_context(context: TypeEvaluationContext, tt: Type) -> Tuple[TypeEvaluationContext, Type]: + def identity(t): return context, t + + def error(_: Any) -> Any: raise Exception() + + def annotate_path(t: Union[RecordType, VariantType]) -> Tuple[TypeEvaluationContext, Type]: + return context.append_path(t.name), t + + return type_dispatch_table( + error, error, error, identity, identity, identity, identity, identity, + annotate_path, annotate_path, identity, identity)(tt) + + +class TemplateMeta(type): + """ + Metaclass for generated template types. + """ + def __new__(mcs, name, bases, namespace, template_name: str): + result = type.__new__(mcs, name, bases, dict(namespace)) + result._template_name = template_name + return result + + def __str__(self): + return self._template_name + + def __repr__(self): + return self._template_name + + +class ChoiceMeta(type): + """ + Metaclass for generated template choice types. + """ + def __new__(mcs, name, bases, namespace, template_name: str, choice_name: str): + result = type.__new__(mcs, name, bases, dict(namespace)) + result._template_name = template_name + result._choice_name = choice_name + return result + + def __str__(self): + return self._choice_name + + def __repr__(self): + return self._choice_name + + +class TypeAdjective(Flag): + """ + Different descriptions for how and why a type comes to be. + + Instance attributes: + + .. attribute: TypeAdjective.DAML_BUILTIN: + + A native type to DAML, such as ``Integer``, ``Text``, or ``ContractId`` + + .. attribute: TypeAdjective.DAML_INTERNAL: + + Types that are used internally to DAML and generally not exposed to users. + + .. attribute: TypeAdjective.USER_TEMPLATE_AUTOGENERATED: + + Types that were created because of a DAML ``template`` declaration. + + .. attribute: TypeAdjective.USER_CHOICE_AUTOGENERATED: + + Types that were created because of a DAML choice declaration. + + .. attribute: TypeAdjective.USER_DEFINED: + + Types that were explicitly created because of a user declaration. + """ + NONE = 0 + DAML_BUILTIN = 1 + DAML_INTERNAL = 2 + USER_TEMPLATE_AUTOGENERATED = 4 + USER_CHOICE_AUTOGENERATED = 8 + USER_DEFINED = 16 + ANY = 0xFFFFFFFF + + +def module(obj): + """ + Marker decorator that denotes a class as a module. + """ + return obj + + +# types that can be used to refer to templates +TemplateNameLike = Union[str, TypeReference, UnresolvedTypeReference, Template] +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/model/writing.html b/docs/_modules/dazl/model/writing.html new file mode 100644 index 00000000..32a2770e --- /dev/null +++ b/docs/_modules/dazl/model/writing.html @@ -0,0 +1,790 @@ + + + + + + + + dazl.model.writing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.model.writing

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+Write-Side types
+----------------
+
+The :mod:`dazl.model.writing` module contains the Python classes used on the write-side of the
+Ledger API.
+
+.. autoclass:: Command
+   :members:
+
+.. autoclass:: CreateCommand
+   :members:
+
+.. autoclass:: ExerciseCommand
+   :members:
+"""
+import uuid
+import warnings
+from datetime import datetime, timedelta
+from typing import Any, Collection, Dict, Generic, List, Mapping, Optional, Sequence, TypeVar, Union
+
+from dataclasses import dataclass, fields
+
+from .. import LOG
+from .core import ContractId, Party
+from .types import Type, TypeReference, UnresolvedTypeReference, TemplateChoice, \
+    RecordType, UnsupportedType, VariantType, ContractIdType, ListType, OptionalType, TextMapType, \
+    EnumType, scalar_type_dispatch_table, TypeEvaluationContext, type_evaluate_dispatch, \
+    TemplateMeta, ChoiceMeta
+from .types_store import PackageStore
+from ..util.prim_types import DEFAULT_TYPE_CONVERTER
+from ..util.typing import safe_cast, safe_optional_cast
+
+TCommand = TypeVar('TCommand')
+TValue = TypeVar('TValue')
+
+
+CommandsOrCommandSequence = Union[None, 'Command', List[Optional['Command']]]
+EventHandlerResponse = Union[CommandsOrCommandSequence, 'CommandBuilder', 'CommandPayload']
+
+
+
[docs]class Command: + """ + Base class for write-side commands. + """
+ + +
[docs]@dataclass(init=False, frozen=True) +class CreateCommand(Command): + """ + A command that creates a contract without any predecessors. + + .. attribute:: CreateCommand.template + + Refers to the type of a template. This can be passed in as a ``str`` to the constructor, + where it assumed to represent the ID or name of a template. + + .. attribute:: CreateCommand.arguments + + The arguments to the create (as a ``dict``). + """ + __slots__ = ('template', 'arguments') + + template: Type + arguments: Dict[str, Any] + + def __init__(self, template: 'Union[str, Type]', arguments=None): + object.__setattr__(self, 'template', template if isinstance(template, Type) + else UnresolvedTypeReference(template)) + object.__setattr__(self, 'arguments', arguments or dict()) + +
[docs] def replace(self, template: Union[None, str, Type] = None, arguments=None): + """ + Create a new :class:`CreateCommand` with the same identifier as this command, but with new + values for its parameters. + + :param template: + The new value of the `template` field, or `None` to reuse the existing value. + :param arguments: + The new value of the `arguments` field, or `None` to reuse the existing value. + """ + if template is not None: + template = template if isinstance(template, Type) \ + else UnresolvedTypeReference(template) + return CreateCommand( + template if template is not None else self.template, + arguments if arguments is not None else self.arguments)
+ + def __repr__(self): + return f'<create {self.template} {self.arguments}>'
+ + +
[docs]@dataclass(init=False, frozen=True) +class ExerciseCommand(Command): + """ + A command that exercises a choice on a pre-existing contract. + + .. attribute:: ExerciseCommand.contract + + The :class:`ContractId` on which a choice is being exercised. + + .. attribute:: ExerciseCommand.choice + + Refers to a choice (either a :class:`ChoiceRef` or a :class:`ChoiceMetadata`). + This can be passed in as a ``str`` to the constructor, where it assumed to represent the + name of a choice. + + .. attribute:: ExerciseCommand.arguments + + The arguments to the exercise choice (as a ``dict``). + + Note that when an ``ExerciseCommand`` is created, an additional ``template_id`` parameter can + be supplied to the constructor to aid in disambiguation of the specific choice being invoked. + In some situations involving composite commands, a ``template_id`` must eventually be supplied + before a choice can be exercised. If this ``template_id`` is specified, the ``contract`` and + ``choice`` are both tagged with this ID. + + Instance methods: + + .. automethod:: replace + """ + __slots__ = ('contract', 'choice', 'arguments') + + def __init__( + self, + contract: 'Union[str, ContractId]', + choice: str, + arguments=None, + template_id=None): + if isinstance(contract, str): + warnings.warn('Untyped ContractId support will be removed with the removal of ' + 'the deprecated REST API.', DeprecationWarning, stacklevel=2) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + contract = ContractId(contract, template_id=template_id) + elif template_id is not None: + warnings.warn( + 'Specifying template_id in an ExerciseChoice is no longer necessary. ' + + 'Please avoid specifying it, as this parameter will be removed in the future.', + DeprecationWarning, stacklevel=2) + elif not isinstance(contract, ContractId): + raise ValueError('ContractId expected here') + + object.__setattr__(self, 'contract', contract) + object.__setattr__(self, 'choice', choice) + object.__setattr__(self, 'arguments', dict(arguments) if arguments is not None else dict()) + +
[docs] def replace(self, contract=None, choice=None, arguments=None, template_id=None): + """ + Create a new :class:`ExerciseCommand` with the same identifier as this command, but with new + values for its parameters. + + :param contract: + The new value of the `contract` field, or `None` to reuse the existing value. + The same type coercion rules used in the constructor apply here. + :param choice: + The new value of the `choice` field, or `None` to reuse the existing value. + The same type coercion rules used in the constructor apply here. + :param arguments: + The new value of the `choice` field, or `None` to reuse the existing value. + :param template_id: + The expected template type. + """ + return ExerciseCommand( + contract if contract is not None else self.contract, + choice if choice is not None else self.choice, + arguments if arguments is not None else self.arguments, + template_id)
+ + def __repr__(self): + return '<exercise \"{}\" with {} on {}>'.format( + self.choice, + self.arguments, + self.contract.contract_id if hasattr(self.contract, 'contract_id') else self.contract)
+ + +@dataclass(frozen=True) +class ExerciseByKeyCommand(Command): + template: Type + contract_key: Any + choice: str + choice_argument: Mapping[str, Any] + + +@dataclass(frozen=True) +class CreateAndExerciseCommand(Command): + template: Type + arguments: Mapping[str, Any] + choice: str + choice_argument: Mapping[str, Any] + + +class CommandBuilder: + """ + Builder class for generating commands to be sent to the ledger. + """ + + @classmethod + def coerce(cls, obj, atomic_default=False) -> 'CommandBuilder': + """ + Create a :class:`CommandBuilder` from the objects that an event handler is allowed to + return. + + :param obj: + :param atomic_default: + :return: + """ + if isinstance(obj, CommandBuilder): + return obj + + builder = CommandBuilder(atomic_default=atomic_default) + if obj is not None: + builder.append(obj) + return builder + + def __init__(self, atomic_default=False): + self._atomic_default = atomic_default + self._commands = [[]] # type: List[List[Command]] + self._defaults = CommandDefaults() + + def defaults(self, + party: Optional[Party] = None, + ledger_id: Optional[str] = None, + workflow_id: Optional[str] = None, + application_id: Optional[str] = None, + command_id: Optional[str] = None) -> None: + if party is not None: + self._defaults.default_party = party + if ledger_id is not None: + self._defaults.ledger_id = ledger_id + if workflow_id is not None: + self._defaults.default_workflow_id = workflow_id + if application_id is not None: + self._defaults.default_application_id = application_id + if command_id is not None: + self._defaults.default_command_id = command_id + + def create(self, template, arguments=None) -> 'CommandBuilder': + return self.append(create(template, arguments=arguments)) + + def exercise(self, contract, choice, arguments=None) -> 'CommandBuilder': + return self.append(exercise(contract, choice, arguments=arguments)) + + def create_and_exercise(self, template, create_arguments, choice_name, choice_arguments=None) \ + -> 'CommandBuilder': + return self.append(create_and_exercise( + template, create_arguments, choice_name, choice_arguments)) + + def append(self, *commands: CommandsOrCommandSequence) -> 'CommandBuilder': + """ + Append one or more commands, or list of commands to the :class:`CommandBuilder` in flight. + This method respects the value of ``atomic_default`` that this object was constructed with. + In order to force commands to be submitted either atomically, use :meth:`append_atomically`. + To allow these commands to be submitted in parallel use :meth:`append_nonatomically`. + + :param commands: One or more commands, or list of commands to be submitted to the ledger. + :return: This object. + """ + if self._atomic_default: + # a command builder that defaults to being atomic will put all commands in a single + # transaction; build on the very first transaction + self._commands[0].extend(flatten_command_sequence(commands)) + return self + else: + return self.append_nonatomically(*commands) + + def append_atomically(self, *commands: Union[Command, Sequence[Command]]) -> 'CommandBuilder': + self._commands.extend([flatten_command_sequence(commands)]) + return self + + def append_nonatomically(self, *commands: Union[Command, Sequence[Command]]) -> \ + 'CommandBuilder': + self._commands.extend([[cmd] for cmd in flatten_command_sequence(commands)]) + return self + + def build(self, defaults: 'Optional[CommandDefaults]' = None, now: Optional[datetime] = None) \ + -> 'Collection[CommandPayload]': + """ + Return a collection of commands. + """ + if defaults is None: + raise ValueError('defaults must currently be specified') + + command_id = defaults.default_command_id or self._defaults.default_command_id or \ + uuid.uuid4().hex + + return [CommandPayload( + party=defaults.default_party or self._defaults.default_party, + ledger_id=defaults.default_ledger_id or self._defaults.default_ledger_id, + workflow_id=defaults.default_workflow_id or self._defaults.default_workflow_id, + application_id=defaults.default_application_id or self._defaults.default_application_id, + command_id=command_id, + ledger_effective_time=now, + maximum_record_time=now + (defaults.default_ttl or self._defaults.default_ttl), + commands=commands + ) for i, commands in enumerate(self._commands) if commands] + + def __format__(self, format_spec): + if format_spec == 'c': + return str(self._commands) + else: + return repr(self) + + def __repr__(self): + return f'CommandBuilder({self._commands})' + + +def flatten_command_sequence(commands: Sequence[CommandsOrCommandSequence]) -> List[Command]: + """ + Convert a list of mixed commands, ``None``, and list of commands into an ordered sequence of + non-``None`` commands. + """ + ret = [] # type: List[Command] + errors = [] + + for i, obj in enumerate(commands): + if obj is not None: + if isinstance(obj, Command): + ret.append(obj) + else: + try: + cmd_iter = iter(obj) + except TypeError: + errors.append(((i,), obj)) + continue + for j, cmd in enumerate(cmd_iter): + if isinstance(cmd, Command): + ret.append(cmd) + else: + errors.append(((i, j), cmd)) + if errors: + raise ValueError(f'Failed to interpret some elements as Commands in the list: ' + f'$[{index}] = {command}' for index, command in errors) + return ret + + +@dataclass +class CommandDefaults: + """ + Values to use for a :class:`Command` when no value is specified with the creation of the + command. + """ + + default_party: Optional[Party] = None + default_ledger_id: Optional[str] = None + default_workflow_id: Optional[str] = None + default_application_id: Optional[str] = None + default_command_id: Optional[str] = None + default_ttl: Optional[timedelta] = None + + +@dataclass(frozen=True) +class CommandPayload: + """ + A request to mutate active state of the ledger. + + .. attribute:: CommandPayload.party + The party submitting the request. + .. attribute:: CommandPayload.application_id: + An optional application ID to accompany the request. + .. attribute:: CommandPayload.command_id: + A hash that represents the BIM commitment. + .. attribute:: CommandPayload.ledger_effective_time: + The effective time of this command. Should usually be set to ``datetime.now()``, but + may have a different value when the server is operating in static time mode. + .. attribute:: CommandPayload.maximum_record_time: + The maximum time before the client should consider this command expired. + .. attribute:: CommandPayload.commands + A sequence of commands to submit to the ledger. These commands are submitted atomically + (in other words, they all succeed or they all fail). + """ + party: Party + ledger_id: str + workflow_id: str + application_id: str + command_id: str + ledger_effective_time: datetime + maximum_record_time: datetime + commands: Sequence[Command] + + def __post_init__(self): + missing_fields = [field.name for field in fields(self) if getattr(self, field.name) is None] + if missing_fields: + raise ValueError(f'Some fields are set to None when they are required: ' + f'{missing_fields}') + + +def create(template, arguments=None): + from .types_dynamic import NamedRecord, ProxyMeta + + template_type = type(template) + if isinstance(template_type, TemplateMeta): + # static codegen, instantiated type + if arguments is not None: + raise ValueError('arguments cannot be specified with an instantiated template') + arguments = template._asdict() + template = str(template_type) + + elif isinstance(template, NamedRecord): + # dynamic "codegen", instantiated type + if arguments is not None: + raise ValueError('arguments cannot be specified with an instantiated template') + template, arguments = template.name, template.arguments + + elif template_type == TemplateMeta: + # static codegen, non-instantiated + template = str(template) + + elif isinstance(template_type, ProxyMeta): + # dynamic codegen, non-instantiated + template = str(template_type) + + elif not isinstance(template, str): + raise ValueError( + 'template must be a string name, a template type, or an instantiated template') + + return CreateCommand(template, arguments) + + +def exercise(contract, choice, arguments=None): + from .types_dynamic import NamedRecord, ProxyMeta + + choice_type = type(choice) + if isinstance(choice_type, ChoiceMeta): + # static codegen, instantiated type + if arguments is not None: + raise ValueError('arguments cannot be specified with an instantiated template') + arguments = choice._asdict() + choice = str(choice_type) + + elif isinstance(choice, NamedRecord): + # dynamic "codegen", instantiated type + if arguments is not None: + raise ValueError('arguments cannot be specified with an instantiated template') + choice, arguments = choice.name, choice.arguments + choice_start_idx = choice.rfind('.') + if choice_start_idx >= 0: + choice = choice[choice_start_idx + 1:] + + elif choice_type == ChoiceMeta: + # static codegen, non-instantiated + choice = str(choice) + + elif isinstance(choice_type, ProxyMeta): + # dynamic codegen, non-instantiated + choice = str(choice_type) + choice_start_idx = choice.rfind('.') + if choice_start_idx >= 0: + choice = choice[choice_start_idx + 1:] + + elif not isinstance(choice, str): + raise ValueError('choice must be a string name, a template type, ' + 'or an instantiated template') + + return ExerciseCommand(contract, choice, arguments) + + +def exercise_by_key(template, contract_key, choice_name, choice_argument): + return ExerciseByKeyCommand(template, contract_key, choice_name, choice_argument) + + +def create_and_exercise(template, create_arguments, choice_name, choice_argument): + return CreateAndExerciseCommand(template, create_arguments, choice_name, choice_argument) + + +#################################################################################################### +# argument iteration support +#################################################################################################### + + +def arg_iter(value): + """ + Produce an iterator that walks over an argument tree and all of its values, recursing into + lists and record/variant fields. + """ + if isinstance(value, str): + # str is a common case, and it's also iterable (which we don't want to exploit here) + yield value + elif isinstance(value, dict): + for sub_value in value.values(): + yield sub_value + elif hasattr(value, '__iter__'): + for sub_value in value: + yield sub_value + else: + yield value + + +class Serializer(Generic[TCommand, TValue]): + """ + Serializer interface for objects on the write-side of the API. + """ + + def serialize_value(self, type_token: Type, obj: Any) -> TValue: + raise NotImplementedError('serialize_value requires an implementation') + + def serialize_command(self, command: Command) -> TCommand: + raise NotImplementedError('serialize_command requires an implementation') + + +class AbstractSerializer(Serializer[TCommand, TValue]): + """ + Implementation of :class:`Serializer` that helps enforce that all possible cases of type + serialization have been implemented. + """ + def __init__(self, store: PackageStore, type_context: 'Optional[TypeEvaluationContext]' = None): + self.store = safe_cast(PackageStore, store) + self.type_context = safe_optional_cast(TypeEvaluationContext, type_context) or \ + DEFAULT_TYPE_CONVERTER + + def serialize_value(self, tt: Type, obj: Any) -> TValue: + context = TypeEvaluationContext.from_store(self.store) + try: + return self._serialize_dispatch(context, tt, obj) + except: + from ..util.fmt_py import python_example_object + + LOG.warning("Expected something like:") + for line in str.splitlines(python_example_object(self.store, tt)): + LOG.warning(' %s', line) + + LOG.warning("But got this instead:") + LOG.warning(' %r', obj) + raise + + def serialize_commands(self, commands: Sequence[Command]) -> Sequence[TCommand]: + return [self.serialize_command(cmd) for cmd in commands] + + def serialize_command(self, command: Command) -> TCommand: + if isinstance(command, CreateCommand): + tt = _resolve_template_type(self.store, command.template) + value = self.serialize_value(tt, command.arguments) + return self.serialize_create_command(tt, value) + elif isinstance(command, ExerciseCommand): + template_type_ref = command.contract.template_id + choice_name = command.choice + choice_opts = self.store.resolve_choice(template_type_ref, choice_name) + if len(choice_opts) == 0: + msg = f'Could not resolve {template_type_ref} {choice_name} to any valid choices' + LOG.error(msg) + raise ValueError(msg) + if len(choice_opts) > 1: + msg = f'Could not uniquely resolve {template_type_ref} {choice_name} ' \ + f'to a single valid choice' + LOG.error(msg) + raise ValueError(msg) + tt, choice = next(iter(choice_opts.items())) + + args = self.serialize_value(choice.type, command.arguments) + return self.serialize_exercise_command(command.contract, choice, args) + elif isinstance(command, CreateAndExerciseCommand): + tt = _resolve_template_type(self.store, command.template) + create_value = self.serialize_value(tt, command.arguments) + _, choice_info = next(iter(self.store.resolve_choice(tt, command.choice).items())) + choice_args = self.serialize_value(choice_info.type, command.choice_argument) + return self.serialize_create_and_exercise_command( + tt, create_value, choice_info, choice_args) + elif isinstance(command, ExerciseByKeyCommand): + template, = self.store.resolve_template(command.template) + key_value = self.serialize_value(template.key_type, command.contract_key) + choices = self.store.resolve_choice(template, command.choice) + _, choice_info = next(iter(choices.items())) + choice_args = self.serialize_value(choice_info.type, command.choice_argument) + return self.serialize_exercise_by_key_command( + template.data_type.name, key_value, choice_info, choice_args) + else: + raise ValueError(f'unknown Command type: {command!r}') + + def serialize_create_command( + self, template_type: RecordType, template_args: TValue) \ + -> TCommand: + raise NotImplementedError('serialize_create_command requires an implementation') + + def serialize_exercise_command( + self, contract_id: ContractId, choice_info: TemplateChoice, choice_args: TValue) \ + -> TCommand: + raise NotImplementedError('serialize_exercise_command requires an implementation') + + def serialize_exercise_by_key_command( + self, template_ref: TypeReference, key_arguments: Any, + choice_info: TemplateChoice, choice_arguments: Any) -> TCommand: + raise NotImplementedError( + 'serialize_exercise_by_key_command requires an implementation') + + def serialize_create_and_exercise_command( + self, template_type: RecordType, create_arguments: Any, + choice_info: TemplateChoice, choice_arguments: Any) -> TCommand: + raise NotImplementedError( + 'serialize_create_and_exercise_command requires an implementation') + + def serialize_unit(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_unit requires an implementation') + + def serialize_bool(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_text(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_int(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_decimal(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_party(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_date(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_datetime(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_timedelta(self, context: TypeEvaluationContext, obj: Any) -> TValue: + raise NotImplementedError('serialize_bool requires an implementation') + + def serialize_contract_id(self, context: TypeEvaluationContext, tt: ContractIdType, obj: Any) \ + -> TValue: + raise NotImplementedError('serialize_contract_id requires an implementation') + + def serialize_optional(self, context: TypeEvaluationContext, tt: OptionalType, obj: Any) \ + -> TValue: + raise NotImplementedError('serialize_optional requires an implementation') + + def serialize_list(self, context: TypeEvaluationContext, tt: ListType, obj: Any) -> TValue: + raise NotImplementedError('serialize_list requires an implementation') + + def serialize_map(self, context: TypeEvaluationContext, tt: TextMapType, obj: Any) -> TValue: + raise NotImplementedError('serialize_map requires an implementation') + + def serialize_record(self, context: TypeEvaluationContext, tt: RecordType, obj: Any) -> TValue: + raise NotImplementedError('serialize_record requires an implementation') + + def serialize_variant(self, context: TypeEvaluationContext, tt: VariantType, obj: Any) \ + -> TValue: + raise NotImplementedError('serialize_variant requires an implementation') + + def serialize_enum(self, context: TypeEvaluationContext, tt: EnumType, obj: Any) -> TValue: + raise NotImplementedError('serialize_enum requires an implementation') + + def serialize_unsupported(self, context: TypeEvaluationContext, tt: UnsupportedType, obj: Any) \ + -> TValue: + raise NotImplementedError('serialize_unsupported requires an implementation') + + def _serialize_dispatch(self, context: TypeEvaluationContext, tt: Type, obj: Any) -> TValue: + eval_fn = type_evaluate_dispatch( + lambda c, st: scalar_type_dispatch_table( + lambda: self.serialize_unit(c, obj), + lambda: self.serialize_bool(c, obj), + lambda: self.serialize_text(c, obj), + lambda: self.serialize_int(c, obj), + lambda: self.serialize_decimal(c, obj), + lambda: self.serialize_party(c, obj), + lambda: self.serialize_date(c, obj), + lambda: self.serialize_datetime(c, obj), + lambda: self.serialize_timedelta(c, obj))(st), + lambda c, ct: self.serialize_contract_id(c, ct, obj), + lambda c, ot: self.serialize_optional(c, ot, obj), + lambda c, lt: self.serialize_list(c, lt, obj), + lambda c, mt: self.serialize_map(c, mt, obj), + lambda c, rt: self.serialize_record(c, rt, obj), + lambda c, vt: self.serialize_variant(c, vt, obj), + lambda c, et: self.serialize_enum(c, et, obj), + lambda c, ut: self.serialize_unsupported(c, ut, obj)) + return eval_fn(context, tt) + + +def _resolve_template_type(store: 'PackageStore', template) -> 'RecordType': + candidates = store.resolve_template_type(template) + if len(candidates) == 0: + msg = f'Could not resolve {template} to any valid types' + LOG.error(msg) + raise ValueError(msg) + elif len(candidates) > 1: + msg = f'Could not uniquely resolve {template} to a single valid type' + LOG.error(msg) + raise ValueError(msg) + + tt, = candidates.values() + if not isinstance(tt, RecordType): + msg = f'CreateCommand requires a type that is a record (got {tt} instead)' + LOG.error(msg) + raise ValueError(msg) + + return tt +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/dazl/pretty.html b/docs/_modules/dazl/pretty.html new file mode 100644 index 00000000..3c3d4475 --- /dev/null +++ b/docs/_modules/dazl/pretty.html @@ -0,0 +1,150 @@ + + + + + + + + dazl.pretty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.pretty

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+:mod:`dazl.pretty` package
+==========================
+
+This module contains utilities for pretty-printing various types in dazl.
+
+.. automodule:: dazl.pretty.render_daml
+.. automodule:: dazl.pretty.util
+"""
+
+from typing import Optional, Type, TYPE_CHECKING
+
+from ._render_base import PrettyPrintBase, pretty_print_syntax
+from .options import PrettyOptions
+from .render_csharp import CSharpPrettyPrint
+from .render_daml import DamlPrettyPrinter, DEFAULT_PRINTER as DAML_PRETTY_PRINTER
+from .render_python import PythonPrettyPrint
+from .util import maybe_parentheses
+from ..model.types_store import PackageStore
+
+if TYPE_CHECKING:
+    from .pygments_daml_lexer import DAMLLexer as _DAMLLexer_TYPE
+
+
+def _import_daml_lexer() -> 'Optional[Type[_DAMLLexer_TYPE]]':
+    # pygments isn't absolutely required, but if it's loaded, also provide our lexer
+    try:
+        from .pygments_daml_lexer import DAMLLexer
+        return DAMLLexer
+    except ImportError:
+        return None
+
+
+DAMLLexer = _import_daml_lexer()
+
+
+ALL_PRINTER_TYPES = [CSharpPrettyPrint, DamlPrettyPrinter, PythonPrettyPrint]
+
+
+# noinspection PyShadowingBuiltins,PyShadowingNames
+
[docs]def get_pretty_printer(format: str, options: 'PrettyOptions', store: 'PackageStore') \ + -> 'Optional[PrettyPrintBase]': + for printer in ALL_PRINTER_TYPES: + if printer.syntax.startswith(format): + return printer(store, options) + return None
+
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/index.html b/docs/_modules/index.html new file mode 100644 index 00000000..53b6dacd --- /dev/null +++ b/docs/_modules/index.html @@ -0,0 +1,108 @@ + + + + + + + + Overview: module code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

All modules for which code is available

+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_sources/basics.rst.txt b/docs/_sources/basics.rst.txt new file mode 100644 index 00000000..60567573 --- /dev/null +++ b/docs/_sources/basics.rst.txt @@ -0,0 +1,67 @@ +Basics +====== + + +Mapping DAML types to Python types + + ++-------------------------+------------------------------------------------------------------------+ +| DAML type | Python type | ++=========================+========================================================================+ +| ``Unit`` or ``()`` | ``dict()`` (an empty dictionary) | ++-------------------------+------------------------------------------------------------------------+ +| ``Bool`` | ``bool`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Integer`` or ``Int`` | ``int`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Decimal`` | ``decimal.Decimal`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Text`` | ``str`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Party`` | ``str`` | ++-------------------------+------------------------------------------------------------------------+ +| ``RelTime`` | ``datetime.timedelta`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Date`` | ``datetime.datetime`` | ++-------------------------+------------------------------------------------------------------------+ +| ``Time`` | ``datetime.time`` | ++-------------------------+------------------------------------------------------------------------+ +| ``ContractId a`` | :class:`dazl.model.core.ContractId` | ++-------------------------+------------------------------------------------------------------------+ +| ``List a`` | ``list`` | ++-------------------------+------------------------------------------------------------------------+ +| records | ``dict`` where keys are field names and values are as listed in this | +| | table | ++-------------------------+------------------------------------------------------------------------+ +| variants | ``dict`` containing a single key naming the specific constructor to | +| | use, and value as listed in this table | ++-------------------------+------------------------------------------------------------------------+ + + +Some examples + +The examples below are valid for the following DAML: + +.. code-block:: daml + + data Rectangle = Rectangle with + length: Decimal + width: Decimal + + data Expr a = Num a + | Product (Expr a) (Expr a) + | Sum (Expr a) (Expr a) + + template CalculateRequest + with + requester: Party + computer: Party + expression: Expr Decimal + + template CalculateResponse + with + requester: Party + computer: Party + value: Decimal + + diff --git a/docs/_sources/dazl.cli.rst.txt b/docs/_sources/dazl.cli.rst.txt new file mode 100644 index 00000000..569fe17e --- /dev/null +++ b/docs/_sources/dazl.cli.rst.txt @@ -0,0 +1,22 @@ +dazl\.cli package +================= + +Submodules +---------- + +dazl\.cli\.ls module +-------------------- + +.. automodule:: dazl.cli.ls + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dazl.cli + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_sources/dazl.client.rst.txt b/docs/_sources/dazl.client.rst.txt new file mode 100644 index 00000000..284c3102 --- /dev/null +++ b/docs/_sources/dazl.client.rst.txt @@ -0,0 +1,30 @@ +dazl\.client package +==================== + +Submodules +---------- + +dazl\.client\.api module +------------------------ + +.. automodule:: dazl.client.api + :members: + :undoc-members: + :show-inheritance: + +dazl\.client\.bots module +---------------------------- + +.. automodule:: dazl.client.bots + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dazl.client + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_sources/dazl.damlast.rst.txt b/docs/_sources/dazl.damlast.rst.txt new file mode 100644 index 00000000..f14b1aae --- /dev/null +++ b/docs/_sources/dazl.damlast.rst.txt @@ -0,0 +1,3 @@ +.. automodule:: dazl.damlast + :members: + :undoc-members: diff --git a/docs/_sources/dazl.damlsdk.rst.txt b/docs/_sources/dazl.damlsdk.rst.txt new file mode 100644 index 00000000..ded65309 --- /dev/null +++ b/docs/_sources/dazl.damlsdk.rst.txt @@ -0,0 +1,3 @@ +.. automodule:: dazl.damlsdk + :members: + :undoc-members: diff --git a/docs/_sources/dazl.model.rst.txt b/docs/_sources/dazl.model.rst.txt new file mode 100644 index 00000000..dc431050 --- /dev/null +++ b/docs/_sources/dazl.model.rst.txt @@ -0,0 +1,3 @@ +.. automodule:: dazl.model + :members: + :undoc-members: diff --git a/docs/_sources/dazl.pretty.rst.txt b/docs/_sources/dazl.pretty.rst.txt new file mode 100644 index 00000000..591e480e --- /dev/null +++ b/docs/_sources/dazl.pretty.rst.txt @@ -0,0 +1,3 @@ +.. automodule:: dazl.pretty + :members: + :undoc-members: diff --git a/docs/_sources/dazl.protocols.rst.txt b/docs/_sources/dazl.protocols.rst.txt new file mode 100644 index 00000000..0601efe0 --- /dev/null +++ b/docs/_sources/dazl.protocols.rst.txt @@ -0,0 +1,30 @@ +dazl\.protocols package +======================= + +Submodules +---------- + +dazl\.protocols\.v0 module +---------------------------- + +.. automodule:: dazl.protocols.v0 + :members: + :undoc-members: + :show-inheritance: + +dazl\.protocols\.v1 module +---------------------------- + +.. automodule:: dazl.protocols.v1 + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: dazl.protocols + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_sources/dazl.rst.txt b/docs/_sources/dazl.rst.txt new file mode 100644 index 00000000..46f00d27 --- /dev/null +++ b/docs/_sources/dazl.rst.txt @@ -0,0 +1,24 @@ +dazl package +============ + +Subpackages +----------- + +.. toctree:: + + dazl.cli + dazl.client + dazl.damlast + dazl.damlsdk + dazl.model + dazl.pretty + dazl.protocols + dazl.util + +Module contents +--------------- + +.. automodule:: dazl + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/_sources/dazl.util.rst.txt b/docs/_sources/dazl.util.rst.txt new file mode 100644 index 00000000..d966e8bd --- /dev/null +++ b/docs/_sources/dazl.util.rst.txt @@ -0,0 +1,3 @@ +.. automodule:: dazl.util + :members: + :undoc-members: diff --git a/docs/_sources/glossary.rst.txt b/docs/_sources/glossary.rst.txt new file mode 100644 index 00000000..b23fab24 --- /dev/null +++ b/docs/_sources/glossary.rst.txt @@ -0,0 +1,7 @@ +Glossary +======== + +.. glossary:: + + dazl + The Python client library for Digital Asset ledgers. \ No newline at end of file diff --git a/docs/_sources/index.rst.txt b/docs/_sources/index.rst.txt new file mode 100644 index 00000000..ef572167 --- /dev/null +++ b/docs/_sources/index.rst.txt @@ -0,0 +1,70 @@ +dazl: DA client library for Python +================================== + +*Version: |release|* + +Dependencies +------------ + +You will need Python 3.6 or later and a Digital Asset ledger implementation (DA Sandbox or +DA Ledger Server). :term:`dazl` additionally requires the following libraries to be +installed: + +* grpcio, version 1.18.0 or later +* PyYAML +* semver + +Getting Started +--------------- + +This section assumes that you already have a running ledger with a DAML model loaded. + +Connect to the ledger and submit a single command:: + + with dazl.simple_client('http://localhost:7600', 'Alice') as client: + client.submit_create('Alice', 'My.Template', { someField: 'someText' }) + +Connect to the ledger as a single party, print all contracts, and close:: + + with dazl.simple_client('http://localhost:7600', 'Alice') as client: + # wait for the ACS to be fully read + client.ready() + contract_dict = client.find_active('*') + print(contract_dict) + +Connect to the ledger as multiple parties:: + + network = dazl.Network() + network.set_config(url='http://localhost:7600') + + alice = network.simple_party('Alice') + bob = network.simple_party('Bob') + + @alice.ledger_ready() + def set_up(event): + currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"}) + return dazl.create('SomethingOf.Value', { + 'amount': 100, + 'currency': currency_cid, + 'from': 'Accept', + 'to': 'Bob' }) + + @bob.ledger_created('SomethingOf.Value') + def on_something_of_value(event): + return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' }) + + network.start() + + +Table of Contents +----------------- + +.. toctree:: + :maxdepth: 4 + :caption: Contents: + + basics + migrating + tutorials + dazl + glossary diff --git a/docs/_sources/migrating.rst.txt b/docs/_sources/migrating.rst.txt new file mode 100644 index 00000000..afd5c809 --- /dev/null +++ b/docs/_sources/migrating.rst.txt @@ -0,0 +1,89 @@ +Migrate +======= + +Migrating from dazl v5 from v4 + + + +Library Initialization +---------------------- + +Old API:: + + # original dazl API + with create_client(participant_url='http://localhost:7600', parties=['Alice', 'Bob']) as manager: + alice_client = manager.client('Alice') + bob_client = manager.client('Bob') + # register some event handlers for Alice and Bob + manager.run_forever() + +New API:: + + # asyncio-based API + network = Network() + network.set_config(url='http://localhost:7600') + + alice_client = network.aio_party('Alice') + bob_client = network.aio_party('Bob') + + # run + alice_client.run_forever() + +Initialization Event Listeners +------------------------------ + +Arguments to event listeners have changed in order to provide more information about events and +for consistency across event handlers. + +Initialization has been collapsed into a single event, where formerly, there were two events +(``on_init`` and ``on_init_metadata``): + +Old API:: + + # original dazl API + client = manager.client('Some Party') + client.on_init(lambda: print('Ledger initialization is happening') + client.on_init_metadata(lambda store: print(f'Ledger package store: {store}')) + +New API:: + + # asyncio-based API + client.add_ledger_init(lambda event: print(f'Ledger initialization with package store: {event.store}')) + +Ready Event Listeners +--------------------- + +Old API:: + + # original dazl API + client = manager.client('Some Party') + client.on_ready(lambda party_name, client\_: print(f'Party {party_name} is ready')) + +New API:: + + # asyncio-based API + client = network.aio_party('Some Party') + client.add_ledger_ready(lambda event: print(f'Party {event.party} is ready')) + +Create/Archive Event Listeners +------------------------------ + +Create and archive events now take a single parameter, called ``event`` by convention, that contain +the contract ID, contract data, and additional metadata about the event, such as the time of +execution, ledger ID, and access to the active contract set. + +Old API:: + + # original dazl API + client = manager.client('Some Party') + client.on_created('Some.Asset', lambda cid, cdata: print(cid, cdata)) + client.on_archived('Some.Asset', lambda cid: print(cid)) + +New API:: + + # asyncio-based API + client = network.aio_party('Some Party') + client.add_ledger_created('Some.Asset', lambda event: print(event.cid, event.cdata)) + client.add_ledger_archived('Some.Asset', lambda event: print(event.cid)) + + diff --git a/docs/_sources/tutorials.rst.txt b/docs/_sources/tutorials.rst.txt new file mode 100644 index 00000000..595bfb78 --- /dev/null +++ b/docs/_sources/tutorials.rst.txt @@ -0,0 +1,9 @@ +Tutorials +========= + +.. toctree:: + :name: tutorials + + tutorials_post_office + tutorials_workflow_state + tutorials_message_ingester diff --git a/docs/_sources/tutorials_message_ingester.rst.txt b/docs/_sources/tutorials_message_ingester.rst.txt new file mode 100644 index 00000000..089827f5 --- /dev/null +++ b/docs/_sources/tutorials_message_ingester.rst.txt @@ -0,0 +1,108 @@ +.. _tutorials_message_ingester: + +Message Ingester +================ + +This example sets up a workflow involving two parties, ``Alice`` and ``Bob``. When writing a DAML +application, we recommend the following steps: + + 1. Describe your workflow as a series of contracts in DAML. + 2. Write one or more DAML test scenarios that walk through each step of the workflow, starting from creation of the genesis contract, through a sequence of ``exercise`` commands, to the final state of the workflow. (Note: The DAML test scenarios are used for verifying the steps of the workflow in a sequential manner. However, when the workflow is deployed to a live platflorm, the events that prompt steps in the workflow to move forward cannot be assumed to occur sequentially.) + 3. Write your application. + 4. Test your application on the sandbox. The ledger server implements the same API, so performance testing can be done with the same application. + +The Message Ingester workflow is as follows: + +1. The genesis contract, ``OperatorRole``, is created. The ``OperatorRole`` contract is a contract that describes the operation(s) that the operator of this workflow can perform. In this example, we have assigned the party name ``Alice`` to the OperatorRole. +2. ``Alice`` ingests an input message, which causes the generation of a ``TradeRequest`` contract. +3. ``Bob`` is the ``requestProcessingParty`` on the ``TradeRequest`` contract, and exercises the + ``AcceptMessage`` choice on the ``TradeRequest``. This causes the generation of a ``TradeResponse`` contract. +4. ``Alice`` exercises the ``Acknowledge`` choice on the ``TradeResponse`` contract. + This causes the generation of a ``WorkflowCompleted`` contract. + +DAML Model +---------- + +This example assumes the following DAML: + +.. literalinclude:: ../tests/tutorials/message_ingester/MessageIngester.daml + :language: daml + +The ``messageIngesterTest`` scenario describes a sample execution of the workflow, and is the basis from from which +our Python application will be designed. + +Python Application +------------------ + +.. literalinclude:: ../tests/tutorials/message_ingester/message_ingester.py + :language: python + :linenos: + +To run this code sample: + 1. Download the SDK + 2. create a new project: ``da new my-project-name-here`` + 3. ``cd my-project-name-here`` + 4. Create a file, MessageIngester.daml, that contains the above listed DAML. + 5. Createa file, message_ingester.py, that contains the above listed Python code. + 6. Download the dazl-starter template (which also creates a Python venv): ``da project add dazl-starter`` + 7. Start the sandbox: ``da sandbox`` + 8. Run the application: ``./venv/bin/python3 message_ingester.py`` + +:func:`run` configures client_mgr such that it will invoke the :func:`work` function after +it has successfully connected to the platform/sandbox. + +:func:`work` contains a command to create the genesis contract, and a series of callback registrations, +each of which provide a reference to a custom python function that shall be invoked when a certain +leger event occurs. For example, this registration: + +.. literalinclude:: ../tests/tutorials/message_ingester/message_ingester.py + :language: python + :start-after: # DOC_BEGIN: SAMPLE_CALLBACK_ONCREATED + :end-before: # DOC_END: SAMPLE_CALLBACK_ONCREATED + +indicates that the :func:`ingest_the_message` shall be invoked after the ``OperatorRole`` contract is +created. + +:func:`ingest_the_message` describes what will happen when at ``on_created`` event occurs: + 1. The DAZL framework, upon detecting the specified ``on_created`` event, will invoke this function and pass it the contract id (``cid``) and corresponding contract parameters (``cdata``). + 2. An ``exercise`` choice will be performed on the contract (in this case, it's an ``OperatorRole`` contract) + 3. That ``exercise`` choice will be invoked on a DAML contract with a contract id of ``cid``, with the specified parameters. + 4. Since this is a non-consuming choice, the ``OperatorRole`` contract will remain active. + +.. literalinclude:: ../tests/tutorials/message_ingester/message_ingester.py + :language: python + :start-after: # DOC_BEGIN: FUNCTION_INGEST_THE_MESSAGE + :end-before: # DOC_BEGIN: FUNCTION_INGEST_THE_MESSAGE + +The :func:`exercise` call in the above code snippet corresponds to this line in our DAML test scenario: + +.. literalinclude:: ../tests/tutorials/message_ingester/MessageIngester.daml + :language: daml + :start-after: -- DOC_BEGIN: SAMPLE_DAML_SCENARIO_INGEST_MESSAGE + :end-before: -- DOC_END: SAMPLE_DAML_SCENARIO_INGEST_MESSAGE + +Thus, a typical application would have a similar structure to :func:`work` in that it will contain only one command +to create the genesis contract, and all other code will describe the callback handlers and the situations under which +those callbacks shall be invoked. + +Application Output +------------------ + +This application will produce this output:: + + 2 total contracts over 2 templates + +- party 'Alice' (block heights 1 to 5) + |+ party 'Bob' (block heights 2 to 5) + || + + MessageIngester.OperatorRole (1 contract) ------------------------------------------------------------------------------ + #cid operator + C 0:0_ Alice + + MessageIngester.WorkflowCompleted (1 contract) ------------------------------------------------------------------------- + #cid acknowledgingParty originalMessageIngestedTime TradeResponseAcknowledgedTime + C 3:2_ Alice 1970-01-01T00:00:00Z 1970-01-01T00:00:00Z + +The ``TradeRequest`` and ``TradeResponse`` contracts were created, and subsequently archived during the course +of the workflow, thus only ``OperatorRole`` ``WorkflowCompleted`` and (which has no consuming choices) are active on the ledger +when this application terminates. diff --git a/docs/_sources/tutorials_post_office.rst.txt b/docs/_sources/tutorials_post_office.rst.txt new file mode 100644 index 00000000..3d7b9e1d --- /dev/null +++ b/docs/_sources/tutorials_post_office.rst.txt @@ -0,0 +1,147 @@ +.. _tutorials_post_office: + +Post Office +=========== + +This example sets up a post office, with a ``Postman`` who routes letters, instances of ``Author`` +who send letters, and instances of ``Receiver`` who receive letters. + +Each author, when instantiated, will immediately send letters to five of their friends. + +DAML Model +---------- + +This example assumes the following DAML: + +.. literalinclude:: ../tests/tutorials/post_office/Main.daml + :language: daml + +Create the Postman +------------------ + +The Postman serves as the operator of this market, and its role contract must be defined before +anything else can happen: + +If you are running this code example through the SDK, it will: + 1. start up a Ledger Sandbox in the background, point it to the above DAML model, + 2. run the code against that Ledger Sandbox, and + 3. stop the Ledger Sandbox. + +First, a few important imports: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :start-after: # DOC_BEGIN: IMPORTS_CONSTANTS + :end-before: # DOC_END: IMPORTS_CONSTANTS + :name: imports_and_constants + +Then the main dish: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :dedent: 4 + :start-after: # DOC_BEGIN: CREATE_POSTMAN + :end-before: # DOC_END: CREATE_POSTMAN + :name: run_test_create_postman + +Lastly, the code that actually runs everything: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :dedent: 4 + :start-after: # DOC_BEGIN: MAIN-BOILERPLATE + :end-before: # DOC_END: MAIN-BOILERPLATE + +.. note:: + + :func:`dazl.sandbox` is a helper function for creating a disposable sandbox, running + a test, and terminating the process. You wouldn't use it when pointing to a production instance, + but it is very useful for testing. All of these examples assume that you are using a blank + ledger every single time. As you iterate through the steps of the tutorial, make sure to stop and + start the ledger each time if you're using :func:`dazl.sandbox`. + +:func:`dazl.simple_client` is a helper function for creating a :class:`LedgerClientManager`. +At a minimum, you must provide it a list of parties to listen as, and a URL to the Sandbox +(or Ledger Server participant node when running against a real instance). + +To create a client for a specific party, call :meth:`LedgerClientManager.new_client`. There are +several key methods on it; this example introduces ``ParticipantLedgerClient.on_ready``, which is +called when the connection to the ledger is initialized. The parameters are ignored at this point. +The callback, like most callbacks, can return a ``Command`` to submit to the ledger. In this +example, a ``Main.postmanRole`` contract is to be created with one argument named ``postman`` +and a value of ``'Postman'`` + +Finally, to actually start the manager and all the clients, call +``LedgerClientManager.run_until_complete``. The code should run and return an exit code of 0, +indicating that the script successfully ran. But what if you wanted to actually see what happened +to the ledger afterwards? + + +Inspect the Ledger +------------------ + +Using the convenience ``sandbox()`` method makes development a bit quicker, but it is difficult to +actually see what is happening afterwards because it tears down the ledger and all of its state. +You could either start a Sandbox instance manually through the SDK, or you could output the ledger +after every run: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :dedent: 4 + :start-after: # DOC_BEGIN: INSPECT_LEDGER + :end-before: # DOC_END: INSPECT_LEDGER + +We have added :class:`dazl.plugin.LedgerCapturePlugin`, which listens for events from the ledger and +stores them internally to be drawn out later. The main body of ``run_test`` outputs the result of +the ledger in a ``try``/``finally`` block so that the ledger is always printed out, even if an +exception occurs. + +:class:`dazl.plugin.LedgerCapturePlugin` exposes several class methods for easily creating an +instance; in this example, ``LedgerCapturePlugin`` outputs its results to ``stdout`` when +``dump_all`` is called. + + +Set up participants +------------------- + +We have now created the postman and can see that on the ledger; now we'll add the other participants +of this market. For readability, let's also split out all the registration methods into a separate +``set_up`` function so that we can keep the focus on adding listeners to the ledger: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :dedent: 4 + :start-after: # DOC_BEGIN: INVITE_PARTICIPANTS + :end-before: # DOC_END: INVITE_PARTICIPANTS + +The ``on_created`` method allows you to add an event handler for templates as they are created on +the ledger. Like the ``on_ready`` method above, you can return a ``Command`` (or in this case, a +``list`` of ``Command``) that is to be executed in response to this event. + +After running the script, you should see a few more columns in the output for all the new parties, +and you can see that the parties now see invitation contracts that they can exercise choices on. To +further progress the workflow, let's add more callbacks in ``set_up``: + +.. literalinclude:: ../tests/tutorials/post_office/tutorial.py + :language: python + :dedent: 4 + :start-after: # DOC_BEGIN: ACCEPT_INVITES + :end-before: # DOC_END: ACCEPT_INVITES + +Now notice that the ``inviteAsAuthor`` and ``inviteAsReceiver`` contracts are no longer in the +output, instead replaced with ``authorRole`` and ``receiverRole`` contracts; that's because the +``accept`` choice on these contracts is a consuming choice. + +In order to respond to these contracts as other parties, we have also created new clients, one for +every additional party. Now that we have a universe of participants fully set up and ready to go, +let's do some actual work. + + +Send some "letters" through the post office +------------------------------------------- + +Once a participant's ``Main.authorRole`` is created, that participant is now granted the ability to +send letters to other participants in the market. + +-- TBC -- + diff --git a/docs/_sources/tutorials_workflow_state.rst.txt b/docs/_sources/tutorials_workflow_state.rst.txt new file mode 100644 index 00000000..2e47ecff --- /dev/null +++ b/docs/_sources/tutorials_workflow_state.rst.txt @@ -0,0 +1,114 @@ +.. _tutorials_workflow_state: + +Workflow State Example +====================== + +The purpose of this example is to demonstrate a multi-contract-creation dependency use-case: a sitution where the application must wait for multiple contracts to be created before it can proceed to the next step. This is similar to the "Message Ingester" sample application, but with the key difference that the state transitions in the "Message Ingester" workflow each depend solely on a single contract creation. + +The workflow involving three parties: ``Alice``, ``Bob``, and ``Operator``. When writing a DAML +application, we recommend the following steps: + + 1. Describe your workflow as a series of contracts in DAML. + 2. Write one or more DAML test scenarios that walk through each step of the workflow, starting from creation of the genesis contract, through a sequence of ``exercise`` commands, to the final state of the workflow. (Note: The DAML test scenarios are used for verifying the steps of the workflow in a sequential manner. However, when the workflow is deployed to a live platflorm, the events that prompt steps in the workflow to move forward cannot be assumed to occur sequentially.) + 3. Write your application. + 4. Test your application on the sandbox. The ledger server implements the same API, so performance testing can be done with the same application. + + +The workflow for this application is as follows: + +1. The ``GenesisContract``, is created. It describes the operation(s) that the operator of this workflow can perform. In this example, we have assigned the party name ``Operator`` to the GenesisContract. +2. ``Operator`` invites the ``Bob`` to be the ticket seller, and also invites ``Alice`` to be the ticket buyer. +3. Only after BOTH ``Alice`` and ``Bob`` have accepted their respective invitations can the workflow progress to the next state (``TicketTransactionsInProgress``) +4. A ticket transaction occurs. +5. The workflow is completed. + +DAML Model +---------- + +``WorkflowStateExample.daml`` + +.. literalinclude:: ../tests/tutorials/workflow_state/daml/WorkflowStateExample.daml + :language: daml + +The ``ticketTransactionTest`` scenario describes a sample execution of the workflow, and is the basis from from which +our Python application will be designed. + +Python Application +------------------ + +``store.py`` + +.. literalinclude:: ../tests/tutorials/workflow_state/store.py + :language: python + +``workflow_state_example.py`` + +.. literalinclude:: ../tests/tutorials/workflow_state/workflow_state_example.py + :language: python + +To run this code sample: + 1. Download the SDK + 2. create a new project: ``da new my-project-name-here`` + 3. ``cd my-project-name-here`` + 4. Create a file, WorkflowStateExample.daml, that contains the above listed DAML. + 5. Create a file, workflow_state_sample.py, that contains the Python code for "workflow_state_example.py" listed above. + 6. Create a file, store.py, that contains, that contains the Python code for "store.py" listed above. + 7. Download the dazl-starter template (which also creates a Python venv): ``da project add dazl-starter`` + 8. Run the application: ``./venv/bin/python3 workflow_state_example.py`` + +:func:`accept_ticket_seller_invite` and :func:`accept_ticket_buyer_invite` store their respective contracts into ``contract_store``. This is the first step in setting up a multi-contract-creation dependency. + +.. literalinclude:: ../tests/tutorials/workflow_state/workflow_state_example.py + :language: python + :start-after: # DOC_BEGIN: FUNCTION_ACCEPT_INVITE + :end-before: # DOC_END: FUNCTION_ACCEPT_INVITE + +:func:`transition_to_ticket_transactions_in_progress` performs lookups into ``contract_store``. These lookups will wait until the specified contract keys are present in the ``contract_store``, and only perform the ``exercise`` command after that point. Thus, BOTH the `TicketSellerRole` and the `TicketBuyerRole` must be created before the application can transition to the next step in the workflow. + +.. literalinclude:: ../tests/tutorials/workflow_state/workflow_state_example.py + :language: python + :start-after: # DOC_BEGIN: FUNCTION_MULTI_CREATION_DEPENDENCY + :end-before: # DOC_END: FUNCTION_MULTI_CREATION_DEPENDENCY + +Application Output +------------------ + +This application will produce this output:: + + [Info] Starting: + Sandbox ledger server + .../daml/WorkflowStateExample.daml + with no scenario and binding to port 7600 + Waiting for Sandbox...ok + 5 total contracts over 5 templates + +-- party 'Alice' (block heights 2 to 9) + |+- party 'Bob' (block heights 2 to 9) + ||+ party 'Operator' (block heights 1 to 9) + ||| + + WorkflowStateExample.GenesisContract (1 contract) ---------------------------------------------------------------------- + #cid operator + C 0:0_ Operator + + WorkflowStateExample.TicketBuyerRole (1 contract) ---------------------------------------------------------------------- + #cid operator ticketBuyer + C 2:2_ Operator Alice + + WorkflowStateExample.TicketPurchaseAgreement (1 contract) -------------------------------------------------------------- + #cid operator ticketBuyer ticketSeller + CC 6:2_ Operator Alice Bob + + WorkflowStateExample.TicketSellerRole (1 contract) --------------------------------------------------------------------- + #cid operator ticketSeller + C 3:2_ Operator Bob + + WorkflowStateExample.WorkflowCompleted (1 contract) -------------------------------------------------------------------- + #cid operator + C 7:2_ Operator + stopping... Sandbox ledger server + .../daml/WorkflowStateExample.daml + with no scenario and binding to port 7600 + + Process finished with exit code 0 + +Thus, a ``TicketPurchaseAgreement`` is created. Also note that the contracts representing intermediate steps in the workflow (``WorkflowSetupInProgress``, and ``WorkflowTicketTransactionsInProgress``) were created and then subsequently archived. Only the contract representing the final state, ``WorkflowCompleted`` is active. diff --git a/docs/_static/basic.css b/docs/_static/basic.css new file mode 100644 index 00000000..c41d718e --- /dev/null +++ b/docs/_static/basic.css @@ -0,0 +1,763 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox 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 div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a.brackets:before, +span.brackets > a:before{ + content: "["; +} + +a.brackets:after, +span.brackets > a:after { + content: "]"; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.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 { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > p:first-child, +td > p:first-child { + margin-top: 0px; +} + +th > p:last-child, +td > p:last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + +/* -- 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 td { + vertical-align: top; +} + + +/* -- 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; +} + +li > p:first-child { + margin-top: 0px; +} + +li > p:last-child { + margin-bottom: 0px; +} + +dl.footnote > dt, +dl.citation > dt { + float: left; +} + +dl.footnote > dd, +dl.citation > dd { + margin-bottom: 0em; +} + +dl.footnote > dd:after, +dl.citation > dd:after { + content: ""; + clear: both; +} + +dl.field-list { + display: flex; + flex-wrap: wrap; +} + +dl.field-list > dt { + flex-basis: 20%; + font-weight: bold; + word-break: break-word; +} + +dl.field-list > dt:after { + content: ":"; +} + +dl.field-list > dd { + flex-basis: 70%; + padding-left: 1em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > p:first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0.5em; + content: ":"; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: relative; + left: 0px; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/_static/css/theme.css b/docs/_static/css/theme.css new file mode 100644 index 00000000..ef994823 --- /dev/null +++ b/docs/_static/css/theme.css @@ -0,0 +1,39 @@ +@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap'); +@import url('https://fonts.googleapis.com/css?family=Source+Code+Pro&display=swap'); + +body { + font-family: "Open Sans", sans-serif; + display: flex; + flex-flow: row wrap; + background: #F2F3F7; + color: #354C86; +} + +pre { + font-family: "Source Code Pro", monospace; + background: #F2F3F7; +} + +.pre { + font-family: "Source Code Pro", monospace; +} + +header { + flex: 1 100%; +} + +nav { + flex: 0 auto; + width: 300px; +} + +main { + flex: 1 0; + background: white; + padding: 10px; + box-sizing: border-box; +} + +footer { + flex: 1 100%; +} diff --git a/docs/_static/doctools.js b/docs/_static/doctools.js new file mode 100644 index 00000000..b33f87fc --- /dev/null +++ b/docs/_static/doctools.js @@ -0,0 +1,314 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated === 'undefined') + return string; + return (typeof translated === 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated === 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) === 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this === '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/docs/_static/documentation_options.js b/docs/_static/documentation_options.js new file mode 100644 index 00000000..d8a5fb6a --- /dev/null +++ b/docs/_static/documentation_options.js @@ -0,0 +1,10 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: 'unknown', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + FILE_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false +}; \ No newline at end of file diff --git a/docs/_static/file.png b/docs/_static/file.png new file mode 100644 index 0000000000000000000000000000000000000000..a858a410e4faa62ce324d814e4b816fff83a6fb3 GIT binary patch literal 286 zcmV+(0pb3MP)s`hMrGg#P~ix$^RISR_I47Y|r1 z_CyJOe}D1){SET-^Amu_i71Lt6eYfZjRyw@I6OQAIXXHDfiX^GbOlHe=Ae4>0m)d(f|Me07*qoM6N<$f}vM^LjV8( literal 0 HcmV?d00001 diff --git a/docs/_static/jquery-3.2.1.js b/docs/_static/jquery-3.2.1.js new file mode 100644 index 00000000..d2d8ca47 --- /dev/null +++ b/docs/_static/jquery-3.2.1.js @@ -0,0 +1,10253 @@ +/*! + * jQuery JavaScript Library v3.2.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2017-03-20T18:59Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +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 = {}; + + + + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* 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.2.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +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 ); + }, + + 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" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && Array.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); + }, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // 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 ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + 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; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + 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 concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +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 = jQuery.type( obj ); + + if ( type === "function" || jQuery.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.3 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-08-08 + */ +(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(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = 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]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // 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 + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + 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" ) + }, + + 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-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // 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(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true && ("form" in elem || "label" in elem); + }, + { 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 + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var 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 ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + 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 && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // 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 + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } 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 && + disabledAncestor( 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 ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + 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 + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + 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 ); + } + } + + /* 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 ) { + // 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("~="); + } + + // 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(".#.+[+~]"); + } + }); + + 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" ); + } + + // 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 + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + 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 ) { + return a === document ? -1 : + b === document ? 1 : + 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 + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ 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) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.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 += ""; + + 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; + }; + }, + + "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 || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": 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 ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + 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 ) { + 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; + 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 ); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + 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; + } ); + } + + // Simple selector that can be filtered directly, removing non-Elements + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + // Complex selector, compare the two sets, removing non-Elements + qualifier = jQuery.filter( qualifier, elements ); + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; + } ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + 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 ( jQuery.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 ( nodeName( elem, "iframe" ) ) { + 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 ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( 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 && jQuery.isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && jQuery.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 = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + 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 ( jQuery.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, + jQuery.isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.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, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( 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 ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < 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; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ jQuery.camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ jQuery.camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ jQuery.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( jQuery.camelCase ); + } else { + key = jQuery.camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.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 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. + jQuery.contains( elem.ownerDocument, elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + +var swap = function( elem, options, callback, args ) { + 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.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + 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 = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + do { + + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } + + 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 = ( /^$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE <=9 only + option: [ 1, "" ], + + // 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, "", "" ] +}; + +// Support: IE <=9 only +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, 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 ( jQuery.type( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); +var documentElement = document.documentElement; + + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 only +// See #13393 for more info +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 ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // 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 = {}; + } + 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 ) { + + // Make a writable jQuery.Event from the native event object + var event = jQuery.event.fix( nativeEvent ); + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + 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() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: jQuery.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 + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.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, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +// 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 + + /* eslint-disable max-len */ + + // See https://github.com/eslint/eslint/issues/3229 + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, + + /* eslint-enable */ + + // Support: IE <=10 - 11, Edge 12 - 13 + // 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( ">tbody", elem )[ 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 ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.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 = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), 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 && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, 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 rmargin = ( /^margin/ ); + +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + + + +( 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; + } + + div.style.cssText = + "box-sizing:border-box;" + + "position:relative;display:block;" + + "margin:auto;border:1px;padding:1px;" + + "top:1%;width:50%"; + div.innerHTML = ""; + documentElement.appendChild( container ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = divStyle.marginLeft === "2px"; + boxSizingReliableVal = divStyle.width === "4px"; + + // Support: Android 4.0 - 4.3 only + // Some styles come back with percentage values, even though they shouldn't + div.style.marginRight = "50%"; + pixelMarginRightVal = divStyle.marginRight === "4px"; + + 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; + } + + var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + + "padding:0;margin-top:1px;position:absolute"; + container.appendChild( div ); + + jQuery.extend( support, { + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelMarginRight: function() { + computeStyleTests(); + return pixelMarginRightVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, 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.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.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 + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }, + + cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style; + +// Return a css property mapped to a potentially vendor prefixed property +function vendorPropName( name ) { + + // Shortcut for names that are not vendor prefixed + if ( name in emptyStyle ) { + return name; + } + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a property mapped along what jQuery.cssProps suggests or to +// a vendor prefixed property. +function finalPropName( name ) { + var ret = jQuery.cssProps[ name ]; + if ( !ret ) { + ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; + } + return ret; +} + +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 augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i, + val = 0; + + // If we already have the right measurement, avoid augmentation + if ( extra === ( isBorderBox ? "border" : "content" ) ) { + i = 4; + + // Otherwise initialize for horizontal or vertical properties + } else { + i = name === "width" ? 1 : 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // At this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + + // At this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // At this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with computed style + var valueIsBorderBox, + styles = getStyles( elem ), + val = curCSS( elem, name, styles ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test( val ) ) { + return val; + } + + // Check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && + ( support.boxSizingReliable() || val === elem.style[ name ] ); + + // Fall back to offsetWidth/Height when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + if ( val === "auto" ) { + val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; + } + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + + // Use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "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, + "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: { + "float": "cssFloat" + }, + + // 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 = jQuery.camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + if ( type === "number" ) { + 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 = jQuery.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, name ) { + jQuery.cssHooks[ name ] = { + 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, name, extra ); + } ) : + getWidthOrHeight( elem, name, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = extra && getStyles( elem ), + subtract = extra && augmentWidthOrHeight( + elem, + name, + extra, + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + styles + ); + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ name ] = value; + value = jQuery.css( elem, name ); + } + + 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 ( !rmargin.test( prefix ) ) { + 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 && + ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || + jQuery.cssHooks[ tween.prop ] ) ) { + 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 = jQuery.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 - 13 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY + 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 = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( jQuery.isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + jQuery.proxy( result.stop, result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( jQuery.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 ( jQuery.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 || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.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 ( jQuery.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 && type !== false ) { + 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 = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnothtmlwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnothtmlwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( type === "string" ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = value.match( rnothtmlwhite ) || []; + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, isFunction, + 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; + } + + isFunction = jQuery.isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + 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 ); + } + } +} ); + + +jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup contextmenu" ).split( " " ), + function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; +} ); + +jQuery.fn.extend( { + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +} ); + + + + +support.focusin = "onfocusin" in window; + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// 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() { + var doc = this.ownerDocument || 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, + 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 = jQuery.now(); + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && jQuery.type( 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 = jQuery.isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( jQuery.isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match == null ? null : match; + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 13 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available, append data to url + if ( s.data ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + 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 ); + } + + // 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 ( jQuery.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._evalUrl = function( url ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + "throws": true + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( jQuery.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 ( jQuery.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 isFunction = jQuery.isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.cli.html b/docs/dazl.cli.html new file mode 100644 index 00000000..44244196 --- /dev/null +++ b/docs/dazl.cli.html @@ -0,0 +1,171 @@ + + + + + + + + dazl.cli package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.cli package

+
+

Submodules

+
+
+

dazl.cli.ls module

+
+
+class dazl.cli.ls.ListAllCommand[source]
+

Bases: dazl.cli._base.CliCommand

+
+
+execute(args) → int[source]
+
+ +
+
+name = 'ls'
+
+ +
+
+parser() → argparse.ArgumentParser[source]
+
+ +
+ +
+
+

Module contents

+

Simple command-line handlers.

+
+
+dazl.cli.main()[source]
+

Executes one of the known commands.

+
+ +
+
+dazl.cli.print_cmd_help()[source]
+
+ +
+
+dazl.cli.run(cmd, args) → int[source]
+
+ +
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.client.html b/docs/dazl.client.html new file mode 100644 index 00000000..ca019f58 --- /dev/null +++ b/docs/dazl.client.html @@ -0,0 +1,1554 @@ + + + + + + + + dazl.client package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.client package

+
+

Submodules

+
+
+

dazl.client.api module

+

This module contains the public API for interacting with the ledger from the perspective of a +specific party.

+
+
+class dazl.client.api.AIOGlobalClient(impl: dazl.client._network_client_impl._NetworkImpl)[source]
+

Bases: dazl.client.api.GlobalClient

+
+
+async ensure_dar(contents: Union[str, pathlib.Path, bytes, BinaryIO], timeout: Union[int, float, decimal.Decimal, str, datetime.timedelta] = 30) → None[source]
+

Validate that the ledger has the packages specified by the given contents (as a byte array). +Throw an exception if the specified DARs do not exist within the specified timeout.

+
+
Parameters
+
    +
  • contents – The DAR or DALF to ensure.

  • +
  • timeout – The maximum length of time to wait before giving up.

  • +
+
+
+
+ +
+
+async ensure_packages(package_ids: Collection[str], timeout: Union[int, float, decimal.Decimal, str, datetime.timedelta] = 30) → None[source]
+

Validate that packages with the specified package IDs exist on the ledger. Throw an +exception if the specified packages do not exist within the specified timeout.

+
+
Parameters
+
    +
  • package_ids – The set of package IDs to check for.

  • +
  • timeout – The maximum length of time to wait before giving up.

  • +
+
+
+
+ +
+
+async get_time() → datetime.datetime[source]
+
+ +
+
+async metadata() → dazl.model.ledger.LedgerMetadata[source]
+

Return the current set of known packages.

+
+ +
+
+async set_time(new_datetime: datetime.datetime) → None[source]
+
+ +
+ +
+
+class dazl.client.api.AIOPartyClient(impl: dazl.client._party_client_impl._PartyClientImpl)[source]
+

Bases: dazl.client.api.PartyClient

+

Implementation of a PartyClient that exposes an async/await-style API that runs on +an event loop.

+
+
+add_ledger_archived(template: Any, handler: Callable[dazl.model.reading.ContractArchiveEvent], match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → None[source]
+

Register a callback to be invoked when the PartyClient encounters a newly archived +contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • handler – The callback to invoke whenever a matching template is created.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+add_ledger_created(template: Any, handler: Callable[dazl.model.reading.ContractCreateEvent], match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → dazl.client.bots.Bot[source]
+

Register a callback to be invoked when the PartyClient encounters a newly created +contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • handler – The callback to invoke whenever a matching template is created.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+add_ledger_exercised(template: Any, choice: str, handler: Callable[dazl.model.reading.ContractExercisedEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient encounters an exercised +choice event.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • choice – The name of the choice to listen for exercises on.

  • +
  • handler – The callback to invoke whenever a matching template is exercised.

  • +
+
+
+
+ +
+
+add_ledger_init(handler: Callable[dazl.model.reading.InitEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient has been instructed to +begin, but before any network activity is started.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+add_ledger_packages_added(handler: Callable[dazl.model.reading.PackagesAddedEvent], initial: bool = False) → None[source]
+

Register a callback to be invoked when the PartyClient has detected new packages +added to the ledger.

+
+
Parameters
+
    +
  • handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

  • +
  • initialTrue to call the handler when the client is ready. This can be useful if you want +to handle package additions identically whether they were already in the ledger when +the client started up or only after a package has been added. The default value is +False, which means that this handler is only called on NEW packages that have been +uploaded after this client has started.

  • +
+
+
Returns
+

+
+
+
+ +
+
+add_ledger_ready(handler: Callable[dazl.model.reading.ReadyEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient has caught up to the head of +the ledger, but before any ledger_create() or ledger_archive() callbacks are +invoked.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+add_ledger_transaction_end(handler: Callable[dazl.model.reading.TransactionEndEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient receives a new transaction. +Called after individual ledger_create() and ledger_archive() callbacks.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+add_ledger_transaction_start(handler: Callable[dazl.model.reading.TransactionStartEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient receives a new transaction. +Called before individual ledger_create() and ledger_archive() callbacks.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+find(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None, include_archived: bool = False) → dazl.model.core.ContractContextualDataCollection[source]
+
+ +
+
+find_active(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Dict[dazl.model.core.ContractId, Dict[str, Any]][source]
+

Immediately return data from the current active contract set.

+

The contents of this ACS are guaranteed to be present (or removed) in the current +transaction _before_ processing any corresponding on_created or on_archived +callbacks for this party. The ACS is populated _before_ processing any on_ready +callbacks.

+

This method raises an error if ACS tracking has been disabled on this client.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
+
+
Returns
+

A dict whose keys are ContractId and values are corresponding contract +data that match the current query.

+
+
+
+ +
+
+find_by_id(cid: Union[str, dazl.model.core.ContractId]) → Optional[dazl.model.core.ContractContextualData][source]
+
+ +
+
+find_historical(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → dazl.model.core.ContractContextualDataCollection[source]
+

Immediately return data from the current active and historical contract set as +a contextual data collection

+

The contents of this set are guaranteed to be up-to-date in the current transaction _before_ +processing any corresponding on_created or on_archived callbacks for this party. The +set is up-to-date _before_ processing any on_ready callbacks.

+

This method raises an error if historical tracking has been disabled on this client.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
+
+
Returns
+

A ContractContextualDataCollection whose values correspond to the contract +data for active and archived contracts matching the current query.

+
+
+
+ +
+
+find_nonempty(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]], min_count: int = 1, timeout: float = 30) → Awaitable[Dict[dazl.model.core.ContractId, Dict[str, Any]]][source]
+

Return data from the current active contract set when at least some amount of rows exist in +the active contract set.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
  • min_count – The minimum number of rows to return. The default value is 1.

  • +
  • timeout – Number of seconds in which to time out the search.

  • +
+
+
Returns
+

A Future that is resolved with a dict whose keys are ContractId and +values are corresponding contract data that match the current query.

+
+
+
+ +
+
+find_one(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None, timeout: float = 30) → Awaitable[Tuple[dazl.model.core.ContractId, Dict[str, Any]]][source]
+

Return data from the current active contract set when at least some amount of rows exist in +the active contract set.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
  • timeout – Number of seconds in which to time out the search.

  • +
+
+
Returns
+

A Future that is resolved with a dict whose keys are ContractId and +values are corresponding contract data that match the current query.

+
+
+
+ +
+
+get_time() → Awaitable[datetime.datetime][source]
+

Return the current time on the remote server. Also advance the local notion of time if +required.

+
+ +
+
+ledger_archived(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Callable[dazl.model.reading.ContractArchiveEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient encounters +a newly archived contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+ledger_created(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Callable[dazl.model.reading.ContractCreateEvent][source]
+

Register a callback to be invoked when the PartyClient encounters a newly created +template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+ledger_exercised(template: Any, choice: str) → Callable[dazl.model.reading.ContractExercisedEvent][source]
+

Register a callback to be invoked when the PartyClient encounters an exercised +choice event.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • choice – The name of the choice to listen for exercises on.

  • +
+
+
+
+ +
+
+ledger_init() → Callable[dazl.model.reading.InitEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has been +instructed to begin, but before any network activity is started.

+
+ +
+
+ledger_packages_added(initial: bool = False) → Callable[dazl.model.reading.PackagesAddedEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has +detected new packages added to the ledger.

+
+
Parameters
+

initialTrue to call the handler when the client is ready. This can be useful if you want +to handle package additions identically whether they were already in the ledger when +the client started up or only after a package has been added. The default value is +False, which means that this handler is only called on NEW packages that have been +uploaded after this client has started.

+
+
Returns
+

+
+
+
+ +
+
+ledger_ready() → Callable[dazl.model.reading.ReadyEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has caught +up to the head of the ledger, but before any ledger_create() or ledger_archive() +callbacks are invoked.

+
+ +
+
+ledger_transaction_end() → Callable[dazl.model.reading.TransactionEndEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient receives a +new transaction. Called after individual ledger_create() and ledger_archive() +callbacks.

+
+ +
+
+ledger_transaction_start() → Callable[dazl.model.reading.TransactionStartEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient receives a +new transaction. Called before individual ledger_create() and ledger_archive() +callbacks.

+
+ +
+
+ready() → Awaitable[None][source]
+

Block until the ledger client has caught up to the current head and is ready to send +commands.

+
+ +
+
+set_config(url: Optional[str], **kwargs)[source]
+
+ +
+
+set_time(new_datetime: datetime.datetime) → Awaitable[None][source]
+

Set the current time on the ledger. This is only supported if the ledger supports time +manipulation.

+
+ +
+
+submit(commands: Union[None, Command, List[Optional[Command]], CommandBuilder, CommandPayload], workflow_id: Optional[str] = None) → Awaitable[None][source]
+

Submit commands to the ledger.

+
+
Parameters
+
    +
  • commands – An object that can be converted to a command.

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
Returns
+

A future that resolves when the command has made it to the ledger _or_ an error +occurred when trying to process them.

+
+
+
+ +
+
+submit_create(template_name: str, arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → Awaitable[None][source]
+

Submit a single create command. Equivalent to calling submit() with a single +create.

+
+
Parameters
+
    +
  • template_name – The name of the template.

  • +
  • arguments – The arguments to the create (as a dict).

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
Returns
+

A future that resolves when the command has made it to the ledger _or_ an error +occurred when trying to process them.

+
+
+
+ +
+
+submit_create_and_exercise(template_name: Union[str, dazl.model.types.TypeReference, dazl.model.types.UnresolvedTypeReference, dazl.model.types.Template], arguments: dict, choice_name: str, choice_arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → Awaitable[None][source]
+

Synchronously submit a single create-and-exercise command. Equivalent to calling +submit() with a single create_and_exercise.

+
+
Parameters
+
    +
  • template_name – The name of the template on which to do an exercise-by-key.

  • +
  • arguments – The arguments to the create (as a dict).

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • choice_arguments – The arguments to the exercise (as a dict). Can be omitted (None) for no-argument

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+
+submit_exercise(cid: dazl.model.core.ContractId, choice_name: str, arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → Awaitable[None][source]
+

Submit a single exercise choice. Equivalent to calling submit() with a single +exercise.

+
+
Parameters
+
    +
  • cid – The ContractId on which a choice is being exercised.

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • arguments – The arguments to the exercise (as a dict). Can be omitted (None) for no-argument +choices.

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
Returns
+

A future that resolves when the command has made it to the ledger _or_ an error +occurred when trying to process them.

+
+
+
+ +
+
+submit_exercise_by_key(template_name: Union[str, dazl.model.types.TypeReference, dazl.model.types.UnresolvedTypeReference, dazl.model.types.Template], contract_key: Any, choice_name: str, arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → Awaitable[None][source]
+

Synchronously submit a single exercise choice. Equivalent to calling submit() with a +single exercise_by_key.

+
+
Parameters
+
    +
  • template_name – The name of the template on which to do an exercise-by-key.

  • +
  • contract_key – The value that should uniquely identify a contract for the specified template.

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • arguments – The arguments to the create (as a dict). Can be omitted (None) for no-argument +choices.

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+ +
+
+class dazl.client.api.GlobalClient(impl: dazl.client._network_client_impl._NetworkImpl)[source]
+

Bases: object

+

Public interface for either an async-based or a thread-safe version of an API for interacting +with a Ledger API implementation that manages global ledger data, such as package store +management and current time.

+
+ +
+
+class dazl.client.api.Network(metrics: Optional[dazl.metrics.api.MetricEvents] = None)[source]
+

Bases: object

+

Manages network connection/scheduling logic on behalf of one or more PartyClient +instances.

+
+
+aio_global() → dazl.client.api.AIOGlobalClient[source]
+

Return a GlobalClient that works on an asyncio event loop.

+
+ +
+
+aio_party(party: Union[str, NewType.<locals>.new_type]) → dazl.client.api.AIOPartyClient[source]
+

Return a PartyClient that works on an asyncio event loop.

+
+
Parameters
+

party – The party to get a client for.

+
+
+
+ +
+
+async aio_run(*coroutines, run_state: Optional[dazl.client._run_level.RunState] = None) → None[source]
+

Coroutine where all network activity is scheduled from. This coroutine exits when +shutdown() is called, and can be used directly as an asyncio-native alternative to +start_in_background() and join().

+

You would normally call this method directly only if you are trying to incorporate +the client into an already-running event loop. Prefer run_until_complete() or +run_forever() if you can block the current thread, or start_in_background() +with join() if you wish to run the entire client on background threads.

+
+ +
+
+bots() → Collection[dazl.client.bots.Bot][source]
+
+ +
+
+join(timeout: Optional[float] = None) → None[source]
+

Block the current thread until the client is shut down.

+
+
Parameters
+

timeout – Number of seconds to wait before timing out the join, or None to wait indefinitely.

+
+
+
+ +
+
+parties() → Collection[NewType.<locals>.new_type][source]
+

Return a snapshot of the set of parties that exist right now.

+
+ +
+
+party_bots(party: Union[str, NewType.<locals>.new_type], if_missing: typing_extensions.Literal[typing_extensions.Literal[1], typing_extensions.Literal[2], typing_extensions.Literal[3]] = typing_extensions.Literal[1]) → dazl.client.bots.BotCollection[source]
+

Return the collection of bots associated with a party.

+
+
Parameters
+
    +
  • party – The party to get bots for.

  • +
  • if_missing – Specify the behavior to use in the case where no client has been yet requested for this +party. The default behavior is CREATE_IF_MISSING.

  • +
+
+
+
+ +
+
+resolved_config() → dazl.client.config.NetworkConfig[source]
+

Calculate the configuration that will be used for this client when it is instantiated.

+
+ +
+
+run_forever(*coroutines, install_signal_handlers: Optional[bool] = None) → None[source]
+

Block the main thread and run the application in an event loop on the main thread. The loop +terminates when shutdown() is called AND all active command submissions and event +handlers’ follow-ups have successfully returned.

+
+ +
+
+run_until_complete(*coroutines, install_signal_handlers: Optional[bool] = None) → None[source]
+

Block the main thread and run the application in an event loop on the main thread. The loop +terminates when the given (optional) coroutines terminate OR shutdown() is called AND +all active command submissions and event handlers’ follow-ups have successfully returned.

+
+
Parameters
+
    +
  • coroutines – Coroutines to run alongside event handlers and command submissions. When these +coroutines are done running and the

  • +
  • install_signal_handlersTrue to install SIGINT and SIGQUIT event handlers (CTRL+C and CTRL+); +False to skip installation. The default value is None, which installs signal +handlers only when called from the main thread (default). If signal handlers are +requested to be installed and the thread is NOT the main thread, this method throws.

  • +
+
+
+
+ +
+
+set_config(*config, url: Optional[str] = None, admin_url: Optional[str] = None, **kwargs)[source]
+
+ +
+
+shutdown() → None[source]
+

Gracefully shut down all network connections and notify all clients that they are about to +be terminated.

+

The current thread does NOT block.

+
+ +
+
+simple_global() → dazl.client.api.SimpleGlobalClient[source]
+

Return a GlobalClient that exposes thread-safe, synchronous (blocking) methods for +communicating with a ledger. Callbacks are dispatched to background threads.

+
+ +
+
+simple_party(party: Union[str, NewType.<locals>.new_type]) → dazl.client.api.SimplePartyClient[source]
+

Return a PartyClient that exposes thread-safe, synchronous (blocking) methods for +communicating with a ledger. Callbacks are dispatched to background threads.

+
+
Parameters
+

party – The party to get a client for.

+
+
+
+ +
+
+start_in_background(daemon: bool = True, install_signal_handlers: Optional[bool] = None) → None[source]
+

Connect to the ledger in a background thread.

+

The current thread does NOT block. Operations on instances of SimplePartyClient +are allowed, and operations on instances of AIOPartyClient are allowed as long as +they are made from the correct thread.

+
+ +
+ +
+
+class dazl.client.api.PartyClient(impl: dazl.client._party_client_impl._PartyClientImpl)[source]
+

Bases: object

+

Public interface for either an async-based or a thread-safe version of an API for interacting +with a Ledger API implementation from the perspective of a single client.

+
+
+property party
+

Return the party serviced by this client.

+
+ +
+
+resolved_config() → dazl.client.config.PartyConfig[source]
+

Calculate the configuration that will be used for this client when it is instantiated.

+
+ +
+ +
+
+class dazl.client.api.SimpleGlobalClient(impl: dazl.client._network_client_impl._NetworkImpl)[source]
+

Bases: dazl.client.api.GlobalClient

+
+
+ensure_dar(contents: Union[str, pathlib.Path, bytes, BinaryIO], timeout: Union[int, float, decimal.Decimal, str, datetime.timedelta] = 30) → None[source]
+

Validate that the ledger has the packages specified by the given contents (as a byte array). +Throw an exception if the specified DARs do not exist within the specified timeout.

+
+
Parameters
+
    +
  • contents – The DAR or DALF to ensure.

  • +
  • timeout – The maximum length of time to wait before giving up.

  • +
+
+
+
+ +
+
+ensure_packages(package_ids: Collection[str], timeout: Union[int, float, decimal.Decimal, str, datetime.timedelta] = 30) → None[source]
+

Validate that packages with the specified package IDs exist on the ledger. Throw an +exception if the specified packages do not exist within the specified timeout.

+
+
Parameters
+
    +
  • package_ids – The set of package IDs to check for.

  • +
  • timeout – The maximum length of time to wait before giving up.

  • +
+
+
+
+ +
+
+get_time() → datetime.datetime[source]
+
+ +
+
+metadata(timeout: Union[int, float, decimal.Decimal, str, datetime.timedelta] = 30) → dazl.model.ledger.LedgerMetadata[source]
+

Return the current set of known packages.

+
+ +
+
+set_time(new_datetime: datetime.datetime) → None[source]
+
+ +
+ +
+
+class dazl.client.api.SimplePartyClient(impl: dazl.client._party_client_impl._PartyClientImpl)[source]
+

Bases: dazl.client.api.PartyClient

+

Implementation of a PartyClient that exposes blocking calls, but can be used from any +thread.

+
+
Use this implementation if any of these apply:
    +
  • you wish to interact with libraries that do not natively support asyncio

  • +
  • you are comfortable with the trade-off of having to block threads in order to write code

  • +
+
+
+
+
+add_ledger_archived(template: Any, handler: Callable[dazl.model.reading.ContractArchiveEvent], match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → None[source]
+

Register a callback to be invoked when the PartyClient encounters a newly archived +contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • handler – The callback to invoke whenever a matching template is created.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+add_ledger_created(template: Any, handler: Callable[dazl.model.reading.ContractCreateEvent], match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → None[source]
+

Register a callback to be invoked when the PartyClient encounters a newly created +contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • handler – The callback to invoke whenever a matching template is created.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+add_ledger_exercised(template: Any, choice: str, handler: Callable[dazl.model.reading.ContractExercisedEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient encounters an exercised +choice event.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • choice – The name of the choice to listen for exercises on.

  • +
  • handler – The callback to invoke whenever a matching template is exercised.

  • +
+
+
+
+ +
+
+add_ledger_init(handler: Callable[dazl.model.reading.InitEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient has been instructed to +begin, but before any network activity is started.

+
+
Parameters
+

handler – The handler to register. May return anything that can be successfully coerced into a +CommandPayload.

+
+
+
+ +
+
+add_ledger_packages_added(handler: Callable[dazl.model.reading.PackagesAddedEvent], initial: bool = False) → None[source]
+

Register a callback to be invoked when the PartyClient has detected new packages +added to the ledger.

+
+
Parameters
+
    +
  • handler – The handler to register. May return anything that can be successfully coerced into a +CommandPayload.

  • +
  • initialTrue to call the handler when the client is ready. This can be useful if you want +to handle package additions identically whether they were already in the ledger when +the client started up or only after a package has been added. The default value is +False, which means that this handler is only called on NEW packages that have been +uploaded after this client has started.

  • +
+
+
Returns
+

+
+
+
+ +
+
+add_ledger_ready(handler: Callable[dazl.model.reading.ReadyEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient has caught up to the head of +the ledger, but before any ledger_create() or ledger_archive() callbacks are +invoked.

+
+
Parameters
+

handler – The handler to register. May return anything that can be successfully coerced into a +CommandPayload.

+
+
+
+ +
+
+add_ledger_transaction_end(handler: Callable[dazl.model.reading.TransactionEndEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient receives a new transaction. +Called after individual ledger_create() and ledger_archive() callbacks.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+add_ledger_transaction_start(handler: Callable[dazl.model.reading.TransactionStartEvent]) → None[source]
+

Register a callback to be invoked when the PartyClient receives a new transaction. +Called before individual ledger_create() and ledger_archive() callbacks.

+
+
Parameters
+

handler – The handler to register. This can either be a coroutine or a normal function, and may +return anything that can be successfully coerced into a CommandPayload.

+
+
+
+ +
+
+find(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None, include_archived: bool = False) → dazl.model.core.ContractContextualDataCollection[source]
+
+ +
+
+find_active(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Dict[dazl.model.core.ContractId, Dict[str, Any]][source]
+

Immediately return data from the current active contract set.

+

The contents of this ACS are guaranteed to be present (or removed) in the current +transaction _before_ processing any corresponding on_created or on_archived +callbacks for this party. The ACS is populated _before_ processing any on_ready +callbacks.

+

This method raises an error if ACS tracking has been disabled on this client.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
+
+
Returns
+

A dict whose keys are ContractId and values are corresponding contract +data that match the current query.

+
+
Returns
+

A dict whose keys are ContractId and values are corresponding contract +data that match the current query.

+
+
+
+ +
+
+find_by_id(cid: Union[str, dazl.model.core.ContractId]) → Optional[dazl.model.core.ContractContextualData][source]
+
+ +
+
+find_historical(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → dazl.model.core.ContractContextualDataCollection[source]
+

Immediately return data from the current active and historical contract set.

+

The contents of this set are guaranteed to be up-to-date in the current transaction _before_ +processing any corresponding on_created or on_archived callbacks for this party. The +set is up-to-date _before_ processing any on_ready callbacks.

+

This method raises an error if historical tracking has been disabled on this client.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
+
+
Returns
+

A dict whose keys are ContractId and values are corresponding contract +data that match the current query.

+
+
Returns
+

A dict whose keys are ContractId and values are corresponding contract +data that match the current query.

+
+
+
+ +
+
+find_nonempty(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]], min_count: int = 1, timeout: float = 30) → Dict[dazl.model.core.ContractId, Dict[str, Any]][source]
+

Return data from the current active contract set when at least some amount of rows exist in +the active contract set.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
  • min_count – The minimum number of rows to return. The default value is 1.

  • +
  • timeout – Number of seconds in which to time out the search.

  • +
+
+
Returns
+

A Future that is resolved with a dict whose keys are ContractId and +values are corresponding contract data that match the current query.

+
+
+
+ +
+
+find_one(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None, timeout: float = 30) → Tuple[dazl.model.core.ContractId, Dict[str, Any]][source]
+

Return data from the current active contract set when at least some amount of rows exist in +the active contract set.

+
+
Parameters
+
    +
  • template – The name of the template to fetch data from.

  • +
  • match – An optional dictionary whose keys are matched against corresponding field values.

  • +
  • timeout – Number of seconds in which to time out the search.

  • +
+
+
Returns
+

A Future that is resolved with a dict whose keys are ContractId and +values are corresponding contract data that match the current query.

+
+
+
+ +
+
+get_time() → datetime.datetime[source]
+
+ +
+
+ledger_archived(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Callable[dazl.model.reading.ContractArchiveEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient encounters +a newly archived contract instance of a template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+ledger_created(template: Any, match: Union[None, Callable[Dict[str, Any], bool], Dict[str, Any]] = None) → Callable[dazl.model.reading.ContractCreateEvent][source]
+

Register a callback to be invoked when the PartyClient encounters a newly created +template.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • match – An (optional) parameter that filters the templates to be received by the callback.

  • +
+
+
+
+ +
+
+ledger_exercised(template: Any, choice: str) → Callable[dazl.model.reading.ContractExercisedEvent][source]
+

Register a callback to be invoked when the PartyClient encounters an exercised +choice event.

+
+
Parameters
+
    +
  • template – A template name to subscribe to, or ‘*’ to subscribe on all templates.

  • +
  • choice – The name of the choice to listen for exercises on.

  • +
+
+
+
+ +
+
+ledger_init() → Callable[dazl.model.reading.InitEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has been +instructed to begin, but before any network activity is started.

+
+ +
+
+ledger_packages_added(initial: bool = False) → Callable[dazl.model.reading.PackagesAddedEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has +detected new packages added to the ledger.

+
+
Parameters
+

initialTrue to call the handler when the client is ready. This can be useful if you want +to handle package additions identically whether they were already in the ledger when +the client started up or only after a package has been added. The default value is +False, which means that this handler is only called on NEW packages that have been +uploaded after this client has started.

+
+
Returns
+

+
+
+
+ +
+
+ledger_ready() → Callable[dazl.model.reading.ReadyEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient has caught +up to the head of the ledger, but before any ledger_create() or ledger_archive() +callbacks are invoked.

+
+ +
+
+ledger_transaction_end() → Callable[dazl.model.reading.TransactionEndEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient receives a +new transaction. Called after individual ledger_create() and ledger_archive() +callbacks.

+
+ +
+
+ledger_transaction_start() → Callable[dazl.model.reading.TransactionStartEvent][source]
+

Decorator for registering a callback to be invoked when the PartyClient receives a +new transaction. Called before individual ledger_create() and ledger_archive() +callbacks.

+
+ +
+
+ready() → None[source]
+

Block until the underlying infrastructure has connected to all necessary services.

+
+ +
+
+set_config(url: Optional[str], **kwargs)[source]
+
+ +
+
+set_time(new_datetime: datetime.datetime) → None[source]
+
+ +
+
+submit(commands, workflow_id: str = None) → None[source]
+
+ +
+
+submit_create(template_name: Union[str, dazl.model.types.TypeReference, dazl.model.types.UnresolvedTypeReference, dazl.model.types.Template], arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → None[source]
+

Synchronously submit a single create command. Equivalent to calling submit() with a +single create.

+
+
Parameters
+
    +
  • template_name – The name of the template.

  • +
  • arguments – The arguments to the create (as a dict).

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+
+submit_create_and_exercise(template_name: Union[str, dazl.model.types.TypeReference, dazl.model.types.UnresolvedTypeReference, dazl.model.types.Template], arguments: dict, choice_name: str, choice_arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → None[source]
+

Synchronously submit a single create-and-exercise command. Equivalent to calling +submit() with a single create_and_exercise.

+
+
Parameters
+
    +
  • template_name – The name of the template on which to do an exercise-by-key.

  • +
  • arguments – The arguments to the create (as a dict).

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • choice_arguments – The arguments to the exercise (as a dict). Can be omitted (None) for no-argument

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+
+submit_exercise(cid: dazl.model.core.ContractId, choice_name: str, arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → None[source]
+

Synchronously submit a single exercise choice. Equivalent to calling submit() with a +single exercise.

+
+
Parameters
+
    +
  • cid – The ContractId on which a choice is being exercised.

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • arguments – The arguments to the exercise (as a dict). Can be omitted (None) for no-argument +choices.

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+
+submit_exercise_by_key(template_name: Union[str, dazl.model.types.TypeReference, dazl.model.types.UnresolvedTypeReference, dazl.model.types.Template], contract_key: Any, choice_name: str, arguments: Optional[dict] = None, workflow_id: Optional[str] = None) → None[source]
+

Synchronously submit a single exercise choice. Equivalent to calling submit() with a +single exercise_by_key.

+
+
Parameters
+
    +
  • template_name – The name of the template on which to do an exercise-by-key.

  • +
  • contract_key – The value that should uniquely identify a contract for the specified template.

  • +
  • choice_name – The name of the choice to exercise.

  • +
  • arguments – The arguments to the create (as a dict). Can be omitted (None) for no-argument +choices.

  • +
  • workflow_id – The optional workflow ID to stamp on the outgoing command.

  • +
+
+
+
+ +
+ +
+
+dazl.client.api.simple_client(url: Optional[str] = None, party: Union[None, str, Party] = None, log_level: Optional[int] = 20) → ContextManager[SimplePartyClient][source]
+

Start up a single client connecting to a single specific party.

+
+
Parameters
+
    +
  • url – The URL of the client to connect to. Defaults to the value of the DAML_LEDGER_URL +environment variable (if set).

  • +
  • party – The party to connect as. Defaults to the value of the DAML_LEDGER_PARTY environment +variable if it is set.

  • +
  • log_level – If non-None, configure a default logger that logs output at the specified level. The +default value is INFO.

  • +
+
+
Returns
+

A SimplePartyClient that can be used in a completely blocking, synchronous +fashion.

+
+
+
+ +
+
+

dazl.client.bots module

+
+
+class dazl.client.bots.Bot(party_client: Optional[PartyClient], name: str)[source]
+

Bases: object

+
+
+add_event_handler(keys: Union[str, Collection[str]], handler: Callable[E, Any], filter_fn: Optional[Callable[E, bool]] = None) → None[source]
+

Add a new event handler to this bot for the specified event.

+
+
Parameters
+
    +
  • keys – The key(s) of the event (as returned by EventKey.from_event()).

  • +
  • filter_fn – An optional callback that returns True or False on whether the corresponding +callback should be invoked. This cannot be a coroutine function.

  • +
  • handler – An event handler to be invoked when an event with the specified key is raised.

  • +
+
+
+
+ +
+
+entries() → Sequence[dazl.client.bots.BotEntry][source]
+

The collection of individual event handlers in a bot, in the order that they will be +executed.

+
+ +
+
+event_keys() → AbstractSet[str][source]
+

Return the set of keys that event handlers in this bot are configured to handle.

+
+ +
+
+property id
+

The ID of this bot, generated at runtime.

+
+ +
+
+ledger_created(template: Any)[source]
+
+ +
+
+property name
+

The name of this bot. Defaults to the name of the original event handler if unspecified.

+
+ +
+
+notify(event: dazl.model.reading.BaseEvent) → Awaitable[None][source]
+

Notifies handler(s) associated with this bot that the given event has occurred. Note that +this notification is asynchronous: in other words, event handlers will not have processed +this event by the time this function returns.

+
+
Parameters
+

event – The event to raise.

+
+
+
+ +
+
+property party
+

Primary party that this bot receives events for (and potentially generates commands for).

+
+ +
+
+pause() → None[source]
+

Immediately change the state of this bot to PAUSING, and pause event handler +invocations. The event handler currently running is allowed to complete. When that is +completed, the state is changed to PAUSED.

+
+ +
+
+resume() → None[source]
+

Immediately change the state of this bot to RESUMING and process any events that have +queued up while the bot was paused. When this queue is fully drained, the state is changed +to RUNNING.

+
+ +
+
+property running
+

Return True if this bot is currently processing events.

+
+ +
+
+property state
+

Current running state of the bot.

+
+ +
+
+stop()[source]
+

Permanently stop this bot. If you need to be able to “restart” a stopped bot, use +pause() and resume() instead.

+
+ +
+
+wants_any_keys(keys: Collection[str]) → bool[source]
+
+ +
+ +
+
+class dazl.client.bots.BotCollection(party: Optional[NewType.<locals>.new_type])[source]
+

Bases: typing.Sequence

+

A collection of bots for a party.

+

This class is thread-safe except for notify() and _main() in order to support adding +event handlers from any thread. The most common use of this is for SimplePartyClient +instances, where event registration is done from the main thread (from the perspective of the +caller) and event notifications are done on an asyncio event loop thread (hidden from the +caller).

+
+
+add_new(name: str, party_client: Optional[PartyClient] = None) → Bot[source]
+
+ +
+
+add_single(keys: Union[str, Sequence[str]], handler: BotCallback, filter_fn: Optional[BotFilter] = None, name: Optional[str] = None, party_client: Optional[PartyClient] = None) → Bot[source]
+

Convenience method for creating a bot with a single event handler.

+
+ +
+
+notify(event: dazl.model.reading.BaseEvent)[source]
+
+ +
+
+stop_all()[source]
+
+ +
+ +
+
+class dazl.client.bots.BotEntry(event_key:str, callback:Callable[[~E], Any], filter:Union[Callable[[~E], bool], NoneType]=None, source_location:Union[dazl.model.core.SourceLocation, NoneType]=None)[source]
+

Bases: object

+
+
+filter = None
+
+ +
+
+source_location = None
+
+ +
+ +
+
+class dazl.client.bots.BotInvocation(event:dazl.model.reading.BaseEvent, future:_asyncio.Future=<factory>)[source]
+

Bases: object

+
+ +
+
+class dazl.client.bots.BotState[source]
+

Bases: enum.Enum

+

Possible states of a Bot.

+
+
+PAUSED = 'PAUSED'
+
+ +
+
+PAUSING = 'PAUSING'
+

This bot has been told to pause, but has not yet completed processing events in flight.

+
+ +
+
+RESUMING = 'RESUMING'
+
+ +
+
+RUNNING = 'RUNNING'
+
+ +
+
+STARTING = 'STARTING'
+

The bot is starting (has not yet received the “ready” event).

+
+ +
+
+STOPPED = 'STOPPED'
+
+ +
+
+STOPPING = 'STOPPING'
+
+ +
+ +
+
+dazl.client.bots.wrap_as_command_submission(submit_fn, callback, filter) → Callable[dazl.model.reading.BaseEvent, Awaitable[Any]][source]
+

Normalize a callback to something that takes a single contract ID and contract data, and +return an awaitable that is resolved when the underlying command has been fully submitted.

+
+ +
+
+

Module contents

+
+

dazl.client package

+

The dazl.client module a high-level view of the Ledger API in a friendly way.

+

It provides:

+
+
    +
  • a callback-based API for interacting with events on the read-side of the Ledger API

  • +
  • convenient methods for creating arbitrary commands on the write-side of the Ledger API.

  • +
+
+

For a higher-level, more declarative API, see dazl.query.

+
+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.damlast.html b/docs/dazl.damlast.html new file mode 100644 index 00000000..e4dafdf0 --- /dev/null +++ b/docs/dazl.damlast.html @@ -0,0 +1,119 @@ + + + + + + + + dazl.damast package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.damast package

+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.damlsdk.html b/docs/dazl.damlsdk.html new file mode 100644 index 00000000..019b12a7 --- /dev/null +++ b/docs/dazl.damlsdk.html @@ -0,0 +1,120 @@ + + + + + + + + dazl.damlsdk package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.damlsdk package

+

Module that exposes general utility functions around the DAML SDK Assistant.

+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.html b/docs/dazl.html new file mode 100644 index 00000000..864f9912 --- /dev/null +++ b/docs/dazl.html @@ -0,0 +1,162 @@ + + + + + + + + dazl package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ + + + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.model.html b/docs/dazl.model.html new file mode 100644 index 00000000..9f6d2f4b --- /dev/null +++ b/docs/dazl.model.html @@ -0,0 +1,379 @@ + + + + + + + + dazl.model package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.model package

+

The dazl.model module is the low-level domain model for the Ledger. Most of the time, these +classes will not be instantiated directly, but will frequently be passed to your code to work with.

+

The most important classes:

+
+
dazl.model.core:

ContractId

+
+
dazl.model.writing:

Subclasses of Command for the Write API: +CreateCommand and +ExerciseCommand

+
+
dazl.model.types:

Type description classes: +Subclasses of Type: +ScalarType, +ListType, +RecordType, +VariantType

+
+
+
+

Core types

+

The dazl.model.core module contains classes used on both the read-side and the write-side of +the Ledger API.

+
+
+class dazl.model.core.ContractId(contract_id: str, template_id: Union[None, str, Type] = None)[source]
+

There are two kinds of contract IDs: those that know the template type of the underlying +contract instance and those that don’t. Contract IDs that arise from event processing are always +tagged with their type when they are read off the event stream. Contract IDs that are +parameters to a template are not currently tagged with a template type.

+

Instance attributes:

+
+
+contract_id
+

A str reference to a contract.

+
+ +
+
+template_id
+

An optional str template ID.

+
+ +

Instance members:

+
+
+exercise(choice_name, arguments=None)[source]
+

Create an ExerciseCommand that represents the result of exercising a choice on this +contract with the specified choice.

+
+
Parameters
+
    +
  • choice_name – The name of the choice to exercise.

  • +
  • arguments – (optional) A dict of named values to send as parameters to the choice exercise.

  • +
+
+
+
+ +
+
+for_json()[source]
+

Return the JSON representation of this contract. This is currently just the contract ID +string itself.

+
+ +
+
+replace(contract_id=None, template_id=None)[source]
+

Return a new ContractId instance replacing specified fields with values.

+
+ +
+ +
+

Types that describe the behavior of the ledger itself.

+

This module contains models used on the read-side of the Ledger API.

+
+

Type system types

+

The dazl.model.types module contains the Python classes used to represent the DAML type +system.

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

DAML type

Python type

Bool

bool

Int

int

Decimal

decimal.Decimal

[a]

list

+
+
+class dazl.model.types.Type[source]
+

A DAML-defined type.

+
+ +
+
+class dazl.model.types.ScalarType(name: str)[source]
+

A DAML-defined type that represents a simple scalar value. You should not need to ever +construct instances of this directly; all scalar types are builtins.

+
+ +
+
+class dazl.model.types.ListType(type_parameter: dazl.model.types.Type)[source]
+
+ +
+
+class dazl.model.types.RecordType(named_args: dazl.model.types.NamedArgumentList, name: Optional[dazl.model.types.TypeReference], type_args: Sequence[dazl.model.types.TypeVariable], adjective: dazl.model.types.TypeAdjective)[source]
+
+ +
+
+class dazl.model.types.VariantType(named_args: dazl.model.types.NamedArgumentList, name: Optional[dazl.model.types.TypeReference], type_args: Sequence[dazl.model.types.TypeVariable], adjective: dazl.model.types.TypeAdjective)[source]
+
+ +
+
+class dazl.model.types.UnsupportedType(name)[source]
+

A DAML type that is currently unparseable by the Python client library.

+
+ +
+
+

Write-Side types

+

The dazl.model.writing module contains the Python classes used on the write-side of the +Ledger API.

+
+
+class dazl.model.writing.Command[source]
+

Base class for write-side commands.

+
+ +
+
+class dazl.model.writing.CreateCommand(template: Union[str, dazl.model.types.Type], arguments=None)[source]
+

A command that creates a contract without any predecessors.

+
+
+template
+

Refers to the type of a template. This can be passed in as a str to the constructor, +where it assumed to represent the ID or name of a template.

+
+ +
+
+arguments
+

The arguments to the create (as a dict).

+
+ +
+
+replace(template: Union[None, str, dazl.model.types.Type] = None, arguments=None)[source]
+

Create a new CreateCommand with the same identifier as this command, but with new +values for its parameters.

+
+
Parameters
+
    +
  • template – The new value of the template field, or None to reuse the existing value.

  • +
  • arguments – The new value of the arguments field, or None to reuse the existing value.

  • +
+
+
+
+ +
+ +
+
+class dazl.model.writing.ExerciseCommand(contract: Union[str, dazl.model.core.ContractId], choice: str, arguments=None, template_id=None)[source]
+

A command that exercises a choice on a pre-existing contract.

+
+
+contract
+

The ContractId on which a choice is being exercised.

+
+ +
+
+choice
+

Refers to a choice (either a ChoiceRef or a ChoiceMetadata). +This can be passed in as a str to the constructor, where it assumed to represent the +name of a choice.

+
+ +
+
+arguments
+

The arguments to the exercise choice (as a dict).

+
+ +

Note that when an ExerciseCommand is created, an additional template_id parameter can +be supplied to the constructor to aid in disambiguation of the specific choice being invoked. +In some situations involving composite commands, a template_id must eventually be supplied +before a choice can be exercised. If this template_id is specified, the contract and +choice are both tagged with this ID.

+

Instance methods:

+
+
+replace(contract=None, choice=None, arguments=None, template_id=None)[source]
+

Create a new ExerciseCommand with the same identifier as this command, but with new +values for its parameters.

+
+
Parameters
+
    +
  • contract – The new value of the contract field, or None to reuse the existing value. +The same type coercion rules used in the constructor apply here.

  • +
  • choice – The new value of the choice field, or None to reuse the existing value. +The same type coercion rules used in the constructor apply here.

  • +
  • arguments – The new value of the choice field, or None to reuse the existing value.

  • +
  • template_id – The expected template type.

  • +
+
+
+
+ +
+
+replace(contract=None, choice=None, arguments=None, template_id=None)[source]
+

Create a new ExerciseCommand with the same identifier as this command, but with new +values for its parameters.

+
+
Parameters
+
    +
  • contract – The new value of the contract field, or None to reuse the existing value. +The same type coercion rules used in the constructor apply here.

  • +
  • choice – The new value of the choice field, or None to reuse the existing value. +The same type coercion rules used in the constructor apply here.

  • +
  • arguments – The new value of the choice field, or None to reuse the existing value.

  • +
  • template_id – The expected template type.

  • +
+
+
+
+ +
+ +
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.pretty.html b/docs/dazl.pretty.html new file mode 100644 index 00000000..997d8d85 --- /dev/null +++ b/docs/dazl.pretty.html @@ -0,0 +1,125 @@ + + + + + + + + dazl.pretty package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.pretty package

+

This module contains utilities for pretty-printing various types in dazl.

+
+
+dazl.pretty.get_pretty_printer(format: str, options: dazl.pretty.options.PrettyOptions, store: dazl.model.types_store.PackageStore) → Optional[dazl.pretty._render_base.PrettyPrintBase][source]
+
+ +
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.protocols.html b/docs/dazl.protocols.html new file mode 100644 index 00000000..d21daf48 --- /dev/null +++ b/docs/dazl.protocols.html @@ -0,0 +1,139 @@ + + + + + + + + dazl.protocols package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.protocols package

+
+

Submodules

+
+
+

dazl.protocols.v0 module

+
+
+

dazl.protocols.v1 module

+
+
+

Module contents

+

This module contains implementations for the different protocols and serialization formats +supported by this client library.

+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/dazl.util.html b/docs/dazl.util.html new file mode 100644 index 00000000..2ab2fca8 --- /dev/null +++ b/docs/dazl.util.html @@ -0,0 +1,120 @@ + + + + + + + + dazl.util package + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl.util package

+

Module that exposes general utility functions.

+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/genindex.html b/docs/genindex.html new file mode 100644 index 00000000..8b3b87b5 --- /dev/null +++ b/docs/genindex.html @@ -0,0 +1,715 @@ + + + + + + + + + Index + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ + +

Index

+ +
+ A + | B + | C + | D + | E + | F + | G + | I + | J + | L + | M + | N + | P + | R + | S + | T + | U + | V + | W + +
+

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

I

+ + +
+ +

J

+ + +
+ +

L

+ + + +
+ +

M

+ + + +
+ +

N

+ + + +
+ +

P

+ + + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + +
+ +

V

+ + +
+ +

W

+ + + +
+ + + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/glossary.html b/docs/glossary.html new file mode 100644 index 00000000..00f4c54e --- /dev/null +++ b/docs/glossary.html @@ -0,0 +1,107 @@ + + + + + + + + Glossary + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

Glossary

+
+
dazl

The Python client library for Digital Asset ledgers.

+
+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 00000000..9359d0aa --- /dev/null +++ b/docs/index.html @@ -0,0 +1,232 @@ + + + + + + + + dazl: DA client library for Python + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

dazl: DA client library for Python

+

Version: |release|

+
+

Dependencies

+

You will need Python 3.6 or later and a Digital Asset ledger implementation (DA Sandbox or +DA Ledger Server). dazl additionally requires the following libraries to be +installed:

+
    +
  • grpcio, version 1.18.0 or later

  • +
  • PyYAML

  • +
  • semver

  • +
+
+
+

Getting Started

+

This section assumes that you already have a running ledger with a DAML model loaded.

+

Connect to the ledger and submit a single command:

+
with dazl.simple_client('http://localhost:7600', 'Alice') as client:
+    client.submit_create('Alice', 'My.Template', { someField: 'someText' })
+
+
+

Connect to the ledger as a single party, print all contracts, and close:

+
with dazl.simple_client('http://localhost:7600', 'Alice') as client:
+    # wait for the ACS to be fully read
+    client.ready()
+    contract_dict = client.find_active('*')
+print(contract_dict)
+
+
+

Connect to the ledger as multiple parties:

+
network = dazl.Network()
+network.set_config(url='http://localhost:7600')
+
+alice = network.simple_party('Alice')
+bob = network.simple_party('Bob')
+
+@alice.ledger_ready()
+def set_up(event):
+    currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"})
+    return dazl.create('SomethingOf.Value', {
+        'amount': 100,
+        'currency': currency_cid,
+        'from': 'Accept',
+        'to': 'Bob' })
+
+@bob.ledger_created('SomethingOf.Value')
+def on_something_of_value(event):
+    return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' })
+
+network.start()
+
+
+
+ +
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/migrating.html b/docs/migrating.html new file mode 100644 index 00000000..a7a7d5c4 --- /dev/null +++ b/docs/migrating.html @@ -0,0 +1,189 @@ + + + + + + + + Migrate + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

Migrate

+

Migrating from dazl v5 from v4

+
+

Library Initialization

+

Old API:

+
# original dazl API
+with create_client(participant_url='http://localhost:7600', parties=['Alice', 'Bob']) as manager:
+    alice_client = manager.client('Alice')
+    bob_client = manager.client('Bob')
+    # register some event handlers for Alice and Bob
+    manager.run_forever()
+
+
+

New API:

+
# asyncio-based API
+network = Network()
+network.set_config(url='http://localhost:7600')
+
+alice_client = network.aio_party('Alice')
+bob_client = network.aio_party('Bob')
+
+# run
+alice_client.run_forever()
+
+
+
+
+

Initialization Event Listeners

+

Arguments to event listeners have changed in order to provide more information about events and +for consistency across event handlers.

+

Initialization has been collapsed into a single event, where formerly, there were two events +(on_init and on_init_metadata):

+

Old API:

+
# original dazl API
+client = manager.client('Some Party')
+client.on_init(lambda: print('Ledger initialization is happening')
+client.on_init_metadata(lambda store: print(f'Ledger package store: {store}'))
+
+
+

New API:

+
# asyncio-based API
+client.add_ledger_init(lambda event: print(f'Ledger initialization with package store: {event.store}'))
+
+
+
+
+

Ready Event Listeners

+

Old API:

+
# original dazl API
+client = manager.client('Some Party')
+client.on_ready(lambda party_name, client\_: print(f'Party {party_name} is ready'))
+
+
+

New API:

+
# asyncio-based API
+client = network.aio_party('Some Party')
+client.add_ledger_ready(lambda event: print(f'Party {event.party} is ready'))
+
+
+
+
+

Create/Archive Event Listeners

+

Create and archive events now take a single parameter, called event by convention, that contain +the contract ID, contract data, and additional metadata about the event, such as the time of +execution, ledger ID, and access to the active contract set.

+

Old API:

+
# original dazl API
+client = manager.client('Some Party')
+client.on_created('Some.Asset', lambda cid, cdata: print(cid, cdata))
+client.on_archived('Some.Asset', lambda cid: print(cid))
+
+
+

New API:

+
# asyncio-based API
+client = network.aio_party('Some Party')
+client.add_ledger_created('Some.Asset', lambda event: print(event.cid, event.cdata))
+client.add_ledger_archived('Some.Asset', lambda event: print(event.cid))
+
+
+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/objects.inv b/docs/objects.inv new file mode 100644 index 0000000000000000000000000000000000000000..446d3f164fcf63e4fc22b5a1a0ed3c667409c38d GIT binary patch literal 1820 zcmV+%2jlo7AX9K?X>NERX>N99Zgg*Qc_4OWa&u{KZXhxWBOp+6Z)#;@bUGkpVR~!| zBOq2~a&u{KZaN@!ZfkCDcWw$JAXI2&AaZ4GVQFq;WpW^IW*~HEX>%ZEX>4U6X>%ZB zZ*6dLWpi_7WFU2OX>MmAdTeQ8E(&ZB5@BS;8>0V))Yj0_q>11Y`dg^5N z$jBgLH9}$}5!d_I?~?==W7#p1d;_8Hho@hUrw5eiKbkcAFEuY)ij&Vt2?g0!)%24s zO8-jIg()m3IjsqWXKQCv&K6{U6RGYgec*MCSgG{|MN%er6ZvIbhX3HARoL7gt1U0* z0vM`|8Yv~nTBBwH8YCnZ*BVeG!gSqD%L+v}yIi{wgsHr!%Y2JzbG=Tq*WUy)8fu8IF1vsF`JM7Lq7TFUr=ve$uFz+g$yVUJMDB6$VKu0DLlu_czzVBeks61S zK#fYIP&i43*tA4K?fpk?B+pP;<`kC|7C92dmb~LK)TA-95E!YrNN_l!ATlnLFrs4e z`pKI^SzJq@L(6?kpc05lWZYDaS$Qk8R8S`vz9A7T)R0`8^^W7P*87}9GHVOZHZDkk zXdE8n4A+g?$Dsi%7*s{_d|7O_71?D)cULi8)ot8VR2Ow4_jEJY6sOfXE+{zLkSYo) z%0iRvx{fgCET&suacMd11BR6r3wFs6)P|NZS7x*2EFi6W3pZ*b85g;J z+l`CJ&|SwxxMvuCkr})Pxti{|6*=YmB}&{J?_9|loM*b^3@s#Mat7(2G&uwG%A1_B zs(79G^vg z<=5lt^+yEE>+^FsW%Y9Z>m>%}=W-d`zlP#%%uXO!Y*HuD^*3?3iG!rh9Zo>o0}-p;?5CWPRAn(~S*Ck2iL z>zrdG+^kV-1XkTv@@OU4a`#f`uIc=;JqlYnQN)VWpum{%`R z;stm80WnQt?xP?x$7LX+cobu72x=u~`IT*)|S9Sgg)HdT)1YjU(EkG1{8J(Z7VPcoh6 zV~CkaQ~fZJlF@AIR260fmgpZNqG$~*((|P&wW=q5xajB57=JXclJDKwg48-(kS0M4 zu1_kRVmZEpYV}JxL}lJ^sdB#AfVZ{Nvs0&_P7msIaj>(y`^ZGyurJBC`=pyol&poe z6(Ztfxd#`?7B#5^GC{!zF%(+N4|9qaFtmS!0(;@1;JVdGt**;#DfF2w{Rr#mIVbqja6Rp=rvvB0Jx8P9ZpCz%k|h)*KTW{} z&NTymuvlM8JGGmyKi=9 + + + + + + + Python Module Index + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ + +

Python Module Index

+ +
+ d +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
+ d
+ dazl +
    + dazl.cli +
    + dazl.cli.ls +
    + dazl.client +
    + dazl.client.api +
    + dazl.client.bots +
    + dazl.damlast +
    + dazl.damlsdk +
    + dazl.model +
    + dazl.model.core +
    + dazl.model.ledger +
    + dazl.model.reading +
    + dazl.model.types +
    + dazl.model.types_store +
    + dazl.model.writing +
    + dazl.pretty +
    + dazl.pretty.render_daml +
    + dazl.pretty.util +
    + dazl.protocols +
    + dazl.protocols.v0 +
    + dazl.protocols.v1 +
    + dazl.util +
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/search.html b/docs/search.html new file mode 100644 index 00000000..cb6a9ad8 --- /dev/null +++ b/docs/search.html @@ -0,0 +1,124 @@ + + + + + + + + Search + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Search

+
+ +

+ Please activate JavaScript to enable the search + functionality. +

+
+

+ From here you can search these documents. Enter your search + words into the box below and click "search". Note that the search + function will automatically search for all of the words. Pages + containing fewer words won't appear in the result list. +

+
+ + + +
+ +
+ +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/searchindex.js b/docs/searchindex.js new file mode 100644 index 00000000..f620a033 --- /dev/null +++ b/docs/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["basics","dazl","dazl.cli","dazl.client","dazl.damlast","dazl.damlsdk","dazl.model","dazl.pretty","dazl.protocols","dazl.util","glossary","index","migrating","tutorials","tutorials_message_ingester","tutorials_post_office","tutorials_workflow_state"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["basics.rst","dazl.rst","dazl.cli.rst","dazl.client.rst","dazl.damlast.rst","dazl.damlsdk.rst","dazl.model.rst","dazl.pretty.rst","dazl.protocols.rst","dazl.util.rst","glossary.rst","index.rst","migrating.rst","tutorials.rst","tutorials_message_ingester.rst","tutorials_post_office.rst","tutorials_workflow_state.rst"],objects:{"":{dazl:[1,0,0,"-"]},"dazl.cli":{ls:[2,0,0,"-"],main:[2,4,1,""],print_cmd_help:[2,4,1,""],run:[2,4,1,""]},"dazl.cli.ls":{ListAllCommand:[2,1,1,""]},"dazl.cli.ls.ListAllCommand":{execute:[2,2,1,""],name:[2,3,1,""],parser:[2,2,1,""]},"dazl.client":{api:[3,0,0,"-"],bots:[3,0,0,"-"]},"dazl.client.api":{AIOGlobalClient:[3,1,1,""],AIOPartyClient:[3,1,1,""],GlobalClient:[3,1,1,""],Network:[3,1,1,""],PartyClient:[3,1,1,""],SimpleGlobalClient:[3,1,1,""],SimplePartyClient:[3,1,1,""],simple_client:[3,4,1,""]},"dazl.client.api.AIOGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.AIOPartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.api.Network":{aio_global:[3,2,1,""],aio_party:[3,2,1,""],aio_run:[3,2,1,""],bots:[3,2,1,""],join:[3,2,1,""],parties:[3,2,1,""],party_bots:[3,2,1,""],resolved_config:[3,2,1,""],run_forever:[3,2,1,""],run_until_complete:[3,2,1,""],set_config:[3,2,1,""],shutdown:[3,2,1,""],simple_global:[3,2,1,""],simple_party:[3,2,1,""],start_in_background:[3,2,1,""]},"dazl.client.api.PartyClient":{party:[3,2,1,""],resolved_config:[3,2,1,""]},"dazl.client.api.SimpleGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.SimplePartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.bots":{Bot:[3,1,1,""],BotCollection:[3,1,1,""],BotEntry:[3,1,1,""],BotInvocation:[3,1,1,""],BotState:[3,1,1,""],wrap_as_command_submission:[3,4,1,""]},"dazl.client.bots.Bot":{add_event_handler:[3,2,1,""],entries:[3,2,1,""],event_keys:[3,2,1,""],id:[3,2,1,""],ledger_created:[3,2,1,""],name:[3,2,1,""],notify:[3,2,1,""],party:[3,2,1,""],pause:[3,2,1,""],resume:[3,2,1,""],running:[3,2,1,""],state:[3,2,1,""],stop:[3,2,1,""],wants_any_keys:[3,2,1,""]},"dazl.client.bots.BotCollection":{add_new:[3,2,1,""],add_single:[3,2,1,""],notify:[3,2,1,""],stop_all:[3,2,1,""]},"dazl.client.bots.BotEntry":{filter:[3,3,1,""],source_location:[3,3,1,""]},"dazl.client.bots.BotState":{PAUSED:[3,3,1,""],PAUSING:[3,3,1,""],RESUMING:[3,3,1,""],RUNNING:[3,3,1,""],STARTING:[3,3,1,""],STOPPED:[3,3,1,""],STOPPING:[3,3,1,""]},"dazl.model":{core:[6,0,0,"-"],ledger:[6,0,0,"-"],reading:[6,0,0,"-"],types:[6,0,0,"-"],types_store:[6,0,0,"-"],writing:[6,0,0,"-"]},"dazl.model.core":{ContractId:[6,1,1,""]},"dazl.model.core.ContractId":{contract_id:[6,3,1,""],exercise:[6,2,1,""],for_json:[6,2,1,""],replace:[6,2,1,""],template_id:[6,3,1,""]},"dazl.model.types":{ListType:[6,1,1,""],RecordType:[6,1,1,""],ScalarType:[6,1,1,""],Type:[6,1,1,""],UnsupportedType:[6,1,1,""],VariantType:[6,1,1,""]},"dazl.model.writing":{Command:[6,1,1,""],CreateCommand:[6,1,1,""],ExerciseCommand:[6,1,1,""]},"dazl.model.writing.CreateCommand":{arguments:[6,3,1,""],replace:[6,2,1,""],template:[6,3,1,""]},"dazl.model.writing.ExerciseCommand":{arguments:[6,3,1,""],choice:[6,3,1,""],contract:[6,3,1,""],replace:[6,2,1,""]},"dazl.pretty":{get_pretty_printer:[7,4,1,""],render_daml:[7,0,0,"-"],util:[7,0,0,"-"]},"dazl.protocols":{v0:[8,0,0,"-"],v1:[8,0,0,"-"]},dazl:{cli:[2,0,0,"-"],client:[3,0,0,"-"],damlast:[4,0,0,"-"],damlsdk:[5,0,0,"-"],model:[6,0,0,"-"],pretty:[7,0,0,"-"],protocols:[8,0,0,"-"],util:[9,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"],"3":["py","attribute","Python attribute"],"4":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method","3":"py:attribute","4":"py:function"},terms:{"00z":14,"01t00":14,"byte":3,"case":[3,14,15,16],"class":[2,3,6,15,16],"default":3,"enum":3,"final":[14,15,16],"float":3,"function":[3,5,9,14,15],"import":[6,14,15,16],"int":[0,2,3,6,15],"long":3,"new":[3,6,12,14,15,16],"public":3,"return":[3,6,11,14,15,16],"throw":3,"true":3,"try":[3,14,15,16],"while":3,ACS:[3,11],AND:3,But:15,For:[3,14,15],IDs:[3,6],NOT:3,That:14,The:[0,3,6,10,14,15,16],Then:15,There:[6,15],These:16,Use:3,Using:15,__file__:15,__init__:16,__main__:[14,15,16],__name__:[14,15,16],_asyncio:3,_base:2,_before_:3,_main:3,_network_client_impl:3,_networkimpl:3,_or_:3,_party_client_impl:3,_partyclientimpl:3,_render_bas:7,_resolve_nam:16,_run_level:3,abil:15,abl:3,about:[3,12],abov:[14,15,16],abstractset:3,accept:[11,15,16],accept_message_act:14,accept_the_messag:14,accept_ticket_buyer_invit:16,accept_ticket_seller_invit:16,acceptinviteauthorrol:15,acceptinvitereceiverrol:15,acceptlett:15,acceptmessag:14,acceptsentlett:15,acceptticketbuyerinvit:16,acceptticketsellerinvit:16,access:12,acknowledg:14,acknowledge_message_act:14,acknowledge_the_messag:14,acknowledgingparti:14,acknowlegedlett:15,across:12,acs_find_on:11,action:16,activ:[3,12,14,16],actual:15,add:[3,14,15,16],add_event_handl:3,add_ledger_archiv:[3,12],add_ledger_cr:[3,12],add_ledger_exercis:3,add_ledger_init:[3,12],add_ledger_packages_ad:3,add_ledger_readi:[3,12],add_ledger_transaction_end:3,add_ledger_transaction_start:3,add_new:3,add_singl:3,added:[3,15],adding:[3,15],addit:[3,6,12,15],addition:11,address:15,adject:6,admin_url:3,advanc:3,affili:[14,16],after:[3,14,15,16],afterward:15,against:[3,15],agre:16,agreement:[15,16],aid:6,aio_glob:3,aio_parti:[3,12],aio_run:3,aioglobalcli:3,aiopartycli:3,alic:[11,12,14,16],alice_cli:[12,14,16],all:[3,6,11,14,15,16],all_parti:15,allow:[3,15],alongsid:3,alreadi:[3,11],also:[3,14,15,16],altern:3,alwai:[6,15],amount:[3,11],ani:[3,6],anyth:[3,15],anytim:16,apach:[14,16],api:[1,6,11,12,14,16],append:16,appli:[3,6],applic:[3,11,13],appropri:16,arbitrari:3,archiv:[3,11,14,16],arg:2,argpars:2,argument:[3,6,12,15],argumentpars:2,aris:6,around:5,arrai:3,assert:15,asset:[10,11,12,14,16],assign:[14,16],assist:5,associ:[3,14,16],assum:[6,11,14,15,16],async:[3,16],asynchron:3,asyncio:[3,12,16],attribut:6,author:15,authorrol:15,automat:15,await:[3,11,16],background:[3,15],base:[2,3,6,12],baseev:3,basi:[14,16],basic:11,becaus:[15,16],been:[3,12,16],befor:[3,6,15,16],begin:3,behalf:3,behavior:[3,6],being:[3,6],below:0,best:16,bin:[14,16],binaryio:3,bind:16,bit:15,blank:15,block:[3,14,15,16],bob:[11,12,14,16],bob_client:[12,14,16],bodi:15,bool:[0,3,6],bot:[1,11],botcallback:3,botcollect:3,botentri:3,botfilt:3,both:[6,16],botinvoc:3,botstat:3,builtin:6,buyer:16,calcul:3,calculaterequest:0,calculaterespons:0,call:[3,12,14,15],callabl:3,callback:[3,14,15],caller:3,can:[3,6,14,15,16],cancel:16,cannot:[3,14,16],caught:3,caus:14,cdata:[12,14,15,16],certain:14,chang:[3,12],check:3,choic:[3,6,14,15],choice_argu:3,choice_nam:[3,6],choicemetadata:6,choiceref:6,cid:[3,11,12,14,15,16],clearli:16,cli:[1,11],clicommand:2,client:[1,6,8,10,12,14,15,16],client_mgr:[14,15,16],close:11,cmd:2,code:[3,6,14,15,16],coerc:3,coercion:6,collaps:12,collect:3,column:15,comfort:3,command:[2,3,6,11,14,15,16],commandbuild:3,commandpayload:3,commit:[14,16],common:3,commun:3,complet:[3,16],composit:6,comput:0,config:3,configur:[3,14],connect:[3,11,14,15],consist:12,construct:6,constructor:[0,6],consum:[14,15],contain:[0,1,3,6,7,8,12,14,16],content:15,contextmanag:3,contextu:3,contract:[3,6,11,12,14,15,16],contract_dict:11,contract_id:6,contract_kei:3,contract_stor:16,contractarchiveev:3,contractcontextualdata:3,contractcontextualdatacollect:3,contractcreateev:3,contractexercisedev:3,contractid:[0,3,6,14,15,16],contractstor:16,control:[14,15,16],conveni:[3,15],convent:12,convert:3,copyright:[14,16],core:[0,1,3,11],coroutin:3,correct:3,correspond:[3,14],could:15,cours:14,creat:[3,6,11,13,14,16],create_and_exercis:3,create_cli:[12,14,15,16],create_futur:16,create_if_miss:3,create_initial_workflow_st:16,createa:14,createcommand:6,createdecimallett:15,createintlett:15,createlett:15,createlistintlett:15,createtimelett:15,creation:[14,16],critic:16,ctrl:3,currenc:11,currency_cid:11,current:[3,6],custom:14,daemon:3,dalf:3,damast:[1,11],daml:[0,5,6,11,13],daml_fil:15,daml_ledger_parti:3,daml_ledger_url:3,damlsdk:[1,11],dar:3,data:[0,3,12],date:[0,3],datetim:[0,3],dazl:[0,10,12,14,15,16],deactiv:15,debug:16,decim:[0,3,6,15],declar:3,decor:3,def:[11,14,15,16],defin:[6,14,15,16],del:16,delet:16,deliv:15,demonstr:16,depend:16,deploi:[14,16],describ:[6,14,16],descript:6,design:[14,16],detect:[3,14,16],develop:[15,16],dict:[0,3,6,15,16],dictionari:[0,3],differ:[8,16],difficult:15,digit:[10,11,14,16],directli:[3,6],dirnam:15,disabl:3,disambigu:6,dish:15,dispatch:3,dispos:15,doc_begin:[14,16],doc_end:[14,16],doe:3,domain:6,don:6,done:[3,14,16],down:[3,15],download:[14,16],drain:3,drawn:15,dump_al:[14,15,16],dure:14,each:[14,15,16],easier:16,easili:15,either:[3,6,15],els:[15,16],empti:0,encapsul:16,encount:3,ensur:3,ensure_dar:3,ensure_packag:3,entir:3,entri:3,environ:3,equival:3,error:3,even:15,event:[3,6,11,14,15,16],event_kei:3,eventkei:3,eventu:6,ever:6,everi:15,everyth:15,exampl:[0,11,13,14,15],except:[3,15],execut:[2,3,12,14,15,16],exercis:[3,6,11,14,15,16],exercise_by_kei:3,exercisecommand:6,exist:[3,6],exit:[3,15,16],exit_cod:[14,15,16],expect:6,expos:[3,5,9,15],expr:0,express:0,factori:3,fals:[3,16],fashion:3,fetch:[3,15],few:15,field:[0,3,6],file:[14,16],filter:3,filter_fn:3,find:[3,16],find_act:[3,11],find_by_id:3,find_histor:3,find_nonempti:3,find_on:3,finish:16,first:[15,16],five:15,flight:3,focu:15,follow:[0,3,11,14,15,16],for_json:6,format:[7,8,15],formerli:12,forward:[14,16],framework:14,frequent:6,friend:15,friendli:3,from:[3,6,11,12,14,15,16],from_ev:3,fulli:[3,11,15],function_accept_invit:16,function_ingest_the_messag:14,function_multi_creation_depend:16,further:15,futur:[3,16],gener:[3,5,9,14],genesi:[14,16],genesis_contract:14,genesiscontract:16,get:[3,16],get_event_loop:16,get_pretty_print:7,get_tim:3,getlogg:16,gettim:14,give:3,given:[3,16],global:[3,16],globalcli:3,glossari:11,gmbh:[14,16],gracefulli:3,grant:15,grpcio:11,guarante:[3,16],handl:3,handler:[2,3,12,14,15,16],happen:[12,14,15],has:[3,12,14,16],have:[3,11,12,14,15,16],head:3,height:[14,16],helper:15,here:[6,14,16],hidden:3,high:3,higher:3,histor:3,how:[14,16],howev:[14,16],http:[11,12,14,16],ident:3,identifi:[3,6,14,16],if_miss:3,ignor:15,immedi:[3,15],impl:3,implement:[3,8,11,14,16],include_archiv:3,incorpor:3,indefinit:3,index:15,indic:[14,15],individu:3,info:[3,16],inform:12,infrastructur:3,ingest:[11,13,16],ingest_messag:14,ingest_the_messag:14,ingestmessag:14,initev:3,initi:[3,11,15,16],input:14,inspect:[11,13],inspector:[14,15,16],instal:[3,11],install_signal_handl:3,instanc:[3,6,15],instanti:[3,6,15],instead:[3,15],instruct:3,integ:0,interact:[1,3],interfac:3,intermedi:16,intern:15,introduc:15,invit:[15,16],invite_ticket_buy:16,invite_ticket_sel:16,inviteasauthor:15,inviteasreceiv:15,inviteauthorrol:15,inviteparticip:15,inviteparticipantsinprogress:16,invitereceiverrol:15,inviteticketbuy:16,inviteticketsel:16,invoc:3,invok:[3,6,14],involv:[6,14,16],is_match:16,isinst:16,item:16,iter:15,its:[6,14,15,16],itself:6,join:[3,15,16],json:6,just:6,keep:15,kei:[0,3,15,16],kind:6,know:6,known:[2,3],kwarg:3,lambda:[12,15],lane:15,lastli:15,later:[11,15],least:3,ledger:[1,3,6,10,11,12,13,14,16],ledger_arch:3,ledger_archiv:3,ledger_cr:[3,11],ledger_exercis:3,ledger_init:3,ledger_packages_ad:3,ledger_readi:[3,11],ledger_run:[14,15,16],ledger_transaction_end:3,ledger_transaction_start:3,ledgercaptureplugin:[14,15,16],ledgerclientmanag:15,ledgermetadata:3,leger:14,length:[0,3],let:15,letter:[11,13],level:[3,6],librari:[3,6,8,10],licens:[14,16],like:15,line:[2,14],list:[0,3,6,14,15,16],listallcommand:2,listen:[3,11,15],listtyp:6,liter:3,live:[14,16],load:11,local:3,localhost:[11,12,14,16],log:[3,16],log_level:3,logger:3,logic:3,longer:[15,16],lookup:16,loop:[3,16],low:6,made:3,mai:[3,16],main:[2,3,15],make:15,manag:[3,12,15],manipul:3,manner:[14,16],manual:15,map:0,mark:16,market:15,match:[3,16],maximum:3,mean:3,member:[6,15],member_cli:15,member_party_count:15,messag:[11,13,16],message_ingest:14,messageingest:14,messageingestertest:14,metadata:[3,12],method:[3,6,15],metric:3,metricev:3,migrat:11,mileston:16,min_count:3,minimum:[3,15],model:[0,1,3,7,11,13],modul:[5,6,7,9,11,14,15,16],more:[3,12,14,15,16],most:[3,6,15],move:[14,16],multi:16,multipl:[11,16],must:[6,15,16],name:[0,2,3,6,14,15,16],named_arg:6,namedargumentlist:6,nativ:3,necessari:3,need:[3,6,11],network:[3,11,12],networkconfig:3,new_client:[14,15,16],new_datetim:3,new_typ:3,newli:3,newtyp:3,next:16,node:15,non:[3,14],nonconsum:15,none:[3,6,16],nonetyp:3,normal:3,note:[3,6,14,16],notic:15,notif:3,notifi:3,notion:3,now:[3,12,15],num:0,number:3,object:3,occur:[3,14,15,16],off:[3,6],offer_ticket_purchase_agr:16,offerticketpurchaseagr:16,offic:[11,13],old:12,omit:3,on_archiv:[3,12],on_creat:[3,12,14,15,16],on_init:12,on_init_metadata:12,on_readi:[3,12,14,15],on_something_of_valu:11,onc:15,one:[2,3,14,15,16],onli:[3,14,16],oper:[3,14,15,16],operator_cli:16,operatorrol:14,operatorrolecid:14,option:[3,6,7],order:[3,12,15,16],origin:[3,12],originalmessageingestedtim:14,other:[3,14,15,16],our:[14,16],out:[3,15],outgo:3,output:[3,11,13,15],over:[14,16],packag:[11,12],package_id:3,packagesaddedev:3,packagestor:7,param:16,paramet:[3,6,12,14,15],parser:2,parti:[0,3,11,12,14,15,16],particip:[11,13,16],participant_url:[12,14,15,16],participantledgercli:15,party_bot:3,party_cli:3,party_nam:12,partycli:3,partyconfig:3,pass:[6,14],path:[3,15],pathlib:3,paus:3,perform:[14,16],perman:3,perspect:3,phase:16,platflorm:[14,16],platform:[14,16],plugin:[14,15,16],point:[15,16],popen:16,popul:3,port:16,possibl:3,post:[11,13],postman:[11,13],postman_cli:15,postman_parti:15,postmanrol:15,potenti:3,practic:16,pre:6,predecessor:6,prefer:3,present:[3,16],pretti:[1,11],prettyopt:7,prettyprintbas:7,primari:3,print:[7,11,12,15],print_cmd_help:2,proce:16,process:[3,6,15,16],produc:[14,16],product:[0,15],progress:[15,16],project:[14,16],prompt:[14,16],properti:3,protocol:[1,11],provid:[3,12,14,15],purchas:16,purchase_agr:16,purchase_ticket:16,purchaseticket:16,purchs:16,purpos:16,python3:[14,16],python:[0,1,6,10,13],pyyaml:11,queri:3,queu:3,queue:3,quicker:15,rais:3,ran:15,rang:15,react:[14,16],read:[3,6,11],readabl:15,readi:[3,11,15],readyev:3,real:15,realpath:15,receiv:[3,15],receiveraddress:15,receivercid2:15,receivercid:15,receiverrol:15,recommend:[14,16],record:0,recordtyp:6,rectangl:0,refer:[6,14],regist:[3,12,14,15,16],register_event_handl:[14,16],registr:[3,14,15],rejectmessag:14,releas:11,reltim:0,remain:14,remot:3,remov:3,replac:[6,15],repres:[6,16],represent:6,request:[0,3],requestor:14,requestprocessingparti:14,requir:[3,11],reserv:[14,16],resolv:[3,16],resolved_config:3,respect:16,respond:15,respons:15,restart:3,result:[6,15,16],resum:3,reus:6,right:[3,14,16],role:[15,16],rout:15,row:3,rule:6,run:[2,3,11,12,14,15,16],run_forev:[3,12],run_stat:3,run_test:15,run_until_complet:[3,14,15,16],runstat:3,runtim:3,safe:3,same:[6,14,16],sampl:[14,16],sample_callback_oncr:14,sample_daml_scenario_ingest_messag:14,sandbox:[11,14,15,16],save:16,save_purchase_agr:16,scalar:6,scalartyp:6,scenario:[14,16],schedul:3,script:15,sdk:[5,14,15,16],search:3,second:3,section:11,see:[3,15],self:16,seller:16,semver:11,send:[3,6,11,13],sender:15,sent:15,sentlett:15,sentlettercid2:15,sentlettercid:15,separ:15,sequenc:[3,6,14,16],sequenti:[14,16],seri:[14,16],serial:8,serv:15,server:[3,11,14,15,16],servic:3,set:[3,11,12,13,14,16],set_config:[3,11,12],set_result:16,set_tim:3,set_up:[11,15],setinitialworkflowst:16,sever:15,shall:[14,16],should:[3,6,15],show:15,shut:3,shutdown:3,side:[1,3,11],sigint:3,signal:3,signatori:[14,15,16],sigquit:3,similar:[14,16],simpl:[2,6],simple_cli:[3,11,15],simple_glob:3,simple_parti:[3,11],simpleglobalcli:3,simplepartycli:3,sinc:14,singl:[0,3,11,12,15,16],situat:[6,14],situt:16,skip:3,snapshot:3,snippet:14,sole:16,some:[0,3,6,11,12,13],somefield:11,sometext:11,someth:3,somethingof:11,sort:15,sortedlett:15,sourc:[2,3,6,7],source_loc:3,sourceloc:3,spdx:[14,16],specif:[0,3,6,15],specifi:[3,6,14,16],split:15,stamp:3,start:[3,14,15,16],start_in_background:3,starter:[14,16],state:[3,11,13,14,15],stdout:[14,15,16],step:[14,15,16],stop:[3,15,16],stop_al:3,store:[3,7,12,15,16],str:[0,3,6,7],stream:6,string:6,structur:14,style:3,subclass:6,submiss:3,submit:[3,11,15,16],submit_cr:[3,11],submit_create_and_exercis:3,submit_exercis:3,submit_exercise_by_kei:3,submit_fn:3,submodul:[1,11],subpackag:11,subprocess:16,subscrib:3,subsequ:[14,16],successfulli:[3,14,15],sum:0,suppli:6,support:[3,8],sure:15,switzerland:[14,16],synchron:3,sys:15,system:[1,11],tabl:0,tag:6,take:[3,12],tbc:15,tchoos:14,tear:15,templat:[0,3,6,11,14,15,16],template_id:6,template_nam:3,termin:[3,14,15],test:[14,15,16],text:[0,15],thank:11,thei:[3,6,15],them:[3,15],thereaft:16,thi:[0,1,3,6,7,8,11,14,15,16],those:[6,14],thread:3,three:16,through:[11,13,14,16],thu:[14,16],ticket:16,ticket_buyer_invit:16,ticket_buyer_rol:16,ticket_purchase_agr:16,ticket_seller_invit:16,ticket_seller_rol:16,ticketbuy:16,ticketbuyerinvit:16,ticketbuyerrol:16,ticketbuyerrole1:16,ticketpurchaseagr:16,ticketpurchaseagreementoff:16,ticketsel:16,ticketsellerinvit:16,ticketsellerrol:16,ticketsellerrole1:16,tickettransactionsinprogress:16,tickettransactiontest:16,time:[0,3,6,12,14,15],timedelta:[0,3],timeout:3,told:3,total:[14,16],totext:16,track:3,trade:3,traderequest:14,traderequestacceptedtim:14,traderequestcid:14,traderespons:14,traderesponseacknowledgedtim:14,traderesponsecid:14,transact:[3,16],transaction_limit:16,transactionendev:3,transactionstartev:3,transit:16,transition_to_ticket_transactions_in_progress:16,transition_to_workflow_complet:16,tupl:[3,16],tutori:[11,15],two:[6,12,14],type:[0,1,3,7,11],type_arg:6,type_paramet:6,typeadject:6,typerefer:[3,6],types_stor:7,typevari:6,typic:14,typing_extens:3,under:[14,16],underli:[3,6],union:[3,6],uniqu:3,unit:0,univers:15,unpars:6,unresolvedtyperefer:3,unsortedlett:15,unspecifi:3,unsupportedtyp:6,until:[3,16],upload:3,upon:14,ups:3,url:[3,11,12,14,15,16],usd:11,use:[0,3,15,16],used:[3,6,14,16],useful:[3,15],using:15,util:[1,5,7,11],valid:[0,3],valu:[0,3,6,11,15,16],variabl:3,variant:0,varianttyp:6,variou:7,venv:[14,16],verbos:16,veri:15,verifi:[14,16],version:[3,11],view:3,wai:3,wait:[3,11,16],walk:[14,16],want:[3,15],wants_any_kei:3,were:[3,12,14,16],what:[14,15],when:[3,6,14,15,16],whenev:3,where:[0,3,6,12,14,15,16],whether:3,which:[3,6,14,15,16],who:15,whose:3,width:0,wish:3,within:[3,16],without:6,word:3,work:[3,6,14,15],workflow:[3,11,13,14,15],workflow_complet:16,workflow_id:3,workflow_st:16,workflow_state_exampl:16,workflow_state_sampl:16,workflow_ticket_transactions_in_progress:16,workflowcomplet:[14,16],workflowsetupinprogress:16,workflowstateexampl:16,workflowtickettransactionsinprogress:16,would:[3,14],wouldn:15,wrap_as_command_submiss:3,write:[1,3,11,14,16],yet:3,you:[3,6,11,15],your:[6,14,16]},titles:["Basics","dazl package","dazl.cli package","dazl.client package","dazl.damast package","dazl.damlsdk package","dazl.model package","dazl.pretty package","dazl.protocols package","dazl.util package","Glossary","dazl: DA client library for Python","Migrate","Tutorials","Message Ingester","Post Office","Workflow State Example"],titleterms:{api:3,applic:[14,16],archiv:12,basic:0,bot:3,cli:2,client:[3,11],content:[1,2,3,8,11],core:6,creat:[12,15],damast:4,daml:[14,15,16],damlsdk:5,dazl:[1,2,3,4,5,6,7,8,9,11],depend:11,event:12,exampl:16,get:11,glossari:10,ingest:14,initi:12,inspect:15,ledger:15,letter:15,librari:[11,12],listen:12,messag:14,migrat:12,model:[6,14,15,16],modul:[1,2,3,8],offic:15,output:[14,16],packag:[1,2,3,4,5,6,7,8,9],particip:15,post:15,postman:15,pretti:7,protocol:8,python:[11,14,16],readi:12,send:15,set:15,side:6,some:15,start:11,state:16,submodul:[2,3,8],subpackag:1,system:6,tabl:11,through:15,tutori:13,type:6,util:9,workflow:16,write:6}}) \ No newline at end of file diff --git a/docs/tutorials.html b/docs/tutorials.html new file mode 100644 index 00000000..53e6be19 --- /dev/null +++ b/docs/tutorials.html @@ -0,0 +1,133 @@ + + + + + + + + Tutorials + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ + + + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/tutorials_message_ingester.html b/docs/tutorials_message_ingester.html new file mode 100644 index 00000000..3039b18d --- /dev/null +++ b/docs/tutorials_message_ingester.html @@ -0,0 +1,396 @@ + + + + + + + + Message Ingester + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

Message Ingester

+

This example sets up a workflow involving two parties, Alice and Bob. When writing a DAML +application, we recommend the following steps:

+
+
    +
  1. Describe your workflow as a series of contracts in DAML.

  2. +
  3. Write one or more DAML test scenarios that walk through each step of the workflow, starting from creation of the genesis contract, through a sequence of exercise commands, to the final state of the workflow. (Note: The DAML test scenarios are used for verifying the steps of the workflow in a sequential manner. However, when the workflow is deployed to a live platflorm, the events that prompt steps in the workflow to move forward cannot be assumed to occur sequentially.)

  4. +
  5. Write your application.

  6. +
  7. Test your application on the sandbox. The ledger server implements the same API, so performance testing can be done with the same application.

  8. +
+
+

The Message Ingester workflow is as follows:

+
    +
  1. The genesis contract, OperatorRole, is created. The OperatorRole contract is a contract that describes the operation(s) that the operator of this workflow can perform. In this example, we have assigned the party name Alice to the OperatorRole.

  2. +
  3. Alice ingests an input message, which causes the generation of a TradeRequest contract.

  4. +
  5. Bob is the requestProcessingParty on the TradeRequest contract, and exercises the +AcceptMessage choice on the TradeRequest. This causes the generation of a TradeResponse contract.

  6. +
  7. Alice exercises the Acknowledge choice on the TradeResponse contract. +This causes the generation of a WorkflowCompleted contract.

  8. +
+
+

DAML Model

+

This example assumes the following DAML:

+
daml 1.0
+module MessageIngester where
+
+template OperatorRole
+    with
+        operator: Party
+    where
+        signatory operator
+        controller operator can
+            IngestMessage with requestProcessingParty: Party
+                returning ContractId TradeRequest
+                to do
+                    tchoose <- getTime
+                    create TradeRequest with messageIngester=operator; requestProcessingParty; originalMessageIngestedTime=tchoose;
+
+template TradeRequest
+    with
+        messageIngester: Party
+        requestProcessingParty: Party
+        originalMessageIngestedTime: Time
+    where
+        signatory messageIngester
+
+        controller requestProcessingParty can
+            AcceptMessage with acknowledgingParty: Party
+                returning ContractId TradeResponse
+                to do
+                    tchoose <- getTime
+                    create TradeResponse with acknowledgingParty=messageIngester; tradeRequestAcceptedTime=tchoose; originalMessageIngestedTime;
+            RejectMessage
+                returning {}
+                to return {}
+
+template TradeResponse
+    with
+        acknowledgingParty: Party
+        tradeRequestAcceptedTime: Time
+        originalMessageIngestedTime: Time
+    where
+        signatory acknowledgingParty
+
+        controller acknowledgingParty can
+            Acknowledge
+                returning ContractId WorkflowCompleted
+                to do
+                    create WorkflowCompleted with acknowledgingParty; tradeRequestAcceptedTime; originalMessageIngestedTime;
+
+template WorkflowCompleted
+    with
+        acknowledgingParty: Party
+        tradeRequestAcceptedTime: Time
+        originalMessageIngestedTime: Time
+    where
+        signatory acknowledgingParty
+
+        controller acknowledgingParty can
+            Archive
+                returning {}
+                to return {}
+
+test messageIngesterTest = 
+    scenario
+        operatorRoleCid <- 'Alice' commits create OperatorRole with operator='Alice'
+        -- DOC_BEGIN: SAMPLE_DAML_SCENARIO_INGEST_MESSAGE
+        tradeRequestCid <- 'Alice' commits exercise operatorRoleCid IngestMessage with requestProcessingParty='Bob'
+        -- DOC_END: SAMPLE_DAML_SCENARIO_INGEST_MESSAGE
+        tradeResponseCid <- 'Bob' commits exercise tradeRequestCid AcceptMessage with acknowledgingParty='Alice'
+        workflowCompleted <- 'Alice' commits exercise tradeResponseCid Acknowledge
+        'Alice' commits exercise workflowCompleted Archive 
+
+
+

The messageIngesterTest scenario describes a sample execution of the workflow, and is the basis from from which +our Python application will be designed.

+
+
+

Python Application

+
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+from dazl import create, exercise
+from dazl.client import create_client
+from dazl.plugins import LedgerCapturePlugin
+
+parties = [ 'Alice','Bob']
+url = 'http://localhost:7600/'
+
+
+def genesis_contract(_, __):
+    return create('MessageIngester.OperatorRole', { 'operator' : 'Alice' })
+
+# DOC_BEGIN: FUNCTION_INGEST_THE_MESSAGE
+def ingest_the_message(cid, cdata):
+    ingest_message = [ exercise(cid, 'IngestMessage', {'requestProcessingParty': 'Bob'})]
+    return ingest_message
+    # DOC_BEGIN: FUNCTION_INGEST_THE_MESSAGE
+
+
+def accept_the_message(cid, cdata):
+    accept_message_action = [ exercise(cid, 'AcceptMessage', {'acknowledgingParty': 'alice'})]
+    return accept_message_action
+
+
+def acknowledge_the_message(cid, cdata):
+    acknowledge_message_action = [ exercise(cid, 'Acknowledge', {})]
+    return acknowledge_message_action
+
+
+def register_event_handlers(client_mgr):
+    #define a sandbox client, associated with the 'operator' party, and how it reacts to events
+    alice_client = client_mgr.new_client('Alice')
+    alice_client.on_ready(genesis_contract)
+    # DOC_BEGIN: SAMPLE_CALLBACK_ONCREATED
+    alice_client.on_created('MessageIngester.OperatorRole', ingest_the_message)
+    # DOC_END: SAMPLE_CALLBACK_ONCREATED
+    alice_client.on_created('MessageIngester.TradeResponse', acknowledge_the_message)
+
+    #define a sandbox client, associated with the 'requestor' party, and how it reacts to events
+    bob_client = client_mgr.new_client('Bob')
+    bob_client.on_created('MessageIngester.TradeRequest', accept_the_message)
+
+
+def run():
+    with create_client(parties=parties, participant_url=url) as client_mgr:
+        inspector = LedgerCapturePlugin.stdout()
+        try:
+            client_mgr.register(inspector)
+            register_event_handlers(client_mgr)
+            ledger_run = client_mgr.run_until_complete()
+            return ledger_run.exit_code
+        finally:
+            inspector.dump_all()
+
+if __name__ == "__main__":
+    run()
+
+
+
+
To run this code sample:
    +
  1. Download the SDK

  2. +
  3. create a new project: da new my-project-name-here

  4. +
  5. cd my-project-name-here

  6. +
  7. Create a file, MessageIngester.daml, that contains the above listed DAML.

  8. +
  9. Createa file, message_ingester.py, that contains the above listed Python code.

  10. +
  11. Download the dazl-starter template (which also creates a Python venv): da project add dazl-starter

  12. +
  13. Start the sandbox: da sandbox

  14. +
  15. Run the application: ./venv/bin/python3 message_ingester.py

  16. +
+
+
+

run() configures client_mgr such that it will invoke the work() function after +it has successfully connected to the platform/sandbox.

+

work() contains a command to create the genesis contract, and a series of callback registrations, +each of which provide a reference to a custom python function that shall be invoked when a certain +leger event occurs. For example, this registration:

+
    alice_client.on_created('MessageIngester.OperatorRole', ingest_the_message)
+
+
+

indicates that the ingest_the_message() shall be invoked after the OperatorRole contract is +created.

+
+
ingest_the_message() describes what will happen when at on_created event occurs:
    +
  1. The DAZL framework, upon detecting the specified on_created event, will invoke this function and pass it the contract id (cid) and corresponding contract parameters (cdata).

  2. +
  3. An exercise choice will be performed on the contract (in this case, it’s an OperatorRole contract)

  4. +
  5. That exercise choice will be invoked on a DAML contract with a contract id of cid, with the specified parameters.

  6. +
  7. Since this is a non-consuming choice, the OperatorRole contract will remain active.

  8. +
+
+
+
def ingest_the_message(cid, cdata):
+    ingest_message = [ exercise(cid, 'IngestMessage', {'requestProcessingParty': 'Bob'})]
+    return ingest_message
+
+
+

The exercise() call in the above code snippet corresponds to this line in our DAML test scenario:

+
        tradeRequestCid <- 'Alice' commits exercise operatorRoleCid IngestMessage with requestProcessingParty='Bob'
+
+
+

Thus, a typical application would have a similar structure to work() in that it will contain only one command +to create the genesis contract, and all other code will describe the callback handlers and the situations under which +those callbacks shall be invoked.

+
+
+

Application Output

+

This application will produce this output:

+
2 total contracts over 2 templates
++- party 'Alice' (block heights 1 to 5)
+|+ party 'Bob' (block heights 2 to 5)
+||
+
+MessageIngester.OperatorRole (1 contract) ------------------------------------------------------------------------------
+#cid operator
+C  0:0_ Alice
+
+MessageIngester.WorkflowCompleted (1 contract) -------------------------------------------------------------------------
+#cid acknowledgingParty originalMessageIngestedTime TradeResponseAcknowledgedTime
+C  3:2_ Alice              1970-01-01T00:00:00Z        1970-01-01T00:00:00Z
+
+
+

The TradeRequest and TradeResponse contracts were created, and subsequently archived during the course +of the workflow, thus only OperatorRole WorkflowCompleted and (which has no consuming choices) are active on the ledger +when this application terminates.

+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/tutorials_post_office.html b/docs/tutorials_post_office.html new file mode 100644 index 00000000..fd0b79a2 --- /dev/null +++ b/docs/tutorials_post_office.html @@ -0,0 +1,499 @@ + + + + + + + + Post Office + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

Post Office

+

This example sets up a post office, with a Postman who routes letters, instances of Author +who send letters, and instances of Receiver who receive letters.

+

Each author, when instantiated, will immediately send letters to five of their friends.

+
+

DAML Model

+

This example assumes the following DAML:

+
daml 1.2
+module Main where
+
+
+-- Roles -----------------------------------------------------------------------
+
+template PostmanRole
+  with
+    postman : Party
+  where
+    signatory postman
+    controller postman can
+      nonconsuming InviteParticipant : (ContractId InviteAuthorRole, ContractId InviteReceiverRole)
+        with
+          party : Party; address: Text
+        do
+          c <- create InviteAuthorRole with postman; author = party
+          d <- create InviteReceiverRole with postman; receiver = party; address
+          return (c, d)
+
+template AuthorRole
+  with
+    postman : Party
+    author: Party
+  where
+    signatory postman
+    controller author can
+      nonconsuming CreateLetter : ContractId UnsortedLetter
+        with
+          address : Text
+          content : Text
+        do
+          create UnsortedLetter
+            with
+              postman
+              sender = author
+              address
+              content
+
+      nonconsuming CreateIntLetter : ContractId UnsortedLetter
+        with
+          address : Text
+          content : Int
+        do
+          create UnsortedLetter
+            with
+              postman
+              sender = author
+              address
+              content = (show content)
+
+      nonconsuming CreateDecimalLetter : ContractId UnsortedLetter
+        with
+          address : Text
+          content : Decimal
+        do
+          create UnsortedLetter
+            with
+              postman
+              sender = author
+              address
+              content = (show content)
+
+      nonconsuming CreateTimeLetter : ContractId UnsortedLetter
+        with
+          address : Text
+          content : Time
+        do
+          create UnsortedLetter
+            with
+              postman
+              sender = author
+              address
+              content = (show content)
+
+      nonconsuming CreateListIntLetter : ContractId UnsortedLetter
+        with
+          address : Text
+          content : [Int]
+        do
+          create UnsortedLetter
+            with
+              postman
+              sender = author
+              address
+              content = (show content)
+
+template ReceiverRole
+  with
+    postman : Party
+    receiver : Party
+    address : Text
+  where
+    signatory postman
+    controller receiver can
+      AcceptLetter : ContractId AcknowlegedLetter
+        with
+          sentLetterCid : ContractId SentLetter
+        do
+          sentLetterCid2 <- fetch sentLetterCid
+          assert $ sentLetterCid2.receiver == receiver
+          assert $ sentLetterCid2.receiverAddress == address
+
+          create AcknowlegedLetter
+            with
+              sender = sentLetterCid2.sender
+              receiver
+              receiverAddress = address
+              content = sentLetterCid2.content
+
+    controller postman can
+      Deactivate : ()
+        do
+          assert $ postman == postman
+
+template InviteAuthorRole
+  with
+    postman : Party
+    author : Party
+  where
+    signatory postman
+    controller author can
+      AcceptInviteAuthorRole : ContractId AuthorRole
+        do
+          create AuthorRole with postman; author
+
+template InviteReceiverRole
+  with
+    postman : Party
+    receiver : Party
+    address : Text
+  where
+    signatory postman
+    controller receiver can
+      AcceptInviteReceiverRole : ContractId ReceiverRole
+        do
+          create ReceiverRole with postman; receiver; address
+
+-- Letters ---------------------------------------------------------------------
+
+template UnsortedLetter
+  with
+    postman : Party
+    sender : Party
+    address : Text
+    content : Text
+  where
+    signatory sender
+    controller postman can
+      Sort : ContractId SortedLetter
+        with
+          receiverCid : ContractId ReceiverRole
+        do
+          receiverCid2 <- fetch receiverCid
+          assert $ receiverCid2.address == address
+          assert $ receiverCid2.postman == postman
+
+          create SortedLetter
+            with
+              postman
+              sender
+              receiver = receiverCid2.receiver
+              receiverAddress = receiverCid2.address
+              content
+
+template SortedLetter
+  with
+    postman : Party
+    sender : Party
+    receiver : Party
+    receiverAddress : Text
+    content : Text
+  where
+    signatory sender
+    controller postman can
+      Deliver : ContractId SentLetter
+        do
+          create SentLetter with sender; receiver; receiverAddress; content
+
+template SentLetter
+  with
+    sender : Party
+    receiver : Party
+    receiverAddress : Text
+    content : Text
+  where
+    signatory sender
+    controller receiver can
+      AcceptSentLetter : ContractId AcknowlegedLetter
+        do
+          create AcknowlegedLetter with sender; receiver; receiverAddress; content
+
+template AcknowlegedLetter
+  with
+    sender : Party
+    receiver : Party
+    receiverAddress : Text
+    content : Text
+  where
+    signatory receiver
+
+    agreement (show sender) <> " sent" <> content <> " to " <> (show receiver) <> " at " <> (show receiverAddress)
+
+
+
+
+

Create the Postman

+

The Postman serves as the operator of this market, and its role contract must be defined before +anything else can happen:

+
+
If you are running this code example through the SDK, it will:
    +
  1. start up a Ledger Sandbox in the background, point it to the above DAML model,

  2. +
  3. run the code against that Ledger Sandbox, and

  4. +
  5. stop the Ledger Sandbox.

  6. +
+
+
+

First, a few important imports:

+
from os import path
+
+from dazl import create, sandbox
+from dazl.client import create_client
+
+DAML_FILE = path.realpath(path.join(path.dirname(__file__), './Main.daml'))
+
+POSTMAN_PARTY = 'Postman'
+MEMBER_PARTY_COUNT = 10
+
+
+

Then the main dish:

+
def run_test(url):
+    all_parties = [POSTMAN_PARTY]
+
+    with create_client(parties=all_parties, participant_url=url) as client_mgr:
+        postman_client = client_mgr.new_client(POSTMAN_PARTY)
+        postman_client.on_ready(
+            lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY)))
+
+        ledger_run = client_mgr.run_until_complete()
+        return ledger_run.exit_code
+
+
+

Lastly, the code that actually runs everything:

+
if __name__ == '__main__':
+    import sys
+
+    with sandbox(DAML_FILE) as server:
+        exit_code = run_test(server.url)
+        sys.exit(int(exit_code))
+
+
+
+

Note

+

dazl.sandbox() is a helper function for creating a disposable sandbox, running +a test, and terminating the process. You wouldn’t use it when pointing to a production instance, +but it is very useful for testing. All of these examples assume that you are using a blank +ledger every single time. As you iterate through the steps of the tutorial, make sure to stop and +start the ledger each time if you’re using dazl.sandbox().

+
+

dazl.simple_client() is a helper function for creating a LedgerClientManager. +At a minimum, you must provide it a list of parties to listen as, and a URL to the Sandbox +(or Ledger Server participant node when running against a real instance).

+

To create a client for a specific party, call LedgerClientManager.new_client(). There are +several key methods on it; this example introduces ParticipantLedgerClient.on_ready, which is +called when the connection to the ledger is initialized. The parameters are ignored at this point. +The callback, like most callbacks, can return a Command to submit to the ledger. In this +example, a Main.postmanRole contract is to be created with one argument named postman +and a value of 'Postman'

+

Finally, to actually start the manager and all the clients, call +LedgerClientManager.run_until_complete. The code should run and return an exit code of 0, +indicating that the script successfully ran. But what if you wanted to actually see what happened +to the ledger afterwards?

+
+
+

Inspect the Ledger

+

Using the convenience sandbox() method makes development a bit quicker, but it is difficult to +actually see what is happening afterwards because it tears down the ledger and all of its state. +You could either start a Sandbox instance manually through the SDK, or you could output the ledger +after every run:

+
from dazl.plugins import LedgerCapturePlugin
+
+def run_test(url):
+    all_parties = [POSTMAN_PARTY]
+
+    with create_client(parties=all_parties, participant_url=url) as client_mgr:
+        inspector = LedgerCapturePlugin.stdout()
+        try:
+            postman_client = client_mgr.new_client(POSTMAN_PARTY)
+            postman_client.on_ready(
+                lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY)))
+
+            client_mgr.register(inspector)
+
+            ledger_run = client_mgr.run_until_complete()
+            return ledger_run.exit_code
+        finally:
+            inspector.dump_all()
+
+
+

We have added dazl.plugin.LedgerCapturePlugin, which listens for events from the ledger and +stores them internally to be drawn out later. The main body of run_test outputs the result of +the ledger in a try/finally block so that the ledger is always printed out, even if an +exception occurs.

+

dazl.plugin.LedgerCapturePlugin exposes several class methods for easily creating an +instance; in this example, LedgerCapturePlugin outputs its results to stdout when +dump_all is called.

+
+
+

Set up participants

+

We have now created the postman and can see that on the ledger; now we’ll add the other participants +of this market. For readability, let’s also split out all the registration methods into a separate +set_up function so that we can keep the focus on adding listeners to the ledger:

+
def run_test(url):
+    members = [dict(party=f'Member {i}', address=address(i)) for i in
+               range(0, MEMBER_PARTY_COUNT)]
+    all_parties = [POSTMAN_PARTY] + [member['party'] for member in members]
+
+    with create_client(parties=all_parties, participant_url=url) as client_mgr:
+        inspector = LedgerCapturePlugin.stdout()
+        try:
+            set_up(client_mgr, members)
+            client_mgr.register(inspector)
+
+            ledger_run = client_mgr.run_until_complete()
+            return ledger_run.exit_code
+        finally:
+            inspector.dump_all()
+
+def set_up(client_mgr, members):
+    postman_client = client_mgr.new_client(POSTMAN_PARTY)
+    postman_client.on_ready(
+        lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY)))
+    postman_client.on_created(
+        'Main.PostmanRole',
+        lambda cid, cdata: [cid.exercise('InviteParticipant', m) for m in members])
+
+def address(index):
+    return '{} Member Lane'.format(index)
+
+
+

The on_created method allows you to add an event handler for templates as they are created on +the ledger. Like the on_ready method above, you can return a Command (or in this case, a +list of Command) that is to be executed in response to this event.

+

After running the script, you should see a few more columns in the output for all the new parties, +and you can see that the parties now see invitation contracts that they can exercise choices on. To +further progress the workflow, let’s add more callbacks in set_up:

+
def set_up(client_mgr, members):
+    postman_client = client_mgr.new_client(POSTMAN_PARTY)
+    postman_client.on_ready(
+        lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY)))
+    postman_client.on_created(
+        'Main.PostmanRole',
+        lambda cid, cdata: [cid.exercise('InviteParticipant', m) for m in members])
+
+    member_clients = [client_mgr.new_client(m['party']) for m in members]
+    for member_client in member_clients:
+        # every member automatically accepts
+        member_client.on_created(
+            'Main.InviteAuthorRole', lambda cid, cdata: cid.exercise('AcceptInviteAuthorRole'))
+        member_client.on_created(
+            'Main.InviteReceiverRole', lambda cid, cdata: cid.exercise('AcceptInviteReceiverRole'))
+
+
+

Now notice that the inviteAsAuthor and inviteAsReceiver contracts are no longer in the +output, instead replaced with authorRole and receiverRole contracts; that’s because the +accept choice on these contracts is a consuming choice.

+

In order to respond to these contracts as other parties, we have also created new clients, one for +every additional party. Now that we have a universe of participants fully set up and ready to go, +let’s do some actual work.

+
+
+

Send some “letters” through the post office

+

Once a participant’s Main.authorRole is created, that participant is now granted the ability to +send letters to other participants in the market.

+

– TBC –

+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/tutorials_workflow_state.html b/docs/tutorials_workflow_state.html new file mode 100644 index 00000000..ddc9138a --- /dev/null +++ b/docs/tutorials_workflow_state.html @@ -0,0 +1,605 @@ + + + + + + + + Workflow State Example + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +
+

Workflow State Example

+

The purpose of this example is to demonstrate a multi-contract-creation dependency use-case: a sitution where the application must wait for multiple contracts to be created before it can proceed to the next step. This is similar to the “Message Ingester” sample application, but with the key difference that the state transitions in the “Message Ingester” workflow each depend solely on a single contract creation.

+

The workflow involving three parties: Alice, Bob, and Operator. When writing a DAML +application, we recommend the following steps:

+
+
    +
  1. Describe your workflow as a series of contracts in DAML.

  2. +
  3. Write one or more DAML test scenarios that walk through each step of the workflow, starting from creation of the genesis contract, through a sequence of exercise commands, to the final state of the workflow. (Note: The DAML test scenarios are used for verifying the steps of the workflow in a sequential manner. However, when the workflow is deployed to a live platflorm, the events that prompt steps in the workflow to move forward cannot be assumed to occur sequentially.)

  4. +
  5. Write your application.

  6. +
  7. Test your application on the sandbox. The ledger server implements the same API, so performance testing can be done with the same application.

  8. +
+
+

The workflow for this application is as follows:

+
    +
  1. The GenesisContract, is created. It describes the operation(s) that the operator of this workflow can perform. In this example, we have assigned the party name Operator to the GenesisContract.

  2. +
  3. Operator invites the Bob to be the ticket seller, and also invites Alice to be the ticket buyer.

  4. +
  5. Only after BOTH Alice and Bob have accepted their respective invitations can the workflow progress to the next state (TicketTransactionsInProgress)

  6. +
  7. A ticket transaction occurs.

  8. +
  9. The workflow is completed.

  10. +
+
+

DAML Model

+

WorkflowStateExample.daml

+
daml 1.0
+module WorkflowStateExample where
+
+-- The "Workflow State Contract" Best Practice.
+-- 
+-- Purpose: To encapsulate the state of a workflow within a contract. This results in easier 
+-- development & debugging because workflow milestones are clearly defined 
+
+template GenesisContract
+  with
+    operator: Party
+  where
+    signatory operator
+
+    controller operator can
+      anytime SetInitialWorkflowState
+        returning ContractId WorkflowSetupInProgress
+        to create WorkflowSetupInProgress with operator=operator
+      anytime InviteTicketBuyer with ticketBuyer: Party
+        returning ContractId TicketBuyerInvitation
+        to do
+          create TicketBuyerInvitation with operator; ticketBuyer;
+      anytime InviteTicketSeller with ticketSeller: Party
+        returning ContractId TicketSellerInvitation
+        to create TicketSellerInvitation with operator; ticketSeller;
+
+template TicketBuyerInvitation
+  with
+    operator: Party
+    ticketBuyer: Party
+  where
+    signatory operator
+
+    controller ticketBuyer can
+      AcceptTicketBuyerInvitation
+        returning ContractId TicketBuyerRole
+        to create TicketBuyerRole with ticketBuyer; operator;
+ 
+template TicketBuyerRole
+  with
+    ticketBuyer: Party
+    operator: Party
+  where
+    signatory ticketBuyer
+
+template TicketSellerInvitation
+  with
+    operator: Party
+    ticketSeller: Party
+  where
+    signatory operator
+
+    controller ticketSeller can
+      AcceptTicketSellerInvitation
+        returning ContractId TicketSellerRole
+        to create TicketSellerRole with ticketSeller; operator;
+
+template TicketSellerRole
+  with 
+    ticketSeller: Party
+    operator: Party
+  where
+    signatory ticketSeller
+
+    controller ticketSeller can
+      anytime OfferTicketPurchaseAgreement with ticketBuyer: Party
+        returning ContractId TicketPurchaseAgreementOffer 
+        to create TicketPurchaseAgreementOffer with ticketSeller; ticketBuyer; operator;
+
+template TicketPurchaseAgreementOffer
+  with
+    ticketSeller: Party
+    ticketBuyer: Party
+    operator: Party
+  where
+    signatory ticketSeller
+
+    controller ticketBuyer can
+      PurchaseTicket
+        returning ContractId TicketPurchaseAgreement
+        to create TicketPurchaseAgreement with ticketSeller; ticketBuyer; operator;
+
+template TicketPurchaseAgreement
+  with
+    ticketSeller: Party
+    ticketBuyer: Party
+    operator: Party
+
+  where
+    signatory ticketSeller
+    signatory ticketBuyer
+    agreement toText ticketBuyer <> " agrees to purchase ticket from " <> toText ticketSeller 
+
+-- Workflow state 1 of 3
+template WorkflowSetupInProgress
+  with
+    operator: Party
+  where
+    signatory operator
+
+    controller operator can
+      TicketTransactionsInProgress
+        returning ContractId WorkflowTicketTransactionsInProgress
+        to create WorkflowTicketTransactionsInProgress with operator
+
+-- Workflow state 2 of 3
+template WorkflowTicketTransactionsInProgress
+  with 
+    operator: Party
+  where
+    signatory operator
+
+    controller operator can
+      WorkflowCompleted
+        returning ContractId WorkflowCompleted
+        to create WorkflowCompleted with operator
+
+-- Workflow state 3 of 3
+template WorkflowCompleted
+  with 
+    operator: Party
+  where
+    signatory operator
+
+test ticketTransactionTest = 
+  scenario
+    -- create the genesis contract
+    genesisContract <- 'Operator' commits create GenesisContract with operator='Operator'
+    -- set the initial workflow state (InviteParticipantsInProgress)
+    workflowSetupInProgress <- 'Operator' commits exercise genesisContract SetInitialWorkflowState
+
+    -- initial state: InviteParticipantsInProgress
+    -- operator shall invite all the participants to the workflow, and respective participant role contracts 
+    -- shall be created
+
+    -- note: scenarios list actions in series, but these actions do not have a guaranteed order when running on the Platform 
+
+    ticketSellerInvitation <- 'Operator' commits exercise genesisContract InviteTicketSeller with ticketSeller='Bob'
+    ticketSellerRole <- 'Bob' commits exercise ticketSellerInvitation AcceptTicketSellerInvitation
+
+    ticketBuyerInvitation <- 'Operator' commits exercise genesisContract InviteTicketBuyer with ticketBuyer='Alice'
+    ticketBuyerRole <- 'Alice' commits exercise ticketBuyerInvitation AcceptTicketBuyerInvitation
+    
+    -- next state: TicketTransactionsInProgress
+    -- the application must detect when this state transition can occur, and then perform this exercise
+    workflowTicketTransactionsInProgress <- 'Operator' commits exercise workflowSetupInProgress TicketTransactionsInProgress
+
+    -- In this phase of the workflow, one or more ticket purchases may occur
+
+    -- a ticket is purchsed
+    offerTicketPurchaseAgreement <- 'Bob' commits exercise ticketSellerRole OfferTicketPurchaseAgreement with ticketBuyer='Alice'
+    'Alice' commits exercise offerTicketPurchaseAgreement PurchaseTicket
+
+    -- ...more ticket purchases may occur here
+    
+    -- next state: WorkflowCompleted
+    -- the application must detect when this state transition shall occur, and then perform this exercise
+    workflowCompleted <- 'Operator' commits exercise workflowTicketTransactionsInProgress WorkflowCompleted
+
+    return {
+      genesisContract=genesisContract;
+      ticketBuyerInvitation=ticketBuyerInvitation;
+      ticketBuyerRole=ticketBuyerRole;
+      ticketSellerInvitation=ticketSellerInvitation;
+      ticketSellerRole=ticketSellerRole;
+      workflowCompleted=workflowCompleted;
+    }
+
+
+

The ticketTransactionTest scenario describes a sample execution of the workflow, and is the basis from from which +our Python application will be designed.

+
+
+

Python Application

+

store.py

+
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+import asyncio
+import logging
+
+LOG = logging.getLogger('store')
+
+
+class ContractStore:
+    def __init__(self, loop=None, verbose=False):
+        self.verbose = verbose
+        self.binds = dict()
+        self.loop = loop or asyncio.get_event_loop()
+
+    def save(self, name, cid, cdata):
+        if self.verbose:
+            LOG.critical('Saving %s %s %s', name, cid, cdata)
+        name = self._resolve_name(name)
+        future = self.binds.get(name)
+        if future is None or future.done():
+            future = self.loop.create_future()
+            self.binds[name] = future
+        future.set_result((cid, cdata))
+
+    def find(self, name):
+        """
+        Find the contract under the given name.
+
+        :param name: The "name" of the contract.
+        :return: A ``Future`` that resolves to a (cid, cdata) tuple.
+        """
+        if self.verbose:
+            LOG.critical('Finding in store %s', name)
+        else:
+            LOG.info('Finding in store %s', name)
+        name = self._resolve_name(name)
+        future = self.binds.get(name)
+        if future is None:
+            future = self.loop.create_future()
+            self.binds[name] = future
+        return future
+
+    def delete(self, name):
+        if self.verbose:
+            LOG.critical('Deleting from store %s', name)
+        name = self._resolve_name(name)
+        future = self.binds.get(name)
+        if future is not None:
+            future.cancel()
+            del self.binds[name]
+
+    def archive(self, cid):
+        """
+        Mark the contract as archived.
+
+        :param cid: The contract ID that is no longer active.
+        """
+        for key, future in self.binds.items():
+            if future.done():
+                if future.result() == cid:
+                    del self.binds[key]
+
+    def _resolve_name(self, name):
+        if isinstance(name, list):
+            return '_'.join(name)
+        return name
+
+    def match(self, is_match):
+        xs = []
+        for key, future in self.binds.items():
+            cid, value = future.result()
+            if is_match(key, cid, value):
+                xs.append((key, cid, value))
+        return xs
+
+
+

workflow_state_example.py

+
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+from dazl import create, exercise
+from dazl.client import create_client
+from dazl.plugins import LedgerCapturePlugin
+from store import ContractStore
+import subprocess
+
+operator = 'Operator'
+alice = 'Alice'
+bob = 'Bob'
+
+parties = [operator,alice,bob]
+url = 'http://localhost:7600/'
+contract_store = ContractStore()
+transaction_limit = 1
+
+
+def create_initial_workflow_state(cid, cdata):
+    workflow_state = [ exercise(cid, 'SetInitialWorkflowState', {})]
+    return workflow_state
+
+def invite_ticket_seller(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_seller_invitation = [ exercise(cid, 'InviteTicketSeller', {'ticketSeller': bob})]
+    return ticket_seller_invitation
+
+def invite_ticket_buyer(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_buyer_invitation = [ exercise(cid, 'InviteTicketBuyer', {'ticketBuyer': alice})]
+    return ticket_buyer_invitation
+
+# DOC_BEGIN: FUNCTION_ACCEPT_INVITE
+def accept_ticket_seller_invite(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_seller_role = [ exercise(cid, 'AcceptTicketSellerInvitation', {})]
+    contract_store.save('ticketSellerRole1', cid, cdata)
+    return ticket_seller_role
+
+def accept_ticket_buyer_invite(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_buyer_role = [ exercise(cid, 'AcceptTicketBuyerInvitation', {})]
+    contract_store.save('ticketBuyerRole1', cid, cdata)
+    return ticket_buyer_role
+# DOC_END: FUNCTION_ACCEPT_INVITE
+
+# DOC_BEGIN: FUNCTION_MULTI_CREATION_DEPENDENCY
+async def transition_to_ticket_transactions_in_progress(cid, cdata):
+    await contract_store.find('ticketSellerRole1')
+    await contract_store.find('ticketBuyerRole1')
+    workflow_ticket_transactions_in_progress = [ exercise(cid, 'TicketTransactionsInProgress', {})]
+    contract_store.save('workflowTicketTransactionsInProgress', cid, cdata)
+    return workflow_ticket_transactions_in_progress
+# DOC_END: FUNCTION_MULTI_CREATION_DEPENDENCY
+
+async def offer_ticket_purchase_agreement(cid, cdata):
+    '''Workflow state: WorkflowTicketTransactionsInProgress'''
+    await contract_store.find('workflowTicketTransactionsInProgress')
+    offer_ticket_purchase_agreement = [exercise(cid, 'OfferTicketPurchaseAgreement', {'ticketBuyer': alice})]
+    global transaction_limit
+    if transaction_limit > 0:
+        transaction_limit -= 1
+        return offer_ticket_purchase_agreement
+
+def purchase_ticket(cid, cdata):
+    '''Workflow state: WorkflowTicketTransactionsInProgress'''
+    ticket_purchase_agreement = [exercise(cid, 'PurchaseTicket', {})]
+    return ticket_purchase_agreement
+
+def save_purchase_agreement(cid, cdata):
+    '''Workflow state: WorkflowTicketTransactionsInProgress'''
+    contract_store.save('purchase_agreement', cid, cdata)
+
+async def transition_to_workflow_completed(cid, cdata):
+    await contract_store.find('purchase_agreement')
+    #move on to the next phase of the workflow after 1 purchase agreement has been created
+    workflow_completed =[exercise(cid, 'WorkflowCompleted', {})]
+    return workflow_completed
+
+def register_event_handlers(client_mgr):
+    '''
+    Register event handlers with the appropriate clients.
+    '''
+
+    # initial workflow state (1 of 3): "InviteParticipantsInProgress"
+
+    # Define a ledger client associated with the 'Operator' party, and how it reacts to events
+    operator_client = client_mgr.new_client('Operator')
+    operator_client.on_created('WorkflowStateExample.GenesisContract', create_initial_workflow_state)
+    operator_client.on_created('WorkflowStateExample.GenesisContract', invite_ticket_seller)
+    operator_client.on_created('WorkflowStateExample.GenesisContract', invite_ticket_buyer)
+
+    # define a ledger client associated with the ticket seller, and how it reacts to events
+    bob_client = client_mgr.new_client(bob)
+    bob_client.on_created('WorkflowStateExample.TicketSellerInvitation', accept_ticket_seller_invite)
+
+    # define a ledger client associated with the ticket buyer, and how it reacts to events
+    alice_client = client_mgr.new_client(alice)
+    alice_client.on_created('WorkflowStateExample.TicketBuyerInvitation', accept_ticket_buyer_invite)
+
+    # transition to workflow state: "TicketTransactionsInProgress"
+    operator_client.on_created('WorkflowStateExample.WorkflowSetupInProgress', transition_to_ticket_transactions_in_progress)
+
+    # workflow state (2 of 3): "TicketTransactionsInProgress"
+    bob_client.on_created('WorkflowStateExample.TicketSellerRole', offer_ticket_purchase_agreement)
+
+    # alice purchases a ticket
+    alice_client.on_created('WorkflowStateExample.TicketPurchaseAgreementOffer', purchase_ticket)
+    alice_client.on_created('WorkflowStateExample.TicketPurchaseAgreement', save_purchase_agreement)
+
+    # transition to workflow state (3 of 3): "WorkflowCompleted"
+    operator_client.on_created('WorkflowStateExample.WorkflowTicketTransactionsInProgress', transition_to_workflow_completed)
+
+    # all event handlers are defined; create the genesis contract, and all other event handlers shall react thereafter
+    operator_client.submit([create('WorkflowStateExample.GenesisContract', { 'operator' : 'Operator' })])
+
+def run():
+
+    with create_client(parties=parties, participant_url=url) as client_mgr:
+        inspector = LedgerCapturePlugin.stdout()
+        try:
+            client_mgr.register(inspector)
+            register_event_handlers(client_mgr)
+            ledger_run = client_mgr.run_until_complete()
+            return ledger_run.exit_code
+        finally:
+            inspector.dump_all()
+            subprocess.Popen(['da', 'stop']).wait()
+
+if __name__ == "__main__":
+    subprocess.Popen(['da', 'sandbox']).wait()
+    run()
+
+
+
+
+
To run this code sample:
    +
  1. Download the SDK

  2. +
  3. create a new project: da new my-project-name-here

  4. +
  5. cd my-project-name-here

  6. +
  7. Create a file, WorkflowStateExample.daml, that contains the above listed DAML.

  8. +
  9. Create a file, workflow_state_sample.py, that contains the Python code for “workflow_state_example.py” listed above.

  10. +
  11. Create a file, store.py, that contains, that contains the Python code for “store.py” listed above.

  12. +
  13. Download the dazl-starter template (which also creates a Python venv): da project add dazl-starter

  14. +
  15. Run the application: ./venv/bin/python3 workflow_state_example.py

  16. +
+
+
+

accept_ticket_seller_invite() and accept_ticket_buyer_invite() store their respective contracts into contract_store. This is the first step in setting up a multi-contract-creation dependency.

+
def accept_ticket_seller_invite(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_seller_role = [ exercise(cid, 'AcceptTicketSellerInvitation', {})]
+    contract_store.save('ticketSellerRole1', cid, cdata)
+    return ticket_seller_role
+
+def accept_ticket_buyer_invite(cid, cdata):
+    '''Workflow state: WorkflowSetupInProgress'''
+    ticket_buyer_role = [ exercise(cid, 'AcceptTicketBuyerInvitation', {})]
+    contract_store.save('ticketBuyerRole1', cid, cdata)
+    return ticket_buyer_role
+
+
+

transition_to_ticket_transactions_in_progress() performs lookups into contract_store. These lookups will wait until the specified contract keys are present in the contract_store, and only perform the exercise command after that point. Thus, BOTH the TicketSellerRole and the TicketBuyerRole must be created before the application can transition to the next step in the workflow.

+
async def transition_to_ticket_transactions_in_progress(cid, cdata):
+    await contract_store.find('ticketSellerRole1')
+    await contract_store.find('ticketBuyerRole1')
+    workflow_ticket_transactions_in_progress = [ exercise(cid, 'TicketTransactionsInProgress', {})]
+    contract_store.save('workflowTicketTransactionsInProgress', cid, cdata)
+    return workflow_ticket_transactions_in_progress
+
+
+
+
+

Application Output

+

This application will produce this output:

+
[Info] Starting:
+    Sandbox ledger server
+    .../daml/WorkflowStateExample.daml
+    with no scenario and binding to port 7600
+Waiting for Sandbox...ok
+5 total contracts over 5 templates
++-- party 'Alice' (block heights 2 to 9)
+|+- party 'Bob' (block heights 2 to 9)
+||+ party 'Operator' (block heights 1 to 9)
+|||
+
+WorkflowStateExample.GenesisContract (1 contract) ----------------------------------------------------------------------
+    #cid operator
+  C 0:0_ Operator
+
+WorkflowStateExample.TicketBuyerRole (1 contract) ----------------------------------------------------------------------
+    #cid operator ticketBuyer
+C   2:2_ Operator Alice
+
+WorkflowStateExample.TicketPurchaseAgreement (1 contract) --------------------------------------------------------------
+    #cid operator ticketBuyer ticketSeller
+CC  6:2_ Operator Alice       Bob
+
+WorkflowStateExample.TicketSellerRole (1 contract) ---------------------------------------------------------------------
+    #cid operator ticketSeller
+ C  3:2_ Operator Bob
+
+WorkflowStateExample.WorkflowCompleted (1 contract) --------------------------------------------------------------------
+    #cid operator
+  C 7:2_ Operator
+stopping... Sandbox ledger server
+.../daml/WorkflowStateExample.daml
+with no scenario and binding to port 7600
+
+Process finished with exit code 0
+
+
+

Thus, a TicketPurchaseAgreement is created. Also note that the contracts representing intermediate steps in the workflow (WorkflowSetupInProgress, and WorkflowTicketTransactionsInProgress) were created and then subsequently archived. Only the contract representing the final state, WorkflowCompleted is active.

+
+
+ + +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file From b0375c91e7d9990c66a8c00c253f7b0ccd1cbf33 Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Wed, 28 Aug 2019 16:10:51 +0200 Subject: [PATCH 3/7] Update readme/landing page. Fixes #43. Examples in the README should now compile. Updated info on build environment (poetry instead of pipenv). --- docs/_sources/index.rst.txt | 41 ++++++++++--------------- docs/index.html | 45 +++++++++++---------------- docs/searchindex.js | 2 +- python/README.md | 61 ++++++++++++++++++++++--------------- python/docs/index.rst | 41 ++++++++++--------------- 5 files changed, 87 insertions(+), 103 deletions(-) diff --git a/docs/_sources/index.rst.txt b/docs/_sources/index.rst.txt index ef572167..3185d001 100644 --- a/docs/_sources/index.rst.txt +++ b/docs/_sources/index.rst.txt @@ -7,22 +7,22 @@ Dependencies ------------ You will need Python 3.6 or later and a Digital Asset ledger implementation (DA Sandbox or -DA Ledger Server). :term:`dazl` additionally requires the following libraries to be -installed: +DA Ledger Server). + +Build-time dependencies are handled using `Poetry `_. -* grpcio, version 1.18.0 or later -* PyYAML -* semver Getting Started --------------- -This section assumes that you already have a running ledger with a DAML model loaded. +This section assumes that you already have a running ledger with the standard `daml new` model loaded, and have imported `dazl`. Connect to the ledger and submit a single command:: - with dazl.simple_client('http://localhost:7600', 'Alice') as client: - client.submit_create('Alice', 'My.Template', { someField: 'someText' }) + with dazl.simple_client('http://localhost:6865', 'Alice') as client: + contract = { 'issuer' : 'Alice', 'owner' : 'Alice', 'name' : 'hello world!' } + client.ready() + client.submit_create('Main.Asset', contract) Connect to the ledger as a single party, print all contracts, and close:: @@ -32,29 +32,20 @@ Connect to the ledger as a single party, print all contracts, and close:: contract_dict = client.find_active('*') print(contract_dict) -Connect to the ledger as multiple parties:: +Connect to the ledger using asynchronous callbacks:: + from dazl.model.reading import ReadyEvent network = dazl.Network() - network.set_config(url='http://localhost:7600') + network.set_config(url='http://localhost:6865') - alice = network.simple_party('Alice') - bob = network.simple_party('Bob') + alice = network.aio_party('Alice') @alice.ledger_ready() - def set_up(event): - currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"}) - return dazl.create('SomethingOf.Value', { - 'amount': 100, - 'currency': currency_cid, - 'from': 'Accept', - 'to': 'Bob' }) - - @bob.ledger_created('SomethingOf.Value') - def on_something_of_value(event): - return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' }) - - network.start() + async def onReady(event: ReadyEvent): + contracts = await event.acs_find_one('Main.Asset') + print(contracts) + network.run_until_complete() Table of Contents ----------------- diff --git a/docs/index.html b/docs/index.html index 9359d0aa..b61fa993 100644 --- a/docs/index.html +++ b/docs/index.html @@ -71,20 +71,17 @@

dazl: DA client library for Python

Dependencies

You will need Python 3.6 or later and a Digital Asset ledger implementation (DA Sandbox or -DA Ledger Server). dazl additionally requires the following libraries to be -installed:

-
    -
  • grpcio, version 1.18.0 or later

  • -
  • PyYAML

  • -
  • semver

  • -
+DA Ledger Server).

+

Build-time dependencies are handled using Poetry.

Getting Started

-

This section assumes that you already have a running ledger with a DAML model loaded.

+

This section assumes that you already have a running ledger with the standard daml new model loaded, and have imported dazl.

Connect to the ledger and submit a single command:

-
with dazl.simple_client('http://localhost:7600', 'Alice') as client:
-    client.submit_create('Alice', 'My.Template', { someField: 'someText' })
+
with dazl.simple_client('http://localhost:6865', 'Alice') as client:
+    contract = { 'issuer' : 'Alice', 'owner' : 'Alice', 'name' : 'hello world!' }
+    client.ready()
+    client.submit_create('Main.Asset', contract)
 

Connect to the ledger as a single party, print all contracts, and close:

@@ -95,27 +92,19 @@

Getting Startedprint(contract_dict)

-

Connect to the ledger as multiple parties:

-
network = dazl.Network()
-network.set_config(url='http://localhost:7600')
+

Connect to the ledger using asynchronous callbacks:

+
from dazl.model.reading import ReadyEvent
+network = dazl.Network()
+network.set_config(url='http://localhost:6865')
 
-alice = network.simple_party('Alice')
-bob = network.simple_party('Bob')
+alice = network.aio_party('Alice')
 
 @alice.ledger_ready()
-def set_up(event):
-    currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"})
-    return dazl.create('SomethingOf.Value', {
-        'amount': 100,
-        'currency': currency_cid,
-        'from': 'Accept',
-        'to': 'Bob' })
-
-@bob.ledger_created('SomethingOf.Value')
-def on_something_of_value(event):
-    return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' })
-
-network.start()
+async def onReady(event: ReadyEvent):
+  contracts = await event.acs_find_one('Main.Asset')
+  print(contracts)
+
+network.run_until_complete()
 
diff --git a/docs/searchindex.js b/docs/searchindex.js index f620a033..49799c65 100644 --- a/docs/searchindex.js +++ b/docs/searchindex.js @@ -1 +1 @@ -Search.setIndex({docnames:["basics","dazl","dazl.cli","dazl.client","dazl.damlast","dazl.damlsdk","dazl.model","dazl.pretty","dazl.protocols","dazl.util","glossary","index","migrating","tutorials","tutorials_message_ingester","tutorials_post_office","tutorials_workflow_state"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["basics.rst","dazl.rst","dazl.cli.rst","dazl.client.rst","dazl.damlast.rst","dazl.damlsdk.rst","dazl.model.rst","dazl.pretty.rst","dazl.protocols.rst","dazl.util.rst","glossary.rst","index.rst","migrating.rst","tutorials.rst","tutorials_message_ingester.rst","tutorials_post_office.rst","tutorials_workflow_state.rst"],objects:{"":{dazl:[1,0,0,"-"]},"dazl.cli":{ls:[2,0,0,"-"],main:[2,4,1,""],print_cmd_help:[2,4,1,""],run:[2,4,1,""]},"dazl.cli.ls":{ListAllCommand:[2,1,1,""]},"dazl.cli.ls.ListAllCommand":{execute:[2,2,1,""],name:[2,3,1,""],parser:[2,2,1,""]},"dazl.client":{api:[3,0,0,"-"],bots:[3,0,0,"-"]},"dazl.client.api":{AIOGlobalClient:[3,1,1,""],AIOPartyClient:[3,1,1,""],GlobalClient:[3,1,1,""],Network:[3,1,1,""],PartyClient:[3,1,1,""],SimpleGlobalClient:[3,1,1,""],SimplePartyClient:[3,1,1,""],simple_client:[3,4,1,""]},"dazl.client.api.AIOGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.AIOPartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.api.Network":{aio_global:[3,2,1,""],aio_party:[3,2,1,""],aio_run:[3,2,1,""],bots:[3,2,1,""],join:[3,2,1,""],parties:[3,2,1,""],party_bots:[3,2,1,""],resolved_config:[3,2,1,""],run_forever:[3,2,1,""],run_until_complete:[3,2,1,""],set_config:[3,2,1,""],shutdown:[3,2,1,""],simple_global:[3,2,1,""],simple_party:[3,2,1,""],start_in_background:[3,2,1,""]},"dazl.client.api.PartyClient":{party:[3,2,1,""],resolved_config:[3,2,1,""]},"dazl.client.api.SimpleGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.SimplePartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.bots":{Bot:[3,1,1,""],BotCollection:[3,1,1,""],BotEntry:[3,1,1,""],BotInvocation:[3,1,1,""],BotState:[3,1,1,""],wrap_as_command_submission:[3,4,1,""]},"dazl.client.bots.Bot":{add_event_handler:[3,2,1,""],entries:[3,2,1,""],event_keys:[3,2,1,""],id:[3,2,1,""],ledger_created:[3,2,1,""],name:[3,2,1,""],notify:[3,2,1,""],party:[3,2,1,""],pause:[3,2,1,""],resume:[3,2,1,""],running:[3,2,1,""],state:[3,2,1,""],stop:[3,2,1,""],wants_any_keys:[3,2,1,""]},"dazl.client.bots.BotCollection":{add_new:[3,2,1,""],add_single:[3,2,1,""],notify:[3,2,1,""],stop_all:[3,2,1,""]},"dazl.client.bots.BotEntry":{filter:[3,3,1,""],source_location:[3,3,1,""]},"dazl.client.bots.BotState":{PAUSED:[3,3,1,""],PAUSING:[3,3,1,""],RESUMING:[3,3,1,""],RUNNING:[3,3,1,""],STARTING:[3,3,1,""],STOPPED:[3,3,1,""],STOPPING:[3,3,1,""]},"dazl.model":{core:[6,0,0,"-"],ledger:[6,0,0,"-"],reading:[6,0,0,"-"],types:[6,0,0,"-"],types_store:[6,0,0,"-"],writing:[6,0,0,"-"]},"dazl.model.core":{ContractId:[6,1,1,""]},"dazl.model.core.ContractId":{contract_id:[6,3,1,""],exercise:[6,2,1,""],for_json:[6,2,1,""],replace:[6,2,1,""],template_id:[6,3,1,""]},"dazl.model.types":{ListType:[6,1,1,""],RecordType:[6,1,1,""],ScalarType:[6,1,1,""],Type:[6,1,1,""],UnsupportedType:[6,1,1,""],VariantType:[6,1,1,""]},"dazl.model.writing":{Command:[6,1,1,""],CreateCommand:[6,1,1,""],ExerciseCommand:[6,1,1,""]},"dazl.model.writing.CreateCommand":{arguments:[6,3,1,""],replace:[6,2,1,""],template:[6,3,1,""]},"dazl.model.writing.ExerciseCommand":{arguments:[6,3,1,""],choice:[6,3,1,""],contract:[6,3,1,""],replace:[6,2,1,""]},"dazl.pretty":{get_pretty_printer:[7,4,1,""],render_daml:[7,0,0,"-"],util:[7,0,0,"-"]},"dazl.protocols":{v0:[8,0,0,"-"],v1:[8,0,0,"-"]},dazl:{cli:[2,0,0,"-"],client:[3,0,0,"-"],damlast:[4,0,0,"-"],damlsdk:[5,0,0,"-"],model:[6,0,0,"-"],pretty:[7,0,0,"-"],protocols:[8,0,0,"-"],util:[9,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"],"3":["py","attribute","Python attribute"],"4":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method","3":"py:attribute","4":"py:function"},terms:{"00z":14,"01t00":14,"byte":3,"case":[3,14,15,16],"class":[2,3,6,15,16],"default":3,"enum":3,"final":[14,15,16],"float":3,"function":[3,5,9,14,15],"import":[6,14,15,16],"int":[0,2,3,6,15],"long":3,"new":[3,6,12,14,15,16],"public":3,"return":[3,6,11,14,15,16],"throw":3,"true":3,"try":[3,14,15,16],"while":3,ACS:[3,11],AND:3,But:15,For:[3,14,15],IDs:[3,6],NOT:3,That:14,The:[0,3,6,10,14,15,16],Then:15,There:[6,15],These:16,Use:3,Using:15,__file__:15,__init__:16,__main__:[14,15,16],__name__:[14,15,16],_asyncio:3,_base:2,_before_:3,_main:3,_network_client_impl:3,_networkimpl:3,_or_:3,_party_client_impl:3,_partyclientimpl:3,_render_bas:7,_resolve_nam:16,_run_level:3,abil:15,abl:3,about:[3,12],abov:[14,15,16],abstractset:3,accept:[11,15,16],accept_message_act:14,accept_the_messag:14,accept_ticket_buyer_invit:16,accept_ticket_seller_invit:16,acceptinviteauthorrol:15,acceptinvitereceiverrol:15,acceptlett:15,acceptmessag:14,acceptsentlett:15,acceptticketbuyerinvit:16,acceptticketsellerinvit:16,access:12,acknowledg:14,acknowledge_message_act:14,acknowledge_the_messag:14,acknowledgingparti:14,acknowlegedlett:15,across:12,acs_find_on:11,action:16,activ:[3,12,14,16],actual:15,add:[3,14,15,16],add_event_handl:3,add_ledger_archiv:[3,12],add_ledger_cr:[3,12],add_ledger_exercis:3,add_ledger_init:[3,12],add_ledger_packages_ad:3,add_ledger_readi:[3,12],add_ledger_transaction_end:3,add_ledger_transaction_start:3,add_new:3,add_singl:3,added:[3,15],adding:[3,15],addit:[3,6,12,15],addition:11,address:15,adject:6,admin_url:3,advanc:3,affili:[14,16],after:[3,14,15,16],afterward:15,against:[3,15],agre:16,agreement:[15,16],aid:6,aio_glob:3,aio_parti:[3,12],aio_run:3,aioglobalcli:3,aiopartycli:3,alic:[11,12,14,16],alice_cli:[12,14,16],all:[3,6,11,14,15,16],all_parti:15,allow:[3,15],alongsid:3,alreadi:[3,11],also:[3,14,15,16],altern:3,alwai:[6,15],amount:[3,11],ani:[3,6],anyth:[3,15],anytim:16,apach:[14,16],api:[1,6,11,12,14,16],append:16,appli:[3,6],applic:[3,11,13],appropri:16,arbitrari:3,archiv:[3,11,14,16],arg:2,argpars:2,argument:[3,6,12,15],argumentpars:2,aris:6,around:5,arrai:3,assert:15,asset:[10,11,12,14,16],assign:[14,16],assist:5,associ:[3,14,16],assum:[6,11,14,15,16],async:[3,16],asynchron:3,asyncio:[3,12,16],attribut:6,author:15,authorrol:15,automat:15,await:[3,11,16],background:[3,15],base:[2,3,6,12],baseev:3,basi:[14,16],basic:11,becaus:[15,16],been:[3,12,16],befor:[3,6,15,16],begin:3,behalf:3,behavior:[3,6],being:[3,6],below:0,best:16,bin:[14,16],binaryio:3,bind:16,bit:15,blank:15,block:[3,14,15,16],bob:[11,12,14,16],bob_client:[12,14,16],bodi:15,bool:[0,3,6],bot:[1,11],botcallback:3,botcollect:3,botentri:3,botfilt:3,both:[6,16],botinvoc:3,botstat:3,builtin:6,buyer:16,calcul:3,calculaterequest:0,calculaterespons:0,call:[3,12,14,15],callabl:3,callback:[3,14,15],caller:3,can:[3,6,14,15,16],cancel:16,cannot:[3,14,16],caught:3,caus:14,cdata:[12,14,15,16],certain:14,chang:[3,12],check:3,choic:[3,6,14,15],choice_argu:3,choice_nam:[3,6],choicemetadata:6,choiceref:6,cid:[3,11,12,14,15,16],clearli:16,cli:[1,11],clicommand:2,client:[1,6,8,10,12,14,15,16],client_mgr:[14,15,16],close:11,cmd:2,code:[3,6,14,15,16],coerc:3,coercion:6,collaps:12,collect:3,column:15,comfort:3,command:[2,3,6,11,14,15,16],commandbuild:3,commandpayload:3,commit:[14,16],common:3,commun:3,complet:[3,16],composit:6,comput:0,config:3,configur:[3,14],connect:[3,11,14,15],consist:12,construct:6,constructor:[0,6],consum:[14,15],contain:[0,1,3,6,7,8,12,14,16],content:15,contextmanag:3,contextu:3,contract:[3,6,11,12,14,15,16],contract_dict:11,contract_id:6,contract_kei:3,contract_stor:16,contractarchiveev:3,contractcontextualdata:3,contractcontextualdatacollect:3,contractcreateev:3,contractexercisedev:3,contractid:[0,3,6,14,15,16],contractstor:16,control:[14,15,16],conveni:[3,15],convent:12,convert:3,copyright:[14,16],core:[0,1,3,11],coroutin:3,correct:3,correspond:[3,14],could:15,cours:14,creat:[3,6,11,13,14,16],create_and_exercis:3,create_cli:[12,14,15,16],create_futur:16,create_if_miss:3,create_initial_workflow_st:16,createa:14,createcommand:6,createdecimallett:15,createintlett:15,createlett:15,createlistintlett:15,createtimelett:15,creation:[14,16],critic:16,ctrl:3,currenc:11,currency_cid:11,current:[3,6],custom:14,daemon:3,dalf:3,damast:[1,11],daml:[0,5,6,11,13],daml_fil:15,daml_ledger_parti:3,daml_ledger_url:3,damlsdk:[1,11],dar:3,data:[0,3,12],date:[0,3],datetim:[0,3],dazl:[0,10,12,14,15,16],deactiv:15,debug:16,decim:[0,3,6,15],declar:3,decor:3,def:[11,14,15,16],defin:[6,14,15,16],del:16,delet:16,deliv:15,demonstr:16,depend:16,deploi:[14,16],describ:[6,14,16],descript:6,design:[14,16],detect:[3,14,16],develop:[15,16],dict:[0,3,6,15,16],dictionari:[0,3],differ:[8,16],difficult:15,digit:[10,11,14,16],directli:[3,6],dirnam:15,disabl:3,disambigu:6,dish:15,dispatch:3,dispos:15,doc_begin:[14,16],doc_end:[14,16],doe:3,domain:6,don:6,done:[3,14,16],down:[3,15],download:[14,16],drain:3,drawn:15,dump_al:[14,15,16],dure:14,each:[14,15,16],easier:16,easili:15,either:[3,6,15],els:[15,16],empti:0,encapsul:16,encount:3,ensur:3,ensure_dar:3,ensure_packag:3,entir:3,entri:3,environ:3,equival:3,error:3,even:15,event:[3,6,11,14,15,16],event_kei:3,eventkei:3,eventu:6,ever:6,everi:15,everyth:15,exampl:[0,11,13,14,15],except:[3,15],execut:[2,3,12,14,15,16],exercis:[3,6,11,14,15,16],exercise_by_kei:3,exercisecommand:6,exist:[3,6],exit:[3,15,16],exit_cod:[14,15,16],expect:6,expos:[3,5,9,15],expr:0,express:0,factori:3,fals:[3,16],fashion:3,fetch:[3,15],few:15,field:[0,3,6],file:[14,16],filter:3,filter_fn:3,find:[3,16],find_act:[3,11],find_by_id:3,find_histor:3,find_nonempti:3,find_on:3,finish:16,first:[15,16],five:15,flight:3,focu:15,follow:[0,3,11,14,15,16],for_json:6,format:[7,8,15],formerli:12,forward:[14,16],framework:14,frequent:6,friend:15,friendli:3,from:[3,6,11,12,14,15,16],from_ev:3,fulli:[3,11,15],function_accept_invit:16,function_ingest_the_messag:14,function_multi_creation_depend:16,further:15,futur:[3,16],gener:[3,5,9,14],genesi:[14,16],genesis_contract:14,genesiscontract:16,get:[3,16],get_event_loop:16,get_pretty_print:7,get_tim:3,getlogg:16,gettim:14,give:3,given:[3,16],global:[3,16],globalcli:3,glossari:11,gmbh:[14,16],gracefulli:3,grant:15,grpcio:11,guarante:[3,16],handl:3,handler:[2,3,12,14,15,16],happen:[12,14,15],has:[3,12,14,16],have:[3,11,12,14,15,16],head:3,height:[14,16],helper:15,here:[6,14,16],hidden:3,high:3,higher:3,histor:3,how:[14,16],howev:[14,16],http:[11,12,14,16],ident:3,identifi:[3,6,14,16],if_miss:3,ignor:15,immedi:[3,15],impl:3,implement:[3,8,11,14,16],include_archiv:3,incorpor:3,indefinit:3,index:15,indic:[14,15],individu:3,info:[3,16],inform:12,infrastructur:3,ingest:[11,13,16],ingest_messag:14,ingest_the_messag:14,ingestmessag:14,initev:3,initi:[3,11,15,16],input:14,inspect:[11,13],inspector:[14,15,16],instal:[3,11],install_signal_handl:3,instanc:[3,6,15],instanti:[3,6,15],instead:[3,15],instruct:3,integ:0,interact:[1,3],interfac:3,intermedi:16,intern:15,introduc:15,invit:[15,16],invite_ticket_buy:16,invite_ticket_sel:16,inviteasauthor:15,inviteasreceiv:15,inviteauthorrol:15,inviteparticip:15,inviteparticipantsinprogress:16,invitereceiverrol:15,inviteticketbuy:16,inviteticketsel:16,invoc:3,invok:[3,6,14],involv:[6,14,16],is_match:16,isinst:16,item:16,iter:15,its:[6,14,15,16],itself:6,join:[3,15,16],json:6,just:6,keep:15,kei:[0,3,15,16],kind:6,know:6,known:[2,3],kwarg:3,lambda:[12,15],lane:15,lastli:15,later:[11,15],least:3,ledger:[1,3,6,10,11,12,13,14,16],ledger_arch:3,ledger_archiv:3,ledger_cr:[3,11],ledger_exercis:3,ledger_init:3,ledger_packages_ad:3,ledger_readi:[3,11],ledger_run:[14,15,16],ledger_transaction_end:3,ledger_transaction_start:3,ledgercaptureplugin:[14,15,16],ledgerclientmanag:15,ledgermetadata:3,leger:14,length:[0,3],let:15,letter:[11,13],level:[3,6],librari:[3,6,8,10],licens:[14,16],like:15,line:[2,14],list:[0,3,6,14,15,16],listallcommand:2,listen:[3,11,15],listtyp:6,liter:3,live:[14,16],load:11,local:3,localhost:[11,12,14,16],log:[3,16],log_level:3,logger:3,logic:3,longer:[15,16],lookup:16,loop:[3,16],low:6,made:3,mai:[3,16],main:[2,3,15],make:15,manag:[3,12,15],manipul:3,manner:[14,16],manual:15,map:0,mark:16,market:15,match:[3,16],maximum:3,mean:3,member:[6,15],member_cli:15,member_party_count:15,messag:[11,13,16],message_ingest:14,messageingest:14,messageingestertest:14,metadata:[3,12],method:[3,6,15],metric:3,metricev:3,migrat:11,mileston:16,min_count:3,minimum:[3,15],model:[0,1,3,7,11,13],modul:[5,6,7,9,11,14,15,16],more:[3,12,14,15,16],most:[3,6,15],move:[14,16],multi:16,multipl:[11,16],must:[6,15,16],name:[0,2,3,6,14,15,16],named_arg:6,namedargumentlist:6,nativ:3,necessari:3,need:[3,6,11],network:[3,11,12],networkconfig:3,new_client:[14,15,16],new_datetim:3,new_typ:3,newli:3,newtyp:3,next:16,node:15,non:[3,14],nonconsum:15,none:[3,6,16],nonetyp:3,normal:3,note:[3,6,14,16],notic:15,notif:3,notifi:3,notion:3,now:[3,12,15],num:0,number:3,object:3,occur:[3,14,15,16],off:[3,6],offer_ticket_purchase_agr:16,offerticketpurchaseagr:16,offic:[11,13],old:12,omit:3,on_archiv:[3,12],on_creat:[3,12,14,15,16],on_init:12,on_init_metadata:12,on_readi:[3,12,14,15],on_something_of_valu:11,onc:15,one:[2,3,14,15,16],onli:[3,14,16],oper:[3,14,15,16],operator_cli:16,operatorrol:14,operatorrolecid:14,option:[3,6,7],order:[3,12,15,16],origin:[3,12],originalmessageingestedtim:14,other:[3,14,15,16],our:[14,16],out:[3,15],outgo:3,output:[3,11,13,15],over:[14,16],packag:[11,12],package_id:3,packagesaddedev:3,packagestor:7,param:16,paramet:[3,6,12,14,15],parser:2,parti:[0,3,11,12,14,15,16],particip:[11,13,16],participant_url:[12,14,15,16],participantledgercli:15,party_bot:3,party_cli:3,party_nam:12,partycli:3,partyconfig:3,pass:[6,14],path:[3,15],pathlib:3,paus:3,perform:[14,16],perman:3,perspect:3,phase:16,platflorm:[14,16],platform:[14,16],plugin:[14,15,16],point:[15,16],popen:16,popul:3,port:16,possibl:3,post:[11,13],postman:[11,13],postman_cli:15,postman_parti:15,postmanrol:15,potenti:3,practic:16,pre:6,predecessor:6,prefer:3,present:[3,16],pretti:[1,11],prettyopt:7,prettyprintbas:7,primari:3,print:[7,11,12,15],print_cmd_help:2,proce:16,process:[3,6,15,16],produc:[14,16],product:[0,15],progress:[15,16],project:[14,16],prompt:[14,16],properti:3,protocol:[1,11],provid:[3,12,14,15],purchas:16,purchase_agr:16,purchase_ticket:16,purchaseticket:16,purchs:16,purpos:16,python3:[14,16],python:[0,1,6,10,13],pyyaml:11,queri:3,queu:3,queue:3,quicker:15,rais:3,ran:15,rang:15,react:[14,16],read:[3,6,11],readabl:15,readi:[3,11,15],readyev:3,real:15,realpath:15,receiv:[3,15],receiveraddress:15,receivercid2:15,receivercid:15,receiverrol:15,recommend:[14,16],record:0,recordtyp:6,rectangl:0,refer:[6,14],regist:[3,12,14,15,16],register_event_handl:[14,16],registr:[3,14,15],rejectmessag:14,releas:11,reltim:0,remain:14,remot:3,remov:3,replac:[6,15],repres:[6,16],represent:6,request:[0,3],requestor:14,requestprocessingparti:14,requir:[3,11],reserv:[14,16],resolv:[3,16],resolved_config:3,respect:16,respond:15,respons:15,restart:3,result:[6,15,16],resum:3,reus:6,right:[3,14,16],role:[15,16],rout:15,row:3,rule:6,run:[2,3,11,12,14,15,16],run_forev:[3,12],run_stat:3,run_test:15,run_until_complet:[3,14,15,16],runstat:3,runtim:3,safe:3,same:[6,14,16],sampl:[14,16],sample_callback_oncr:14,sample_daml_scenario_ingest_messag:14,sandbox:[11,14,15,16],save:16,save_purchase_agr:16,scalar:6,scalartyp:6,scenario:[14,16],schedul:3,script:15,sdk:[5,14,15,16],search:3,second:3,section:11,see:[3,15],self:16,seller:16,semver:11,send:[3,6,11,13],sender:15,sent:15,sentlett:15,sentlettercid2:15,sentlettercid:15,separ:15,sequenc:[3,6,14,16],sequenti:[14,16],seri:[14,16],serial:8,serv:15,server:[3,11,14,15,16],servic:3,set:[3,11,12,13,14,16],set_config:[3,11,12],set_result:16,set_tim:3,set_up:[11,15],setinitialworkflowst:16,sever:15,shall:[14,16],should:[3,6,15],show:15,shut:3,shutdown:3,side:[1,3,11],sigint:3,signal:3,signatori:[14,15,16],sigquit:3,similar:[14,16],simpl:[2,6],simple_cli:[3,11,15],simple_glob:3,simple_parti:[3,11],simpleglobalcli:3,simplepartycli:3,sinc:14,singl:[0,3,11,12,15,16],situat:[6,14],situt:16,skip:3,snapshot:3,snippet:14,sole:16,some:[0,3,6,11,12,13],somefield:11,sometext:11,someth:3,somethingof:11,sort:15,sortedlett:15,sourc:[2,3,6,7],source_loc:3,sourceloc:3,spdx:[14,16],specif:[0,3,6,15],specifi:[3,6,14,16],split:15,stamp:3,start:[3,14,15,16],start_in_background:3,starter:[14,16],state:[3,11,13,14,15],stdout:[14,15,16],step:[14,15,16],stop:[3,15,16],stop_al:3,store:[3,7,12,15,16],str:[0,3,6,7],stream:6,string:6,structur:14,style:3,subclass:6,submiss:3,submit:[3,11,15,16],submit_cr:[3,11],submit_create_and_exercis:3,submit_exercis:3,submit_exercise_by_kei:3,submit_fn:3,submodul:[1,11],subpackag:11,subprocess:16,subscrib:3,subsequ:[14,16],successfulli:[3,14,15],sum:0,suppli:6,support:[3,8],sure:15,switzerland:[14,16],synchron:3,sys:15,system:[1,11],tabl:0,tag:6,take:[3,12],tbc:15,tchoos:14,tear:15,templat:[0,3,6,11,14,15,16],template_id:6,template_nam:3,termin:[3,14,15],test:[14,15,16],text:[0,15],thank:11,thei:[3,6,15],them:[3,15],thereaft:16,thi:[0,1,3,6,7,8,11,14,15,16],those:[6,14],thread:3,three:16,through:[11,13,14,16],thu:[14,16],ticket:16,ticket_buyer_invit:16,ticket_buyer_rol:16,ticket_purchase_agr:16,ticket_seller_invit:16,ticket_seller_rol:16,ticketbuy:16,ticketbuyerinvit:16,ticketbuyerrol:16,ticketbuyerrole1:16,ticketpurchaseagr:16,ticketpurchaseagreementoff:16,ticketsel:16,ticketsellerinvit:16,ticketsellerrol:16,ticketsellerrole1:16,tickettransactionsinprogress:16,tickettransactiontest:16,time:[0,3,6,12,14,15],timedelta:[0,3],timeout:3,told:3,total:[14,16],totext:16,track:3,trade:3,traderequest:14,traderequestacceptedtim:14,traderequestcid:14,traderespons:14,traderesponseacknowledgedtim:14,traderesponsecid:14,transact:[3,16],transaction_limit:16,transactionendev:3,transactionstartev:3,transit:16,transition_to_ticket_transactions_in_progress:16,transition_to_workflow_complet:16,tupl:[3,16],tutori:[11,15],two:[6,12,14],type:[0,1,3,7,11],type_arg:6,type_paramet:6,typeadject:6,typerefer:[3,6],types_stor:7,typevari:6,typic:14,typing_extens:3,under:[14,16],underli:[3,6],union:[3,6],uniqu:3,unit:0,univers:15,unpars:6,unresolvedtyperefer:3,unsortedlett:15,unspecifi:3,unsupportedtyp:6,until:[3,16],upload:3,upon:14,ups:3,url:[3,11,12,14,15,16],usd:11,use:[0,3,15,16],used:[3,6,14,16],useful:[3,15],using:15,util:[1,5,7,11],valid:[0,3],valu:[0,3,6,11,15,16],variabl:3,variant:0,varianttyp:6,variou:7,venv:[14,16],verbos:16,veri:15,verifi:[14,16],version:[3,11],view:3,wai:3,wait:[3,11,16],walk:[14,16],want:[3,15],wants_any_kei:3,were:[3,12,14,16],what:[14,15],when:[3,6,14,15,16],whenev:3,where:[0,3,6,12,14,15,16],whether:3,which:[3,6,14,15,16],who:15,whose:3,width:0,wish:3,within:[3,16],without:6,word:3,work:[3,6,14,15],workflow:[3,11,13,14,15],workflow_complet:16,workflow_id:3,workflow_st:16,workflow_state_exampl:16,workflow_state_sampl:16,workflow_ticket_transactions_in_progress:16,workflowcomplet:[14,16],workflowsetupinprogress:16,workflowstateexampl:16,workflowtickettransactionsinprogress:16,would:[3,14],wouldn:15,wrap_as_command_submiss:3,write:[1,3,11,14,16],yet:3,you:[3,6,11,15],your:[6,14,16]},titles:["Basics","dazl package","dazl.cli package","dazl.client package","dazl.damast package","dazl.damlsdk package","dazl.model package","dazl.pretty package","dazl.protocols package","dazl.util package","Glossary","dazl: DA client library for Python","Migrate","Tutorials","Message Ingester","Post Office","Workflow State Example"],titleterms:{api:3,applic:[14,16],archiv:12,basic:0,bot:3,cli:2,client:[3,11],content:[1,2,3,8,11],core:6,creat:[12,15],damast:4,daml:[14,15,16],damlsdk:5,dazl:[1,2,3,4,5,6,7,8,9,11],depend:11,event:12,exampl:16,get:11,glossari:10,ingest:14,initi:12,inspect:15,ledger:15,letter:15,librari:[11,12],listen:12,messag:14,migrat:12,model:[6,14,15,16],modul:[1,2,3,8],offic:15,output:[14,16],packag:[1,2,3,4,5,6,7,8,9],particip:15,post:15,postman:15,pretti:7,protocol:8,python:[11,14,16],readi:12,send:15,set:15,side:6,some:15,start:11,state:16,submodul:[2,3,8],subpackag:1,system:6,tabl:11,through:15,tutori:13,type:6,util:9,workflow:16,write:6}}) \ No newline at end of file +Search.setIndex({docnames:["basics","dazl","dazl.cli","dazl.client","dazl.damlast","dazl.damlsdk","dazl.model","dazl.pretty","dazl.protocols","dazl.util","glossary","index","migrating","tutorials","tutorials_message_ingester","tutorials_post_office","tutorials_workflow_state"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["basics.rst","dazl.rst","dazl.cli.rst","dazl.client.rst","dazl.damlast.rst","dazl.damlsdk.rst","dazl.model.rst","dazl.pretty.rst","dazl.protocols.rst","dazl.util.rst","glossary.rst","index.rst","migrating.rst","tutorials.rst","tutorials_message_ingester.rst","tutorials_post_office.rst","tutorials_workflow_state.rst"],objects:{"":{dazl:[1,0,0,"-"]},"dazl.cli":{ls:[2,0,0,"-"],main:[2,4,1,""],print_cmd_help:[2,4,1,""],run:[2,4,1,""]},"dazl.cli.ls":{ListAllCommand:[2,1,1,""]},"dazl.cli.ls.ListAllCommand":{execute:[2,2,1,""],name:[2,3,1,""],parser:[2,2,1,""]},"dazl.client":{api:[3,0,0,"-"],bots:[3,0,0,"-"]},"dazl.client.api":{AIOGlobalClient:[3,1,1,""],AIOPartyClient:[3,1,1,""],GlobalClient:[3,1,1,""],Network:[3,1,1,""],PartyClient:[3,1,1,""],SimpleGlobalClient:[3,1,1,""],SimplePartyClient:[3,1,1,""],simple_client:[3,4,1,""]},"dazl.client.api.AIOGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.AIOPartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.api.Network":{aio_global:[3,2,1,""],aio_party:[3,2,1,""],aio_run:[3,2,1,""],bots:[3,2,1,""],join:[3,2,1,""],parties:[3,2,1,""],party_bots:[3,2,1,""],resolved_config:[3,2,1,""],run_forever:[3,2,1,""],run_until_complete:[3,2,1,""],set_config:[3,2,1,""],shutdown:[3,2,1,""],simple_global:[3,2,1,""],simple_party:[3,2,1,""],start_in_background:[3,2,1,""]},"dazl.client.api.PartyClient":{party:[3,2,1,""],resolved_config:[3,2,1,""]},"dazl.client.api.SimpleGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.SimplePartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.bots":{Bot:[3,1,1,""],BotCollection:[3,1,1,""],BotEntry:[3,1,1,""],BotInvocation:[3,1,1,""],BotState:[3,1,1,""],wrap_as_command_submission:[3,4,1,""]},"dazl.client.bots.Bot":{add_event_handler:[3,2,1,""],entries:[3,2,1,""],event_keys:[3,2,1,""],id:[3,2,1,""],ledger_created:[3,2,1,""],name:[3,2,1,""],notify:[3,2,1,""],party:[3,2,1,""],pause:[3,2,1,""],resume:[3,2,1,""],running:[3,2,1,""],state:[3,2,1,""],stop:[3,2,1,""],wants_any_keys:[3,2,1,""]},"dazl.client.bots.BotCollection":{add_new:[3,2,1,""],add_single:[3,2,1,""],notify:[3,2,1,""],stop_all:[3,2,1,""]},"dazl.client.bots.BotEntry":{filter:[3,3,1,""],source_location:[3,3,1,""]},"dazl.client.bots.BotState":{PAUSED:[3,3,1,""],PAUSING:[3,3,1,""],RESUMING:[3,3,1,""],RUNNING:[3,3,1,""],STARTING:[3,3,1,""],STOPPED:[3,3,1,""],STOPPING:[3,3,1,""]},"dazl.model":{core:[6,0,0,"-"],ledger:[6,0,0,"-"],reading:[6,0,0,"-"],types:[6,0,0,"-"],types_store:[6,0,0,"-"],writing:[6,0,0,"-"]},"dazl.model.core":{ContractId:[6,1,1,""]},"dazl.model.core.ContractId":{contract_id:[6,3,1,""],exercise:[6,2,1,""],for_json:[6,2,1,""],replace:[6,2,1,""],template_id:[6,3,1,""]},"dazl.model.types":{ListType:[6,1,1,""],RecordType:[6,1,1,""],ScalarType:[6,1,1,""],Type:[6,1,1,""],UnsupportedType:[6,1,1,""],VariantType:[6,1,1,""]},"dazl.model.writing":{Command:[6,1,1,""],CreateCommand:[6,1,1,""],ExerciseCommand:[6,1,1,""]},"dazl.model.writing.CreateCommand":{arguments:[6,3,1,""],replace:[6,2,1,""],template:[6,3,1,""]},"dazl.model.writing.ExerciseCommand":{arguments:[6,3,1,""],choice:[6,3,1,""],contract:[6,3,1,""],replace:[6,2,1,""]},"dazl.pretty":{get_pretty_printer:[7,4,1,""],render_daml:[7,0,0,"-"],util:[7,0,0,"-"]},"dazl.protocols":{v0:[8,0,0,"-"],v1:[8,0,0,"-"]},dazl:{cli:[2,0,0,"-"],client:[3,0,0,"-"],damlast:[4,0,0,"-"],damlsdk:[5,0,0,"-"],model:[6,0,0,"-"],pretty:[7,0,0,"-"],protocols:[8,0,0,"-"],util:[9,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"],"3":["py","attribute","Python attribute"],"4":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method","3":"py:attribute","4":"py:function"},terms:{"00z":14,"01t00":14,"byte":3,"case":[3,14,15,16],"class":[2,3,6,15,16],"default":3,"enum":3,"final":[14,15,16],"float":3,"function":[3,5,9,14,15],"import":[6,11,14,15,16],"int":[0,2,3,6,15],"long":3,"new":[3,6,11,12,14,15,16],"public":3,"return":[3,6,14,15,16],"throw":3,"true":3,"try":[3,14,15,16],"while":3,ACS:[3,11],AND:3,But:15,For:[3,14,15],IDs:[3,6],NOT:3,That:14,The:[0,3,6,10,14,15,16],Then:15,There:[6,15],These:16,Use:3,Using:15,__file__:15,__init__:16,__main__:[14,15,16],__name__:[14,15,16],_asyncio:3,_base:2,_before_:3,_main:3,_network_client_impl:3,_networkimpl:3,_or_:3,_party_client_impl:3,_partyclientimpl:3,_render_bas:7,_resolve_nam:16,_run_level:3,abil:15,abl:3,about:[3,12],abov:[14,15,16],abstractset:3,accept:[15,16],accept_message_act:14,accept_the_messag:14,accept_ticket_buyer_invit:16,accept_ticket_seller_invit:16,acceptinviteauthorrol:15,acceptinvitereceiverrol:15,acceptlett:15,acceptmessag:14,acceptsentlett:15,acceptticketbuyerinvit:16,acceptticketsellerinvit:16,access:12,acknowledg:14,acknowledge_message_act:14,acknowledge_the_messag:14,acknowledgingparti:14,acknowlegedlett:15,across:12,acs_find_on:11,action:16,activ:[3,12,14,16],actual:15,add:[3,14,15,16],add_event_handl:3,add_ledger_archiv:[3,12],add_ledger_cr:[3,12],add_ledger_exercis:3,add_ledger_init:[3,12],add_ledger_packages_ad:3,add_ledger_readi:[3,12],add_ledger_transaction_end:3,add_ledger_transaction_start:3,add_new:3,add_singl:3,added:[3,15],adding:[3,15],addit:[3,6,12,15],addition:[],address:15,adject:6,admin_url:3,advanc:3,affili:[14,16],after:[3,14,15,16],afterward:15,against:[3,15],agre:16,agreement:[15,16],aid:6,aio_glob:3,aio_parti:[3,11,12],aio_run:3,aioglobalcli:3,aiopartycli:3,alic:[11,12,14,16],alice_cli:[12,14,16],all:[3,6,11,14,15,16],all_parti:15,allow:[3,15],alongsid:3,alreadi:[3,11],also:[3,14,15,16],altern:3,alwai:[6,15],amount:3,ani:[3,6],anyth:[3,15],anytim:16,apach:[14,16],api:[1,6,11,12,14,16],append:16,appli:[3,6],applic:[3,11,13],appropri:16,arbitrari:3,archiv:[3,11,14,16],arg:2,argpars:2,argument:[3,6,12,15],argumentpars:2,aris:6,around:5,arrai:3,assert:15,asset:[10,11,12,14,16],assign:[14,16],assist:5,associ:[3,14,16],assum:[6,11,14,15,16],async:[3,11,16],asynchron:[3,11],asyncio:[3,12,16],attribut:6,author:15,authorrol:15,automat:15,await:[3,11,16],background:[3,15],base:[2,3,6,12],baseev:3,basi:[14,16],basic:11,becaus:[15,16],been:[3,12,16],befor:[3,6,15,16],begin:3,behalf:3,behavior:[3,6],being:[3,6],below:0,best:16,bin:[14,16],binaryio:3,bind:16,bit:15,blank:15,block:[3,14,15,16],bob:[12,14,16],bob_client:[12,14,16],bodi:15,bool:[0,3,6],bot:[1,11],botcallback:3,botcollect:3,botentri:3,botfilt:3,both:[6,16],botinvoc:3,botstat:3,build:11,builtin:6,buyer:16,calcul:3,calculaterequest:0,calculaterespons:0,call:[3,12,14,15],callabl:3,callback:[3,11,14,15],caller:3,can:[3,6,14,15,16],cancel:16,cannot:[3,14,16],caught:3,caus:14,cdata:[12,14,15,16],certain:14,chang:[3,12],check:3,choic:[3,6,14,15],choice_argu:3,choice_nam:[3,6],choicemetadata:6,choiceref:6,cid:[3,12,14,15,16],clearli:16,cli:[1,11],clicommand:2,client:[1,6,8,10,12,14,15,16],client_mgr:[14,15,16],close:11,cmd:2,code:[3,6,14,15,16],coerc:3,coercion:6,collaps:12,collect:3,column:15,comfort:3,command:[2,3,6,11,14,15,16],commandbuild:3,commandpayload:3,commit:[14,16],common:3,commun:3,complet:[3,16],composit:6,comput:0,config:3,configur:[3,14],connect:[3,11,14,15],consist:12,construct:6,constructor:[0,6],consum:[14,15],contain:[0,1,3,6,7,8,12,14,16],content:15,contextmanag:3,contextu:3,contract:[3,6,11,12,14,15,16],contract_dict:11,contract_id:6,contract_kei:3,contract_stor:16,contractarchiveev:3,contractcontextualdata:3,contractcontextualdatacollect:3,contractcreateev:3,contractexercisedev:3,contractid:[0,3,6,14,15,16],contractstor:16,control:[14,15,16],conveni:[3,15],convent:12,convert:3,copyright:[14,16],core:[0,1,3,11],coroutin:3,correct:3,correspond:[3,14],could:15,cours:14,creat:[3,6,11,13,14,16],create_and_exercis:3,create_cli:[12,14,15,16],create_futur:16,create_if_miss:3,create_initial_workflow_st:16,createa:14,createcommand:6,createdecimallett:15,createintlett:15,createlett:15,createlistintlett:15,createtimelett:15,creation:[14,16],critic:16,ctrl:3,currenc:[],currency_cid:[],current:[3,6],custom:14,daemon:3,dalf:3,damast:[1,11],daml:[0,5,6,11,13],daml_fil:15,daml_ledger_parti:3,daml_ledger_url:3,damlsdk:[1,11],dar:3,data:[0,3,12],date:[0,3],datetim:[0,3],dazl:[0,10,12,14,15,16],deactiv:15,debug:16,decim:[0,3,6,15],declar:3,decor:3,def:[11,14,15,16],defin:[6,14,15,16],del:16,delet:16,deliv:15,demonstr:16,depend:16,deploi:[14,16],describ:[6,14,16],descript:6,design:[14,16],detect:[3,14,16],develop:[15,16],dict:[0,3,6,15,16],dictionari:[0,3],differ:[8,16],difficult:15,digit:[10,11,14,16],directli:[3,6],dirnam:15,disabl:3,disambigu:6,dish:15,dispatch:3,dispos:15,doc_begin:[14,16],doc_end:[14,16],doe:3,domain:6,don:6,done:[3,14,16],down:[3,15],download:[14,16],drain:3,drawn:15,dump_al:[14,15,16],dure:14,each:[14,15,16],easier:16,easili:15,either:[3,6,15],els:[15,16],empti:0,encapsul:16,encount:3,ensur:3,ensure_dar:3,ensure_packag:3,entir:3,entri:3,environ:3,equival:3,error:3,eustac:[],even:15,event:[3,6,11,14,15,16],event_kei:3,eventkei:3,eventu:6,ever:6,everi:15,everyth:15,exampl:[0,11,13,14,15],except:[3,15],execut:[2,3,12,14,15,16],exercis:[3,6,14,15,16],exercise_by_kei:3,exercisecommand:6,exist:[3,6],exit:[3,15,16],exit_cod:[14,15,16],expect:6,expos:[3,5,9,15],expr:0,express:0,factori:3,fals:[3,16],fashion:3,fetch:[3,15],few:15,field:[0,3,6],file:[14,16],filter:3,filter_fn:3,find:[3,16],find_act:[3,11],find_by_id:3,find_histor:3,find_nonempti:3,find_on:3,finish:16,first:[15,16],five:15,flight:3,focu:15,follow:[0,3,14,15,16],for_json:6,format:[7,8,15],formerli:12,forward:[14,16],framework:14,frequent:6,friend:15,friendli:3,from:[3,6,11,12,14,15,16],from_ev:3,fulli:[3,11,15],function_accept_invit:16,function_ingest_the_messag:14,function_multi_creation_depend:16,further:15,futur:[3,16],gener:[3,5,9,14],genesi:[14,16],genesis_contract:14,genesiscontract:16,get:[3,16],get_event_loop:16,get_pretty_print:7,get_tim:3,getlogg:16,gettim:14,give:3,given:[3,16],global:[3,16],globalcli:3,glossari:11,gmbh:[14,16],gracefulli:3,grant:15,grpcio:[],guarante:[3,16],handl:[3,11],handler:[2,3,12,14,15,16],happen:[12,14,15],has:[3,12,14,16],have:[3,11,12,14,15,16],head:3,height:[14,16],hello:11,helper:15,here:[6,14,16],hidden:3,high:3,higher:3,histor:3,how:[14,16],howev:[14,16],http:[11,12,14,16],ident:3,identifi:[3,6,14,16],if_miss:3,ignor:15,immedi:[3,15],impl:3,implement:[3,8,11,14,16],include_archiv:3,incorpor:3,indefinit:3,index:15,indic:[14,15],individu:3,info:[3,16],inform:12,infrastructur:3,ingest:[11,13,16],ingest_messag:14,ingest_the_messag:14,ingestmessag:14,initev:3,initi:[3,11,15,16],input:14,inspect:[11,13],inspector:[14,15,16],instal:3,install_signal_handl:3,instanc:[3,6,15],instanti:[3,6,15],instead:[3,15],instruct:3,integ:0,interact:[1,3],interfac:3,intermedi:16,intern:15,introduc:15,invit:[15,16],invite_ticket_buy:16,invite_ticket_sel:16,inviteasauthor:15,inviteasreceiv:15,inviteauthorrol:15,inviteparticip:15,inviteparticipantsinprogress:16,invitereceiverrol:15,inviteticketbuy:16,inviteticketsel:16,invoc:3,invok:[3,6,14],involv:[6,14,16],is_match:16,isinst:16,issuer:11,item:16,iter:15,its:[6,14,15,16],itself:6,join:[3,15,16],json:6,just:6,keep:15,kei:[0,3,15,16],kind:6,know:6,known:[2,3],kwarg:3,lambda:[12,15],lane:15,lastli:15,later:[11,15],least:3,ledger:[1,3,6,10,11,12,13,14,16],ledger_arch:3,ledger_archiv:3,ledger_cr:3,ledger_exercis:3,ledger_init:3,ledger_packages_ad:3,ledger_readi:[3,11],ledger_run:[14,15,16],ledger_transaction_end:3,ledger_transaction_start:3,ledgercaptureplugin:[14,15,16],ledgerclientmanag:15,ledgermetadata:3,leger:14,length:[0,3],let:15,letter:[11,13],level:[3,6],librari:[3,6,8,10],licens:[14,16],like:15,line:[2,14],list:[0,3,6,14,15,16],listallcommand:2,listen:[3,11,15],listtyp:6,liter:3,live:[14,16],load:11,local:3,localhost:[11,12,14,16],log:[3,16],log_level:3,logger:3,logic:3,longer:[15,16],lookup:16,loop:[3,16],low:6,made:3,mai:[3,16],main:[2,3,11,15],make:15,manag:[3,12,15],manipul:3,manner:[14,16],manual:15,map:0,mark:16,market:15,match:[3,16],maximum:3,mean:3,member:[6,15],member_cli:15,member_party_count:15,messag:[11,13,16],message_ingest:14,messageingest:14,messageingestertest:14,metadata:[3,12],method:[3,6,15],metric:3,metricev:3,migrat:11,mileston:16,min_count:3,minimum:[3,15],model:[0,1,3,7,11,13],modul:[5,6,7,9,11,14,15,16],more:[3,12,14,15,16],most:[3,6,15],move:[14,16],multi:16,multipl:16,must:[6,15,16],name:[0,2,3,6,11,14,15,16],named_arg:6,namedargumentlist:6,nativ:3,necessari:3,need:[3,6,11],network:[3,11,12],networkconfig:3,new_client:[14,15,16],new_datetim:3,new_typ:3,newli:3,newtyp:3,next:16,node:15,non:[3,14],nonconsum:15,none:[3,6,16],nonetyp:3,normal:3,note:[3,6,14,16],notic:15,notif:3,notifi:3,notion:3,now:[3,12,15],num:0,number:3,object:3,occur:[3,14,15,16],off:[3,6],offer_ticket_purchase_agr:16,offerticketpurchaseagr:16,offic:[11,13],old:12,omit:3,on_archiv:[3,12],on_creat:[3,12,14,15,16],on_init:12,on_init_metadata:12,on_readi:[3,12,14,15],on_something_of_valu:[],onc:15,one:[2,3,14,15,16],onli:[3,14,16],onreadi:11,oper:[3,14,15,16],operator_cli:16,operatorrol:14,operatorrolecid:14,option:[3,6,7],order:[3,12,15,16],origin:[3,12],originalmessageingestedtim:14,other:[3,14,15,16],our:[14,16],out:[3,15],outgo:3,output:[3,11,13,15],over:[14,16],owner:11,packag:[11,12],package_id:3,packagesaddedev:3,packagestor:7,param:16,paramet:[3,6,12,14,15],parser:2,parti:[0,3,11,12,14,15,16],particip:[11,13,16],participant_url:[12,14,15,16],participantledgercli:15,party_bot:3,party_cli:3,party_nam:12,partycli:3,partyconfig:3,pass:[6,14],path:[3,15],pathlib:3,paus:3,perform:[14,16],perman:3,perspect:3,phase:16,platflorm:[14,16],platform:[14,16],plugin:[14,15,16],poetri:11,point:[15,16],popen:16,popul:3,port:16,possibl:3,post:[11,13],postman:[11,13],postman_cli:15,postman_parti:15,postmanrol:15,potenti:3,practic:16,pre:6,predecessor:6,prefer:3,present:[3,16],pretti:[1,11],prettyopt:7,prettyprintbas:7,primari:3,print:[7,11,12,15],print_cmd_help:2,proce:16,process:[3,6,15,16],produc:[14,16],product:[0,15],progress:[15,16],project:[14,16],prompt:[14,16],properti:3,protocol:[1,11],provid:[3,12,14,15],purchas:16,purchase_agr:16,purchase_ticket:16,purchaseticket:16,purchs:16,purpos:16,python3:[14,16],python:[0,1,6,10,13],pyyaml:[],queri:3,queu:3,queue:3,quicker:15,rais:3,ran:15,rang:15,react:[14,16],read:[3,6,11],readabl:15,readi:[3,11,15],readyev:[3,11],real:15,realpath:15,receiv:[3,15],receiveraddress:15,receivercid2:15,receivercid:15,receiverrol:15,recommend:[14,16],record:0,recordtyp:6,rectangl:0,refer:[6,14],regist:[3,12,14,15,16],register_event_handl:[14,16],registr:[3,14,15],rejectmessag:14,releas:11,reltim:0,remain:14,remot:3,remov:3,replac:[6,15],repres:[6,16],represent:6,request:[0,3],requestor:14,requestprocessingparti:14,requir:3,reserv:[14,16],resolv:[3,16],resolved_config:3,respect:16,respond:15,respons:15,restart:3,result:[6,15,16],resum:3,reus:6,right:[3,14,16],role:[15,16],rout:15,row:3,rule:6,run:[2,3,11,12,14,15,16],run_forev:[3,12],run_stat:3,run_test:15,run_until_complet:[3,11,14,15,16],runstat:3,runtim:3,safe:3,same:[6,14,16],sampl:[14,16],sample_callback_oncr:14,sample_daml_scenario_ingest_messag:14,sandbox:[11,14,15,16],save:16,save_purchase_agr:16,scalar:6,scalartyp:6,scenario:[14,16],schedul:3,script:15,sdk:[5,14,15,16],search:3,second:3,section:11,see:[3,15],self:16,seller:16,semver:[],send:[3,6,11,13],sender:15,sent:15,sentlett:15,sentlettercid2:15,sentlettercid:15,separ:15,sequenc:[3,6,14,16],sequenti:[14,16],seri:[14,16],serial:8,serv:15,server:[3,11,14,15,16],servic:3,set:[3,11,12,13,14,16],set_config:[3,11,12],set_result:16,set_tim:3,set_up:15,setinitialworkflowst:16,sever:15,shall:[14,16],should:[3,6,15],show:15,shut:3,shutdown:3,side:[1,3,11],sigint:3,signal:3,signatori:[14,15,16],sigquit:3,similar:[14,16],simpl:[2,6],simple_cli:[3,11,15],simple_glob:3,simple_parti:3,simpleglobalcli:3,simplepartycli:3,sinc:14,singl:[0,3,11,12,15,16],situat:[6,14],situt:16,skip:3,snapshot:3,snippet:14,sole:16,some:[0,3,6,11,12,13],somefield:[],sometext:[],someth:3,somethingof:[],sort:15,sortedlett:15,sourc:[2,3,6,7],source_loc:3,sourceloc:3,spdx:[14,16],specif:[0,3,6,15],specifi:[3,6,14,16],split:15,stamp:3,standard:11,start:[3,14,15,16],start_in_background:3,starter:[14,16],state:[3,11,13,14,15],stdout:[14,15,16],step:[14,15,16],stop:[3,15,16],stop_al:3,store:[3,7,12,15,16],str:[0,3,6,7],stream:6,string:6,structur:14,style:3,subclass:6,submiss:3,submit:[3,11,15,16],submit_cr:[3,11],submit_create_and_exercis:3,submit_exercis:3,submit_exercise_by_kei:3,submit_fn:3,submodul:[1,11],subpackag:11,subprocess:16,subscrib:3,subsequ:[14,16],successfulli:[3,14,15],sum:0,suppli:6,support:[3,8],sure:15,switzerland:[14,16],synchron:3,sys:15,system:[1,11],tabl:0,tag:6,take:[3,12],tbc:15,tchoos:14,tear:15,templat:[0,3,6,14,15,16],template_id:6,template_nam:3,termin:[3,14,15],test:[14,15,16],text:[0,15],thank:[],thei:[3,6,15],them:[3,15],thereaft:16,thi:[0,1,3,6,7,8,11,14,15,16],those:[6,14],thread:3,three:16,through:[11,13,14,16],thu:[14,16],ticket:16,ticket_buyer_invit:16,ticket_buyer_rol:16,ticket_purchase_agr:16,ticket_seller_invit:16,ticket_seller_rol:16,ticketbuy:16,ticketbuyerinvit:16,ticketbuyerrol:16,ticketbuyerrole1:16,ticketpurchaseagr:16,ticketpurchaseagreementoff:16,ticketsel:16,ticketsellerinvit:16,ticketsellerrol:16,ticketsellerrole1:16,tickettransactionsinprogress:16,tickettransactiontest:16,time:[0,3,6,11,12,14,15],timedelta:[0,3],timeout:3,told:3,total:[14,16],totext:16,track:3,trade:3,traderequest:14,traderequestacceptedtim:14,traderequestcid:14,traderespons:14,traderesponseacknowledgedtim:14,traderesponsecid:14,transact:[3,16],transaction_limit:16,transactionendev:3,transactionstartev:3,transit:16,transition_to_ticket_transactions_in_progress:16,transition_to_workflow_complet:16,tupl:[3,16],tutori:[11,15],two:[6,12,14],type:[0,1,3,7,11],type_arg:6,type_paramet:6,typeadject:6,typerefer:[3,6],types_stor:7,typevari:6,typic:14,typing_extens:3,under:[14,16],underli:[3,6],union:[3,6],uniqu:3,unit:0,univers:15,unpars:6,unresolvedtyperefer:3,unsortedlett:15,unspecifi:3,unsupportedtyp:6,until:[3,16],upload:3,upon:14,ups:3,url:[3,11,12,14,15,16],usd:[],use:[0,3,15,16],used:[3,6,14,16],useful:[3,15],using:[11,15],util:[1,5,7,11],valid:[0,3],valu:[0,3,6,15,16],variabl:3,variant:0,varianttyp:6,variou:7,venv:[14,16],verbos:16,veri:15,verifi:[14,16],version:[3,11],view:3,wai:3,wait:[3,11,16],walk:[14,16],want:[3,15],wants_any_kei:3,were:[3,12,14,16],what:[14,15],when:[3,6,14,15,16],whenev:3,where:[0,3,6,12,14,15,16],whether:3,which:[3,6,14,15,16],who:15,whose:3,width:0,wish:3,within:[3,16],without:6,word:3,work:[3,6,14,15],workflow:[3,11,13,14,15],workflow_complet:16,workflow_id:3,workflow_st:16,workflow_state_exampl:16,workflow_state_sampl:16,workflow_ticket_transactions_in_progress:16,workflowcomplet:[14,16],workflowsetupinprogress:16,workflowstateexampl:16,workflowtickettransactionsinprogress:16,world:11,would:[3,14],wouldn:15,wrap_as_command_submiss:3,write:[1,3,11,14,16],yet:3,you:[3,6,11,15],your:[6,14,16]},titles:["Basics","dazl package","dazl.cli package","dazl.client package","dazl.damast package","dazl.damlsdk package","dazl.model package","dazl.pretty package","dazl.protocols package","dazl.util package","Glossary","dazl: DA client library for Python","Migrate","Tutorials","Message Ingester","Post Office","Workflow State Example"],titleterms:{api:3,applic:[14,16],archiv:12,basic:0,bot:3,cli:2,client:[3,11],content:[1,2,3,8,11],core:6,creat:[12,15],damast:4,daml:[14,15,16],damlsdk:5,dazl:[1,2,3,4,5,6,7,8,9,11],depend:11,event:12,exampl:16,get:11,glossari:10,ingest:14,initi:12,inspect:15,ledger:15,letter:15,librari:[11,12],listen:12,messag:14,migrat:12,model:[6,14,15,16],modul:[1,2,3,8],offic:15,output:[14,16],packag:[1,2,3,4,5,6,7,8,9],particip:15,post:15,postman:15,pretti:7,protocol:8,python:[11,14,16],readi:12,send:15,set:15,side:6,some:15,start:11,state:16,submodul:[2,3,8],subpackag:1,system:6,tabl:11,through:15,tutori:13,type:6,util:9,workflow:16,write:6}}) \ No newline at end of file diff --git a/python/README.md b/python/README.md index ec6fbdae..2ecdf937 100644 --- a/python/README.md +++ b/python/README.md @@ -12,69 +12,82 @@ SPDX-License-Identifier: Apache-2.0 Rich Python bindings for accessing Ledger API-based applications. +Documentation +------------- +The user documentation is available online [here](https://digital-asset.github.io/dazl-client). + +Installation +------------ +If you just want to use the library, you can install it locally with `pip`: +```sh +pip install --user dazl +``` + Requirements ------------ * Python 3.6+ -* [Pipenv](https://pipenv.readthedocs.io/en/latest/) +* [Poetry](https://poetry.eustace.io/) for build/dependency management * Although not strictly required for building, you'll probably want the [DAML SDK](https://www.daml.com) Examples -------- -All of the examples below assume you imported `dazl`. +All of the examples below assume you imported `dazl`, and are running a ledger with the default scenario generated with `daml new`. Connect to the ledger and submit a single command: ```py -with dazl.simple_client('http://localhost:7600', 'Alice') as client: - client.submit_create('Alice', 'My.Template', { someField: 'someText' }) +with dazl.simple_client('http://localhost:6865', 'Alice') as client: + contract = { 'issuer' : 'Alice', 'owner' : 'Alice', 'name' : 'hello world!' } + client.ready() + client.submit_create('Main.Asset', contract) ``` Connect to the ledger as a single party, print all contracts, and close: ```py -with dazl.simple_client('http://localhost:7600', 'Alice') as client: +with dazl.simple_client('http://localhost:6865', 'Alice') as client: # wait for the ACS to be fully read client.ready() contract_dict = client.find_active('*') print(contract_dict) ``` -Connect to the ledger as multiple parties: +Connect to the ledger using asynchronous callbacks: ```py +from dazl.model.reading import ReadyEvent network = dazl.Network() -network.set_config(url='http://localhost:7600') +network.set_config(url='http://localhost:6865') -alice = network.simple_party('Alice') -bob = network.simple_party('Bob') +alice = network.aio_party('Alice') @alice.ledger_ready() -def set_up(event): - currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"}) - return dazl.create('SomethingOf.Value', { - 'amount': 100, - 'currency': currency_cid, - 'from': 'Accept', - 'to': 'Bob' }) - -@bob.ledger_created('SomethingOf.Value') -def on_something_of_value(event): - return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' }) - -network.start() +async def onReady(event: ReadyEvent): + contracts = await event.acs_find_one('Main.Asset') + print(contracts) + +network.run_until_complete() ``` Building locally ---------------- +You will need to have [Poetry](https://poetry.eustace.io/) installed, and the dependencies fetched using `poetry install`. Then do: + ```sh -cd python && pipenv run package +make build ``` +If you see errors about incompatible python versions, switch your environment to python3 using `poetry env use python3`, for instance. + +Building Documentation +---------------------- +The above command will build documentation in the root `docs/` dir. Committing this into source control and pushing to github will cause github-pages to be updated. + Tests ----- ```sh -cd python && pipenv run test +make test ``` diff --git a/python/docs/index.rst b/python/docs/index.rst index ef572167..3185d001 100644 --- a/python/docs/index.rst +++ b/python/docs/index.rst @@ -7,22 +7,22 @@ Dependencies ------------ You will need Python 3.6 or later and a Digital Asset ledger implementation (DA Sandbox or -DA Ledger Server). :term:`dazl` additionally requires the following libraries to be -installed: +DA Ledger Server). + +Build-time dependencies are handled using `Poetry `_. -* grpcio, version 1.18.0 or later -* PyYAML -* semver Getting Started --------------- -This section assumes that you already have a running ledger with a DAML model loaded. +This section assumes that you already have a running ledger with the standard `daml new` model loaded, and have imported `dazl`. Connect to the ledger and submit a single command:: - with dazl.simple_client('http://localhost:7600', 'Alice') as client: - client.submit_create('Alice', 'My.Template', { someField: 'someText' }) + with dazl.simple_client('http://localhost:6865', 'Alice') as client: + contract = { 'issuer' : 'Alice', 'owner' : 'Alice', 'name' : 'hello world!' } + client.ready() + client.submit_create('Main.Asset', contract) Connect to the ledger as a single party, print all contracts, and close:: @@ -32,29 +32,20 @@ Connect to the ledger as a single party, print all contracts, and close:: contract_dict = client.find_active('*') print(contract_dict) -Connect to the ledger as multiple parties:: +Connect to the ledger using asynchronous callbacks:: + from dazl.model.reading import ReadyEvent network = dazl.Network() - network.set_config(url='http://localhost:7600') + network.set_config(url='http://localhost:6865') - alice = network.simple_party('Alice') - bob = network.simple_party('Bob') + alice = network.aio_party('Alice') @alice.ledger_ready() - def set_up(event): - currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"}) - return dazl.create('SomethingOf.Value', { - 'amount': 100, - 'currency': currency_cid, - 'from': 'Accept', - 'to': 'Bob' }) - - @bob.ledger_created('SomethingOf.Value') - def on_something_of_value(event): - return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' }) - - network.start() + async def onReady(event: ReadyEvent): + contracts = await event.acs_find_one('Main.Asset') + print(contracts) + network.run_until_complete() Table of Contents ----------------- From 9669666fcc39b595ec472ec98e2e29277cd21f49 Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Wed, 28 Aug 2019 16:14:52 +0200 Subject: [PATCH 4/7] Make README a link to python/README.md. Previously they were not in sync. --- README.md | 81 +------------------------------------------------------ 1 file changed, 1 insertion(+), 80 deletions(-) mode change 100644 => 120000 README.md diff --git a/README.md b/README.md deleted file mode 100644 index ec6fbdae..00000000 --- a/README.md +++ /dev/null @@ -1,80 +0,0 @@ -dazl -==== - -[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/digital-asset/dazl-client/blob/master/LICENSE) -
- - - -Copyright 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - - -Rich Python bindings for accessing Ledger API-based applications. - -Requirements ------------- -* Python 3.6+ -* [Pipenv](https://pipenv.readthedocs.io/en/latest/) -* Although not strictly required for building, you'll probably want the [DAML SDK](https://www.daml.com) - -Examples --------- - -All of the examples below assume you imported `dazl`. - -Connect to the ledger and submit a single command: - -```py -with dazl.simple_client('http://localhost:7600', 'Alice') as client: - client.submit_create('Alice', 'My.Template', { someField: 'someText' }) -``` - -Connect to the ledger as a single party, print all contracts, and close: - -```py -with dazl.simple_client('http://localhost:7600', 'Alice') as client: - # wait for the ACS to be fully read - client.ready() - contract_dict = client.find_active('*') -print(contract_dict) -``` - -Connect to the ledger as multiple parties: - -```py -network = dazl.Network() -network.set_config(url='http://localhost:7600') - -alice = network.simple_party('Alice') -bob = network.simple_party('Bob') - -@alice.ledger_ready() -def set_up(event): - currency_cid, _ = await event.acs_find_one('My.Currency', {"currency": "USD"}) - return dazl.create('SomethingOf.Value', { - 'amount': 100, - 'currency': currency_cid, - 'from': 'Accept', - 'to': 'Bob' }) - -@bob.ledger_created('SomethingOf.Value') -def on_something_of_value(event): - return dazl.exercise(event.cid, 'Accept', { 'message': 'Thanks!' }) - -network.start() -``` - - -Building locally ----------------- -```sh -cd python && pipenv run package -``` - -Tests ------ - -```sh -cd python && pipenv run test -``` diff --git a/README.md b/README.md new file mode 120000 index 00000000..0a36d90c --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +python/README.md \ No newline at end of file From cd29a417f85108c69eaa31d51be9cba5686bf893 Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Fri, 6 Sep 2019 09:13:42 +0200 Subject: [PATCH 5/7] Update hello-world build file. --- samples/hello-world/da.yaml | 8 -------- samples/hello-world/daml.yaml | 10 ++++++++++ 2 files changed, 10 insertions(+), 8 deletions(-) delete mode 100644 samples/hello-world/da.yaml create mode 100644 samples/hello-world/daml.yaml diff --git a/samples/hello-world/da.yaml b/samples/hello-world/da.yaml deleted file mode 100644 index e55bd4af..00000000 --- a/samples/hello-world/da.yaml +++ /dev/null @@ -1,8 +0,0 @@ -project: - sdk-version: '0.12.1' - name: hello-world - source: src/daml/Sample.daml - parties: - - Alice - - Bob -version: 2 diff --git a/samples/hello-world/daml.yaml b/samples/hello-world/daml.yaml new file mode 100644 index 00000000..32746c30 --- /dev/null +++ b/samples/hello-world/daml.yaml @@ -0,0 +1,10 @@ +sdk-version: 0.13.21 +name: hello-world +source: src/daml/Sample.daml +parties: + - Alice + - Bob +version: "2" +dependencies: + - daml-prim + - daml-stdlib From db0d66d08f4f3f1ae780a2dd1f64a0f0b50e0871 Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Fri, 6 Sep 2019 09:34:14 +0200 Subject: [PATCH 6/7] Update ping-pong sample build system. - Use poetry instead of pipenv - Update README to reflect this --- samples/ping-pong/README.md | 6 +- samples/ping-pong/poetry.lock | 316 +++++++++++++++++++++++++++++++ samples/ping-pong/pyproject.toml | 15 ++ samples/ping-pong/run.sh | 10 - 4 files changed, 334 insertions(+), 13 deletions(-) create mode 100644 samples/ping-pong/poetry.lock create mode 100644 samples/ping-pong/pyproject.toml delete mode 100755 samples/ping-pong/run.sh diff --git a/samples/ping-pong/README.md b/samples/ping-pong/README.md index 652df37b..a2502ab9 100644 --- a/samples/ping-pong/README.md +++ b/samples/ping-pong/README.md @@ -6,11 +6,11 @@ Ping Pong application using [DAZL](https://pypi.org/project/dazl/) Run each of the following commands in a spearate shell: -* Start the sandbox and navigator via: +* Start the sandbox and navigator on default port 6865 via: daml start -* Start DAZL via +* Start DAZL ping-pong client via - pipenv run python3 src/main.py --url {ledgerUrl} + poetry run python3 app.py --url localhost:6865 diff --git a/samples/ping-pong/poetry.lock b/samples/ping-pong/poetry.lock new file mode 100644 index 00000000..16477a42 --- /dev/null +++ b/samples/ping-pong/poetry.lock @@ -0,0 +1,316 @@ +[[package]] +category = "main" +description = "Async http client/server framework (asyncio)" +name = "aiohttp" +optional = false +python-versions = ">=3.5.3" +version = "3.5.4" + +[package.dependencies] +async-timeout = ">=3.0,<4.0" +attrs = ">=17.3.0" +chardet = ">=2.0,<4.0" +multidict = ">=4.0,<5.0" +yarl = ">=1.0,<2.0" + +[package.dependencies.idna-ssl] +python = "<3.7" +version = ">=1.0" + +[package.dependencies.typing-extensions] +python = "<3.7" +version = ">=3.6.5" + +[[package]] +category = "main" +description = "Timeout context manager for asyncio programs" +name = "async-timeout" +optional = false +python-versions = ">=3.5.3" +version = "3.0.1" + +[[package]] +category = "main" +description = "Classes Without Boilerplate" +name = "attrs" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +version = "19.1.0" + +[[package]] +category = "main" +description = "Extensible memoizing collections and decorators" +name = "cachetools" +optional = false +python-versions = "*" +version = "3.1.1" + +[[package]] +category = "main" +description = "Python package for providing Mozilla's CA Bundle." +name = "certifi" +optional = false +python-versions = "*" +version = "2019.6.16" + +[[package]] +category = "main" +description = "Universal encoding detector for Python 2 and 3" +name = "chardet" +optional = false +python-versions = "*" +version = "3.0.4" + +[[package]] +category = "main" +description = "A backport of the dataclasses module for Python 3.6" +marker = "python_version >= \"3.6.0\" and python_version < \"3.7.0\"" +name = "dataclasses" +optional = false +python-versions = "*" +version = "0.6" + +[[package]] +category = "main" +description = "high-level Ledger API client for DAML ledgers" +name = "dazl" +optional = false +python-versions = ">=3.6" +version = "6.3.1" + +[package.dependencies] +aiohttp = "*" +google-auth = "*" +grpcio = ">=1.20.1" +oauthlib = "*" +protobuf = ">=3.8.0" +pyyaml = "*" +requests = "*" +semver = "*" +toposort = "*" +typing_extensions = "*" + +[package.dependencies.dataclasses] +python = ">=3.6.0,<3.7.0" +version = "*" + +[[package]] +category = "main" +description = "Google Authentication Library" +name = "google-auth" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*" +version = "1.6.3" + +[package.dependencies] +cachetools = ">=2.0.0" +pyasn1-modules = ">=0.2.1" +rsa = ">=3.1.4" +six = ">=1.9.0" + +[[package]] +category = "main" +description = "HTTP/2-based RPC framework" +name = "grpcio" +optional = false +python-versions = "*" +version = "1.23.0" + +[package.dependencies] +six = ">=1.5.2" + +[[package]] +category = "main" +description = "Internationalized Domain Names in Applications (IDNA)" +name = "idna" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +version = "2.8" + +[[package]] +category = "main" +description = "Patch ssl.match_hostname for Unicode(idna) domains support" +marker = "python_version < \"3.7\"" +name = "idna-ssl" +optional = false +python-versions = "*" +version = "1.1.0" + +[package.dependencies] +idna = ">=2.0" + +[[package]] +category = "main" +description = "multidict implementation" +name = "multidict" +optional = false +python-versions = ">=3.4.1" +version = "4.5.2" + +[[package]] +category = "main" +description = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic" +name = "oauthlib" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +version = "3.1.0" + +[[package]] +category = "main" +description = "Protocol Buffers" +name = "protobuf" +optional = false +python-versions = "*" +version = "3.9.1" + +[package.dependencies] +setuptools = "*" +six = ">=1.9" + +[[package]] +category = "main" +description = "ASN.1 types and codecs" +name = "pyasn1" +optional = false +python-versions = "*" +version = "0.4.7" + +[[package]] +category = "main" +description = "A collection of ASN.1-based protocols modules." +name = "pyasn1-modules" +optional = false +python-versions = "*" +version = "0.2.6" + +[package.dependencies] +pyasn1 = ">=0.4.6,<0.5.0" + +[[package]] +category = "main" +description = "YAML parser and emitter for Python" +name = "pyyaml" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +version = "5.1.2" + +[[package]] +category = "main" +description = "Python HTTP for Humans." +name = "requests" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +version = "2.22.0" + +[package.dependencies] +certifi = ">=2017.4.17" +chardet = ">=3.0.2,<3.1.0" +idna = ">=2.5,<2.9" +urllib3 = ">=1.21.1,<1.25.0 || >1.25.0,<1.25.1 || >1.25.1,<1.26" + +[[package]] +category = "main" +description = "Pure-Python RSA implementation" +name = "rsa" +optional = false +python-versions = "*" +version = "4.0" + +[package.dependencies] +pyasn1 = ">=0.1.3" + +[[package]] +category = "main" +description = "Python helper for Semantic Versioning (http://semver.org/)" +name = "semver" +optional = false +python-versions = "*" +version = "2.8.1" + +[[package]] +category = "main" +description = "Python 2 and 3 compatibility utilities" +name = "six" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*" +version = "1.12.0" + +[[package]] +category = "main" +description = "Implements a topological sort algorithm." +name = "toposort" +optional = false +python-versions = "*" +version = "1.5" + +[[package]] +category = "main" +description = "Type Hints for Python" +name = "typing" +optional = false +python-versions = "*" +version = "3.7.4.1" + +[[package]] +category = "main" +description = "Backported and Experimental Type Hints for Python 3.5+" +name = "typing-extensions" +optional = false +python-versions = "*" +version = "3.7.4" + +[package.dependencies] +typing = ">=3.7.4" + +[[package]] +category = "main" +description = "HTTP library with thread-safe connection pooling, file post, and more." +name = "urllib3" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4" +version = "1.25.3" + +[[package]] +category = "main" +description = "Yet another URL library" +name = "yarl" +optional = false +python-versions = ">=3.5.3" +version = "1.3.0" + +[package.dependencies] +idna = ">=2.0" +multidict = ">=4.0" + +[metadata] +content-hash = "28e4a2ec7f844839ee5e132bf3ece7599dea031122220cda16bb3919366b05d0" +python-versions = "^3.6" + +[metadata.hashes] +aiohttp = ["00d198585474299c9c3b4f1d5de1a576cc230d562abc5e4a0e81d71a20a6ca55", "0155af66de8c21b8dba4992aaeeabf55503caefae00067a3b1139f86d0ec50ed", "09654a9eca62d1bd6d64aa44db2498f60a5c1e0ac4750953fdd79d5c88955e10", "199f1d106e2b44b6dacdf6f9245493c7d716b01d0b7fbe1959318ba4dc64d1f5", "296f30dedc9f4b9e7a301e5cc963012264112d78a1d3094cd83ef148fdf33ca1", "368ed312550bd663ce84dc4b032a962fcb3c7cae099dbbd48663afc305e3b939", "40d7ea570b88db017c51392349cf99b7aefaaddd19d2c78368aeb0bddde9d390", "629102a193162e37102c50713e2e31dc9a2fe7ac5e481da83e5bb3c0cee700aa", "6d5ec9b8948c3d957e75ea14d41e9330e1ac3fed24ec53766c780f82805140dc", "87331d1d6810214085a50749160196391a712a13336cd02ce1c3ea3d05bcf8d5", "9a02a04bbe581c8605ac423ba3a74999ec9d8bce7ae37977a3d38680f5780b6d", "9c4c83f4fa1938377da32bc2d59379025ceeee8e24b89f72fcbccd8ca22dc9bf", "9cddaff94c0135ee627213ac6ca6d05724bfe6e7a356e5e09ec57bd3249510f6", "a25237abf327530d9561ef751eef9511ab56fd9431023ca6f4803f1994104d72", "a5cbd7157b0e383738b8e29d6e556fde8726823dae0e348952a61742b21aeb12", "a97a516e02b726e089cffcde2eea0d3258450389bbac48cbe89e0f0b6e7b0366", "acc89b29b5f4e2332d65cd1b7d10c609a75b88ef8925d487a611ca788432dfa4", "b05bd85cc99b06740aad3629c2585bda7b83bd86e080b44ba47faf905fdf1300", "c2bec436a2b5dafe5eaeb297c03711074d46b6eb236d002c13c42f25c4a8ce9d", "cc619d974c8c11fe84527e4b5e1c07238799a8c29ea1c1285149170524ba9303", "d4392defd4648badaa42b3e101080ae3313e8f4787cb517efd3f5b8157eaefd6", "e1c3c582ee11af7f63a34a46f0448fca58e59889396ffdae1f482085061a2889"] +async-timeout = ["0c3c816a028d47f659d6ff5c745cb2acf1f966da1fe5c19c77a70282b25f4c5f", "4291ca197d287d274d0b6cb5d6f8f8f82d434ed288f962539ff18cc9012f9ea3"] +attrs = ["69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79", "f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399"] +cachetools = ["428266a1c0d36dc5aca63a2d7c5942e88c2c898d72139fca0e97fdd2380517ae", "8ea2d3ce97850f31e4a08b0e2b5e6c34997d7216a9d2c98e0f3978630d4da69a"] +certifi = ["046832c04d4e752f37383b628bc601a7ea7211496b4638f6514d0e5b9acc4939", "945e3ba63a0b9f577b1395204e13c3a231f9bc0223888be653286534e5873695"] +chardet = ["84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", "fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"] +dataclasses = ["454a69d788c7fda44efd71e259be79577822f5e3f53f029a22d08004e951dc9f", "6988bd2b895eef432d562370bb707d540f32f7360ab13da45340101bc2307d84"] +dazl = ["28f5e6871b9241000f4489d74aff675370982c10b9d48cbcc17c5c77f2cb0d56", "9072822197466e24a09b3c939d3e1710f45905dfe78612dce2bf86d179448d75"] +google-auth = ["0f7c6a64927d34c1a474da92cfc59e552a5d3b940d3266606c6a28b72888b9e4", "20705f6803fd2c4d1cc2dcb0df09d4dfcb9a7d51fd59e94a3a28231fd93119ed"] +grpcio = ["1303578092f1f6e4bfbc354c04ac422856c393723d3ffa032fff0f7cb5cfd693", "229c6b313cd82bec8f979b059d87f03cc1a48939b543fe170b5a9c5cf6a6bc69", "3cd3d99a8b5568d0d186f9520c16121a0f2a4bcad8e2b9884b76fb88a85a7774", "41cfb222db358227521f9638a6fbc397f310042a4db5539a19dea01547c621cd", "43330501660f636fd6547d1e196e395cd1e2c2ae57d62219d6184a668ffebda0", "45d7a2bd8b4f25a013296683f4140d636cdbb507d94a382ea5029a21e76b1648", "47dc935658a13b25108823dabd010194ddea9610357c5c1ef1ad7b3f5157ebee", "480aa7e2b56238badce0b9413a96d5b4c90c3bfbd79eba5a0501e92328d9669e", "4a0934c8b0f97e1d8c18e76c45afc0d02d33ab03125258179f2ac6c7a13f3626", "5624dab19e950f99e560400c59d87b685809e4cfcb2c724103f1ab14c06071f7", "60515b1405bb3dadc55e6ca99429072dad3e736afcf5048db5452df5572231ff", "610f97ebae742a57d336a69b09a9c7d7de1f62aa54aaa8adc635b38f55ba4382", "64ea189b2b0859d1f7b411a09185028744d494ef09029630200cc892e366f169", "686090c6c1e09e4f49585b8508d0a31d58bc3895e4049ea55b197d1381e9f70f", "7745c365195bb0605e3d47b480a2a4d1baa8a41a5fd0a20de5fa48900e2c886a", "79491e0d2b77a1c438116bf9e5f9e2e04e78b78524615e2ce453eff62db59a09", "825177dd4c601c487836b7d6b4ba268db59787157911c623ba59a7c03c8d3adc", "8a060e1f72fb94eee8a035ed29f1201ce903ad14cbe27bda56b4a22a8abda045", "90168cc6353e2766e47b650c963f21cfff294654b10b3a14c67e26a4e3683634", "94b7742734bceeff6d8db5edb31ac844cb68fc7f13617eca859ff1b78bb20ba1", "962aebf2dd01bbb2cdb64580e61760f1afc470781f9ecd5fe8f3d8dcd8cf4556", "9c8d9eacdce840b72eee7924c752c31b675f8aec74790e08cff184a4ea8aa9c1", "af5b929debc336f6bab9b0da6915f9ee5e41444012aed6a79a3c7e80d7662fdf", "b9cdb87fc77e9a3eabdc42a512368538d648fa0760ad30cf97788076985c790a", "c5e6380b90b389454669dc67d0a39fb4dc166416e01308fcddd694236b8329ef", "d60c90fe2bfbee735397bf75a2f2c4e70c5deab51cd40c6e4fa98fae018c8db6", "d8582c8b1b1063249da1588854251d8a91df1e210a328aeb0ece39da2b2b763b", "ddbf86ba3aa0ad8fed2867910d2913ee237d55920b55f1d619049b3399f04efc", "e46bc0664c5c8a0545857aa7a096289f8db148e7f9cca2d0b760113e8994bddc", "f6437f70ec7fed0ca3a0eef1146591bb754b418bb6c6b21db74f0333d624e135", "f71693c3396530c6b00773b029ea85e59272557e9bd6077195a6593e4229892a", "f79f7455f8fbd43e8e9d61914ecf7f48ba1c8e271801996fef8d6a8f3cc9f39f"] +idna = ["c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", "ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c"] +idna-ssl = ["a933e3bb13da54383f9e8f35dc4f9cb9eb9b3b78c6b36f311254d6d0d92c6c7c"] +multidict = ["024b8129695a952ebd93373e45b5d341dbb87c17ce49637b34000093f243dd4f", "041e9442b11409be5e4fc8b6a97e4bcead758ab1e11768d1e69160bdde18acc3", "045b4dd0e5f6121e6f314d81759abd2c257db4634260abcfe0d3f7083c4908ef", "047c0a04e382ef8bd74b0de01407e8d8632d7d1b4db6f2561106af812a68741b", "068167c2d7bbeebd359665ac4fff756be5ffac9cda02375b5c5a7c4777038e73", "148ff60e0fffa2f5fad2eb25aae7bef23d8f3b8bdaf947a65cdbe84a978092bc", "1d1c77013a259971a72ddaa83b9f42c80a93ff12df6a4723be99d858fa30bee3", "1d48bc124a6b7a55006d97917f695effa9725d05abe8ee78fd60d6588b8344cd", "31dfa2fc323097f8ad7acd41aa38d7c614dd1960ac6681745b6da124093dc351", "34f82db7f80c49f38b032c5abb605c458bac997a6c3142e0d6c130be6fb2b941", "3d5dd8e5998fb4ace04789d1d008e2bb532de501218519d70bb672c4c5a2fc5d", "4a6ae52bd3ee41ee0f3acf4c60ceb3f44e0e3bc52ab7da1c2b2aa6703363a3d1", "4b02a3b2a2f01d0490dd39321c74273fed0568568ea0e7ea23e02bd1fb10a10b", "4b843f8e1dd6a3195679d9838eb4670222e8b8d01bc36c9894d6c3538316fa0a", "5de53a28f40ef3c4fd57aeab6b590c2c663de87a5af76136ced519923d3efbb3", "61b2b33ede821b94fa99ce0b09c9ece049c7067a33b279f343adfe35108a4ea7", "6a3a9b0f45fd75dc05d8e93dc21b18fc1670135ec9544d1ad4acbcf6b86781d0", "76ad8e4c69dadbb31bad17c16baee61c0d1a4a73bed2590b741b2e1a46d3edd0", "7ba19b777dc00194d1b473180d4ca89a054dd18de27d0ee2e42a103ec9b7d014", "7c1b7eab7a49aa96f3db1f716f0113a8a2e93c7375dd3d5d21c4941f1405c9c5", "7fc0eee3046041387cbace9314926aa48b681202f8897f8bff3809967a049036", "8ccd1c5fff1aa1427100ce188557fc31f1e0a383ad8ec42c559aabd4ff08802d", "8e08dd76de80539d613654915a2f5196dbccc67448df291e69a88712ea21e24a", "c18498c50c59263841862ea0501da9f2b3659c00db54abfbf823a80787fde8ce", "c49db89d602c24928e68c0d510f4fcf8989d77defd01c973d6cbe27e684833b1", "ce20044d0317649ddbb4e54dab3c1bcc7483c78c27d3f58ab3d0c7e6bc60d26a", "d1071414dd06ca2eafa90c85a079169bfeb0e5f57fd0b45d44c092546fcd6fd9", "d3be11ac43ab1a3e979dac80843b42226d5d3cccd3986f2e03152720a4297cd7", "db603a1c235d110c860d5f39988ebc8218ee028f07a7cbc056ba6424372ca31b"] +oauthlib = ["bee41cc35fcca6e988463cacc3bcb8a96224f470ca547e697b604cc697b2f889", "df884cd6cbe20e32633f1db1072e9356f53638e4361bef4e8b03c9127c9328ea"] +protobuf = ["00a1b0b352dc7c809749526d1688a64b62ea400c5b05416f93cfb1b11a036295", "01acbca2d2c8c3f7f235f1842440adbe01bbc379fa1cbdd80753801432b3fae9", "0a795bca65987b62d6b8a2d934aa317fd1a4d06a6dd4df36312f5b0ade44a8d9", "0ec035114213b6d6e7713987a759d762dd94e9f82284515b3b7331f34bfaec7f", "31b18e1434b4907cb0113e7a372cd4d92c047ce7ba0fa7ea66a404d6388ed2c1", "32a3abf79b0bef073c70656e86d5bd68a28a1fbb138429912c4fc07b9d426b07", "55f85b7808766e5e3f526818f5e2aeb5ba2edcc45bcccede46a3ccc19b569cb0", "64ab9bc971989cbdd648c102a96253fdf0202b0c38f15bd34759a8707bdd5f64", "64cf847e843a465b6c1ba90fb6c7f7844d54dbe9eb731e86a60981d03f5b2e6e", "917c8662b585470e8fd42f052661fc66d59fccaae450a60044307dcbf82a3335", "afed9003d7f2be2c3df20f64220c30faec441073731511728a2cb4cab4cd46a6", "b883d7eb129b1b57c5128146bc7c2d1f15de457e96a549827fbee6f26eeedc46", "bf8e05d638b585d1752c5a84247134a0350d3a8b73d3632489a014a9f6f1e758", "d831b047bd69becaf64019a47179eb22118a50dd008340655266a906c69c6417", "de2760583ed28749ff885789c1cbc6c9c06d6de92fc825740ab99deb2f25ea4d", "eabc4cf1bc19689af8022ba52fd668564a8d96e0d08f3b4732d26a64255216a4", "fcff6086c86fb1628d94ea455c7b9de898afc50378042927a59df8065a79a549"] +pyasn1 = ["1321d4b2f051410fe7302bb1619903d30b24ba1451d019c11d242d11b2a35444", "2860a047f666afd23b197a65f33145313511c368ce919b2d9b1853ffd3e9d32d", "2919babd43b3b44247c23201b71072c0c65a636daa595cad5bcd276094dbfc2d", "437a23121602c0bb6c65320b27e31e334ffd73a9ca5c6c075b66b6270b1a8184", "5a89df3c62688261e27439d5715fd0d3ca6bf7bf1067e2171642e92aff17e817", "62cdade8b5530f0b185e09855dd422bc05c0bbff6b72ff61381c09dac7befd8c", "67a43aec85f4ea96e72a7b22227ba7a45cf03b7297e1a53418be164bbf68335e", "813b198c169e9442f340743f77093435bf3e1de8d1731f3abc45d44afba17556", "96c44b5604e7674e53e27fce98f3fc68821d9546151b98842c27b533122649da", "a9495356ca1d66ed197a0f72b41eb1823cf7ea8b5bd07191673e8147aecf8604", "bcac468e38d16e94fee4c8f76eef1feb9a06a911e93465f2351a4140fa66d303", "c39d11c72f0e5e71faa35c8c8ef5ee9b810ec99a3c64f05133f1325fe5636bba", "f124185ccc1c1c5e782aa58d46bc28be279673a482334d70de6735d05d8b4b10"] +pyasn1-modules = ["256c234d85baf315f0e99786d812e68b816e4ee4b35bac982689198ff3df5a61", "3b350a01813f4878f4ebb3e7348d3753556b120145460a810e3121fe78925923", "43c17a83c155229839cc5c6b868e8d0c6041dba149789b6d6e28801c64821722", "525edd202cadbb014587e6e8a82a86424d4c92340222000b300cfd4041625f5a", "5965cb606a914b1b086f6ffdb9e526b5ec21cea81ba0bb75f3b807d5500dda1a", "75819dd99d1be4effd1322859ec8ac3fa7c7503fec0acbce6985b2aae41aa838", "a00100a99dcc71a97b2291fcac868a39f32a72cc54d86a4e5504b34b2f5f8584", "a480489471e67c579f49057a10879cc9a787b64a84af00ed2ed3f68a652b0197", "b3899b59d6c6b4e91e9c5278ec49c0adb971349ef9c3531ae67149e3bb0b272b", "b5e0ab3dc16f42ef0c2e5ebf51db9f1e1aa734a68a4d26a2b475a289182b697f", "bf68431a9043b35aa0a18b865ecbb19ec19f8354488ea0b3b5d9ec33cb4c2be5", "e30199a9d221f1b26c885ff3d87fd08694dbbe18ed0e8e405a2a7126d30ce4c0", "ee0eb28ad9e9c0237954b4ca4c8a91cc2e98476c1dc9a1422310332518b0dd82"] +pyyaml = ["0113bc0ec2ad727182326b61326afa3d1d8280ae1122493553fd6f4397f33df9", "01adf0b6c6f61bd11af6e10ca52b7d4057dd0be0343eb9283c878cf3af56aee4", "5124373960b0b3f4aa7df1707e63e9f109b5263eca5976c66e08b1c552d4eaf8", "5ca4f10adbddae56d824b2c09668e91219bb178a1eee1faa56af6f99f11bf696", "7907be34ffa3c5a32b60b95f4d95ea25361c951383a894fec31be7252b2b6f34", "7ec9b2a4ed5cad025c2278a1e6a19c011c80a3caaac804fd2d329e9cc2c287c9", "87ae4c829bb25b9fe99cf71fbb2140c448f534e24c998cc60f39ae4f94396a73", "9de9919becc9cc2ff03637872a440195ac4241c80536632fffeb6a1e25a74299", "a5a85b10e450c66b49f98846937e8cfca1db3127a9d5d1e31ca45c3d0bef4c5b", "b0997827b4f6a7c286c01c5f60384d218dca4ed7d9efa945c3e1aa623d5709ae", "b631ef96d3222e62861443cc89d6563ba3eeb816eeb96b2629345ab795e53681", "bf47c0607522fdbca6c9e817a6e81b08491de50f3766a7a0e6a5be7905961b41", "f81025eddd0327c7d4cfe9b62cf33190e1e736cc6e97502b3ec425f574b3e7a8"] +requests = ["11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4", "9cf5292fcd0f598c671cfc1e0d7d1a7f13bb8085e9a590f48c010551dc6c4b31"] +rsa = ["14ba45700ff1ec9eeb206a2ce76b32814958a98e372006c8fb76ba820211be66", "1a836406405730121ae9823e19c6e806c62bbad73f890574fff50efa4122c487"] +semver = ["41c9aa26c67dc16c54be13074c352ab666bce1fa219c7110e8f03374cd4206b0", "5b09010a66d9a3837211bb7ae5a20d10ba88f8cb49e92cb139a69ef90d5060d8"] +six = ["3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73"] +toposort = ["d80128b83b411d503b0cdb4a8f172998bc1d3b434b6402a349b8ebd734d51a80", "dba5ae845296e3bf37b042c640870ffebcdeb8cd4df45adaa01d8c5476c557dd"] +typing = ["91dfe6f3f706ee8cc32d38edbbf304e9b7583fb37108fef38229617f8b3eba23", "c8cabb5ab8945cd2f54917be357d134db9cc1eb039e59d1606dc1e60cb1d9d36", "f38d83c5a7a7086543a0f649564d661859c5146a85775ab90c0d2f93ffaa9714"] +typing-extensions = ["2ed632b30bb54fc3941c382decfd0ee4148f5c591651c9272473fea2c6397d95", "b1edbbf0652660e32ae780ac9433f4231e7339c7f9a8057d0f042fcbcea49b87", "d8179012ec2c620d3791ca6fe2bf7979d979acdbef1fca0bc56b37411db682ed"] +urllib3 = ["b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1", "dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232"] +yarl = ["024ecdc12bc02b321bc66b41327f930d1c2c543fa9a561b39861da9388ba7aa9", "2f3010703295fbe1aec51023740871e64bb9664c789cba5a6bdf404e93f7568f", "3890ab952d508523ef4881457c4099056546593fa05e93da84c7250516e632eb", "3e2724eb9af5dc41648e5bb304fcf4891adc33258c6e14e2a7414ea32541e320", "5badb97dd0abf26623a9982cd448ff12cb39b8e4c94032ccdedf22ce01a64842", "73f447d11b530d860ca1e6b582f947688286ad16ca42256413083d13f260b7a0", "7ab825726f2940c16d92aaec7d204cfc34ac26c0040da727cf8ba87255a33829", "b25de84a8c20540531526dfbb0e2d2b648c13fd5dd126728c496d7c3fea33310", "c6e341f5a6562af74ba55205dbd56d248daf1b5748ec48a0200ba227bb9e33f4", "c9bb7c249c4432cd47e75af3864bc02d26c9594f49c82e2a28624417f0ae63b8", "e060906c0c585565c718d1c3841747b61c5439af2211e185f6739a9412dfbde1"] diff --git a/samples/ping-pong/pyproject.toml b/samples/ping-pong/pyproject.toml new file mode 100644 index 00000000..202d056b --- /dev/null +++ b/samples/ping-pong/pyproject.toml @@ -0,0 +1,15 @@ +[tool.poetry] +name = "ping-pong" +version = "0.1.0" +description = "" +authors = ["Luciano Joublanc (DA) "] + +[tool.poetry.dependencies] +python = "^3.6" +dazl = "^6.3" + +[tool.poetry.dev-dependencies] + +[build-system] +requires = ["poetry>=0.12"] +build-backend = "poetry.masonry.api" diff --git a/samples/ping-pong/run.sh b/samples/ping-pong/run.sh deleted file mode 100755 index 0abcbe59..00000000 --- a/samples/ping-pong/run.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -daml start --start-navigator=no & -sandbox_pid=$! -trap "kill ${sandbox_pid}" SIGINT SIGTERM EXIT - -DAML_LEDGER_URL=http://localhost:6865/ DAZL_SERVER_PORT=53390 .venv/bin/python3 app.py -kill ${sandbox_pid} From c4e2d7453f014142f90d6d1881da750b9bc3b832 Mon Sep 17 00:00:00 2001 From: "Luciano Joublanc (DA)" Date: Fri, 6 Sep 2019 12:06:38 +0200 Subject: [PATCH 7/7] Fixes #47, dazl.model.reading api docs missing. --- docs/_modules/dazl/model/reading.html | 477 ++++++++++++++++++++++++++ docs/_modules/index.html | 1 + docs/dazl.html | 1 + docs/dazl.model.html | 160 ++++++++- docs/genindex.html | 73 +++- docs/index.html | 1 + docs/objects.inv | Bin 1820 -> 1957 bytes docs/searchindex.js | 2 +- python/dazl/model/reading.py | 50 +++ 9 files changed, 754 insertions(+), 11 deletions(-) create mode 100644 docs/_modules/dazl/model/reading.html diff --git a/docs/_modules/dazl/model/reading.html b/docs/_modules/dazl/model/reading.html new file mode 100644 index 00000000..1e292fe6 --- /dev/null +++ b/docs/_modules/dazl/model/reading.html @@ -0,0 +1,477 @@ + + + + + + + + dazl.model.reading + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ dazl + +
+ +
+ +

Source code for dazl.model.reading

+# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+# TODO: `automodule reading` directive doesn't appear to work here, have to list each class individually.
+"""
+Read-Side Types
+---------------
+
+This module contains models used on the read-side of the Ledger API.
+
+.. autoclass:: InitEvent
+  :members:
+
+.. autoclass::  InitEvent
+  :members:
+
+.. autoclass::  OffsetEvent
+  :members:
+
+.. autoclass::  ReadyEvent
+  :members:
+
+.. autoclass::  ActiveContractSetEvent
+  :members:
+
+.. autoclass::  BaseTransactionEvent
+  :members:
+
+.. autoclass::  TransactionStartEvent
+  :members:
+
+.. autoclass::  TransactionEndEvent
+  :members:
+
+.. autoclass::  ContractEvent
+  :members:
+
+.. autoclass::  ContractCreateEvent
+  :members:
+
+.. autoclass::  ContractExercisedEvent
+  :members:
+
+.. autoclass::  ContractArchiveEvent
+  :members:
+
+.. autoclass::  PackagesAddedEvent
+  :members:
+
+.. autoclass::  TransactionFilter
+  :members:
+
+.. autoclass::  EventKey
+  :members:
+
+"""
+
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any, Callable, Collection, Optional, Sequence, TypeVar, Union, Tuple
+
+from .core import ContractId, ContractData, ContractContextualData, Party
+from .lookup import template_reverse_globs, validate_template
+from .types import Type, TypeReference
+from .types_store import PackageStore
+
+
+T = TypeVar('T')
+
+
+@dataclass(frozen=True)
+class BaseEvent:
+    """
+    Superclass of all dazl events.
+    """
+
+    client: 'Any'
+    party: Optional[Party]
+    time: Optional[datetime]
+    ledger_id: str
+    package_store: PackageStore
+
+    def acs_find_active(self, template: Union[TypeReference, str], match=None):
+        return self.client.find_active(template, match)
+
+    def acs_find_by_id(self, cid: Union[str, ContractId]) -> Optional[ContractContextualData]:
+        return self.client.find_by_id(cid)
+
+    def acs_find_one(self, template: Union[TypeReference, str], match=None):
+        return self.client.find_one(template, match=match)
+
+    def acs_find_historical(self, template: Union[TypeReference, str], match=None):
+        return self.client.find_historical(template, match)
+
+    def acs_find_nonempty(self, template: Union[TypeReference, str], match=None):
+        return self.client.find_nonempty(template, match=match)
+
+    def __repr__(self):
+        fields = ', '.join(f"{k}={v!r}" for k, v in self.__dict__.items()
+                           if not k.startswith('_') and k != 'client' and k != 'package_store' and
+                           k != 'ledger_id')
+        return f'{self.__class__.__name__}({fields})'
+
+
+
[docs]@dataclass(frozen=True) +class InitEvent(BaseEvent): + """ + Event raised when dazl is initialized, but before it has begun reading from the Active Contract + Set (ACS). + """
+ + +
[docs]@dataclass(frozen=True) +class OffsetEvent(BaseEvent): + """ + Event raised when dazl is ready to begin processing new events. At this point, the Active + Contract Set (ACS) is populated with the current state of the ledger. + """ + + offset: str
+ + +
[docs]@dataclass(frozen=True) +class ReadyEvent(OffsetEvent): + """ + Event raised when dazl is ready to begin processing new events. At this point, the Active + Contract Set (ACS) is populated with the current state of the ledger. + """
+ + +
[docs]@dataclass(frozen=True) +class ActiveContractSetEvent(OffsetEvent): + """ + Event raised on initial read of the active contract set. + """ + contract_events: 'Sequence[ContractCreateEvent]'
+ + +
[docs]@dataclass(frozen=True) +class BaseTransactionEvent(OffsetEvent): + """ + Event raised when dazl encounters a new transaction. This is raised before any corresponding + :class:`ContractCreateEvent` or :class:`ContractArchiveEvent`. + """ + command_id: str + workflow_id: str
+ + +
[docs]@dataclass(frozen=True) +class TransactionStartEvent(BaseTransactionEvent): + """ + Event raised when dazl encounters a new transaction. This is raised before any corresponding + :class:`ContractCreateEvent` or :class:`ContractArchiveEvent`. + """ + contract_events: 'Sequence[ContractEvent]'
+ + +
[docs]@dataclass(frozen=True) +class TransactionEndEvent(BaseTransactionEvent): + """ + Event raised when dazl encounters the end of a transaction. This is raised after any + corresponding :class:`ContractCreateEvent` or :class:`ContractArchiveEvent`. + """ + contract_events: 'Sequence[ContractEvent]'
+ + +
[docs]@dataclass(frozen=True) +class ContractEvent(BaseTransactionEvent): + """ + Event raised when dazl automation detects a new create or an archive. The Active Contract Set + (ACS) reflects this event, as well as all other events that occurred in the same transaction. + """ + cid: ContractId + cdata: ContractData + command_id: str + workflow_id: str + event_id: str + witness_parties: Sequence[str]
+ + +
[docs]@dataclass(frozen=True) +class ContractCreateEvent(ContractEvent): + """ + Event raised when dazl automation detects a contract create. The Active Contract Set + (ACS) reflects this event, as well as all other events that occurred in the same transaction. + """
+ + +
[docs]@dataclass(frozen=True) +class ContractExercisedEvent(ContractEvent): + """ + Event raised when dazl automation detects a contract exercised. + """ + contract_creating_event_id: str + choice: str + choice_args: Any + acting_parties: Sequence[str] + consuming: True + child_event_ids: Sequence[str]
+ + +
[docs]@dataclass(frozen=True) +class ContractArchiveEvent(ContractEvent): + """ + Event raised when dazl automation detects a contract archive. The Active Contract Set + (ACS) reflects this event, as well as all other events that occurred in the same transaction. + """
+ + +
[docs]@dataclass(frozen=True) +class PackagesAddedEvent(BaseEvent): + """ + Event raised when new packages have been detected. + """ + initial: bool
+ + +def create_dispatch( + on_init: Callable[[InitEvent], T], + on_ready: Callable[[ReadyEvent], T], + on_offset: Callable[[OffsetEvent], T], + on_transaction_start: Callable[[TransactionStartEvent], T], + on_transaction_end: Callable[[TransactionEndEvent], T], + on_contract_created: Callable[[ContractCreateEvent], T], + on_contract_exercised: Callable[[ContractExercisedEvent], T], + on_contract_archived: Callable[[ContractArchiveEvent], T], + on_packages_added: Callable[[PackagesAddedEvent], T]) \ + -> Callable[[BaseEvent], T]: + def handle(event: BaseEvent) -> T: + if isinstance(event, ContractCreateEvent): + return on_contract_created(event) + elif isinstance(event, ContractExercisedEvent): + return on_contract_exercised(event) + elif isinstance(event, ContractArchiveEvent): + return on_contract_archived(event) + elif isinstance(event, TransactionStartEvent): + return on_transaction_start(event) + elif isinstance(event, TransactionEndEvent): + return on_transaction_end(event) + elif isinstance(event, ReadyEvent): + return on_ready(event) + elif isinstance(event, InitEvent): + return on_init(event) + elif isinstance(event, OffsetEvent): + return on_offset(event) + elif isinstance(event, PackagesAddedEvent): + return on_packages_added(event) + else: + raise ValueError(f'unknown subclass of BaseEvent: {event!r}') + + return handle + + +
[docs]@dataclass(frozen=True) +class TransactionFilter: + ledger_id: str + current_offset: Optional[str] + destination_offset: Optional[str] + templates: Optional[Collection[Type]] + max_blocks: Optional[int] + party_groups: Optional[Collection[str]]
+ + +
[docs]class EventKey: + + from_event = create_dispatch( + on_init=lambda _: EventKey.init(), + on_ready=lambda _: EventKey.ready(), + on_offset=lambda _: EventKey.offset(), + on_transaction_start=lambda _: EventKey.transaction_start(), + on_transaction_end=lambda _: EventKey.transaction_end(), + on_contract_created=lambda event: EventKey.contract_created(False, event.cid.template_id), + on_contract_exercised=lambda event: EventKey.contract_exercised( + False, event.cid.template_id, event.choice), + on_contract_archived=lambda event: EventKey.contract_archived(False, event.cid.template_id), + on_packages_added=lambda event: EventKey.packages_added( + initial=event.initial, changed=not event.initial)) + +
[docs] @staticmethod + def init() -> Collection[str]: + """ + Return the names of events that get raised in response to an :class:`InitEvent`. This is + currently only ``'init'``. + """ + return 'init',
+ +
[docs] @staticmethod + def ready() -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`ReadyEvent`. This is + currently only ``'ready'``. + """ + return 'ready',
+ +
[docs] @staticmethod + def offset() -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`OffsetEvent`. This is + currently only ``'offset'``. + """ + return 'offset',
+ +
[docs] @staticmethod + def transaction_start() -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`TransactionStartEvent`. + This is currently only ``'transaction-start'``. + """ + return 'transaction-start',
+ +
[docs] @staticmethod + def transaction_end() -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`TransactionEndEvent`. + This is currently only ``'transaction-end'``. + """ + return 'transaction-end',
+ +
[docs] @staticmethod + def contract_created(primary_only: bool, template: Any) -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`ContractCreateEvent` + of the specified template type. + """ + return EventKey._contract(primary_only, 'create', template)
+ +
[docs] @staticmethod + def contract_exercised(primary_only: bool, template: Any, choice: Any) -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`ContractExercisedEvent` + of the specified choice. + """ + return [f'{key}/{choice}' + for key in EventKey._contract(primary_only, 'exercised', template)]
+ +
[docs] @staticmethod + def contract_archived(primary_only: bool, template: Any) -> Collection[str]: + """ + Return the names of events that get raised in response to a :class:`ContractCreateEvent` + of the specified template type. + """ + return EventKey._contract(primary_only, 'archive', template)
+ + @staticmethod + def packages_added(initial: bool, changed: bool) -> 'Collection[str]': + keys = [] + if initial: + keys.append('packages-added/initial') + if changed: + keys.append('packages-added/changed') + return tuple(keys) + + @staticmethod + def _contract(primary_only: bool, prefix: str, template: Any) -> Collection[str]: + m, t = validate_template(template) + return tuple(f'{prefix}/{g}' for g in template_reverse_globs(primary_only, m, t))
+ + +def max_offset(offsets: 'Collection[str]') -> 'Optional[str]': + """ + Return the most "recent" offset from a collection of offsets. + + :param offsets: A collection of offsets to examine. + :return: The largest offset, or ``None`` if unknown. + """ + return max(offsets, key=sortable_offset_height) if offsets else None + + +def sortable_offset_height(value: str) -> int: + if value: + components = value.split('-', 3) + if len(components) == 1: + return int(value) + elif len(components) >= 1: + return int(components[1]) + return 0 +
+ +
+ + + + + + + + + + + + + + + + +
+
+ + \ No newline at end of file diff --git a/docs/_modules/index.html b/docs/_modules/index.html index 53b6dacd..e0861ef7 100644 --- a/docs/_modules/index.html +++ b/docs/_modules/index.html @@ -70,6 +70,7 @@

All modules for which code is available

  • dazl.client.api
  • dazl.client.bots
  • dazl.model.core
  • +
  • dazl.model.reading
  • dazl.model.types
  • dazl.model.writing
  • dazl.pretty
  • diff --git a/docs/dazl.html b/docs/dazl.html index 864f9912..20b14ca5 100644 --- a/docs/dazl.html +++ b/docs/dazl.html @@ -106,6 +106,7 @@

    Subpackagesdazl.damlsdk package
  • dazl.model package diff --git a/docs/dazl.model.html b/docs/dazl.model.html index 9f6d2f4b..fcf38c56 100644 --- a/docs/dazl.model.html +++ b/docs/dazl.model.html @@ -66,6 +66,7 @@
  • dazl.damlsdk package
  • dazl.model package @@ -163,7 +164,164 @@

    Core types

    Types that describe the behavior of the ledger itself.

    -

    This module contains models used on the read-side of the Ledger API.

    +
    +

    Read-Side Types

    +

    This module contains models used on the read-side of the Ledger API.

    +
    +
    +class dazl.model.reading.InitEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore)[source]
    +

    Event raised when dazl is initialized, but before it has begun reading from the Active Contract +Set (ACS).

    +
    + +
    +
    +class dazl.model.reading.InitEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore)[source]
    +

    Event raised when dazl is initialized, but before it has begun reading from the Active Contract +Set (ACS).

    +
    + +
    +
    +class dazl.model.reading.OffsetEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str)[source]
    +

    Event raised when dazl is ready to begin processing new events. At this point, the Active +Contract Set (ACS) is populated with the current state of the ledger.

    +
    + +
    +
    +class dazl.model.reading.ReadyEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str)[source]
    +

    Event raised when dazl is ready to begin processing new events. At this point, the Active +Contract Set (ACS) is populated with the current state of the ledger.

    +
    + +
    +
    +class dazl.model.reading.ActiveContractSetEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, contract_events: Sequence[ContractCreateEvent])[source]
    +

    Event raised on initial read of the active contract set.

    +
    + +
    +
    +class dazl.model.reading.BaseTransactionEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str)[source]
    +

    Event raised when dazl encounters a new transaction. This is raised before any corresponding +ContractCreateEvent or ContractArchiveEvent.

    +
    + +
    +
    +class dazl.model.reading.TransactionStartEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, contract_events: Sequence[ContractEvent])[source]
    +

    Event raised when dazl encounters a new transaction. This is raised before any corresponding +ContractCreateEvent or ContractArchiveEvent.

    +
    + +
    +
    +class dazl.model.reading.TransactionEndEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, contract_events: Sequence[ContractEvent])[source]
    +

    Event raised when dazl encounters the end of a transaction. This is raised after any +corresponding ContractCreateEvent or ContractArchiveEvent.

    +
    + +
    +
    +class dazl.model.reading.ContractEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, cid: dazl.model.core.ContractId, cdata: Dict[str, Any], event_id: str, witness_parties: Sequence[str])[source]
    +

    Event raised when dazl automation detects a new create or an archive. The Active Contract Set +(ACS) reflects this event, as well as all other events that occurred in the same transaction.

    +
    + +
    +
    +class dazl.model.reading.ContractCreateEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, cid: dazl.model.core.ContractId, cdata: Dict[str, Any], event_id: str, witness_parties: Sequence[str])[source]
    +

    Event raised when dazl automation detects a contract create. The Active Contract Set +(ACS) reflects this event, as well as all other events that occurred in the same transaction.

    +
    + +
    +
    +class dazl.model.reading.ContractExercisedEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, cid: dazl.model.core.ContractId, cdata: Dict[str, Any], event_id: str, witness_parties: Sequence[str], contract_creating_event_id: str, choice: str, choice_args: Any, acting_parties: Sequence[str], consuming: True, child_event_ids: Sequence[str])[source]
    +

    Event raised when dazl automation detects a contract exercised.

    +
    + +
    +
    +class dazl.model.reading.ContractArchiveEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, offset: str, command_id: str, workflow_id: str, cid: dazl.model.core.ContractId, cdata: Dict[str, Any], event_id: str, witness_parties: Sequence[str])[source]
    +

    Event raised when dazl automation detects a contract archive. The Active Contract Set +(ACS) reflects this event, as well as all other events that occurred in the same transaction.

    +
    + +
    +
    +class dazl.model.reading.PackagesAddedEvent(client: Any, party: Optional[NewType.<locals>.new_type], time: Optional[datetime.datetime], ledger_id: str, package_store: dazl.model.types_store.PackageStore, initial: bool)[source]
    +

    Event raised when new packages have been detected.

    +
    + +
    +
    +class dazl.model.reading.TransactionFilter(ledger_id:str, current_offset:Union[str, NoneType], destination_offset:Union[str, NoneType], templates:Union[Collection[dazl.model.types.Type], NoneType], max_blocks:Union[int, NoneType], party_groups:Union[Collection[str], NoneType])[source]
    +
    + +
    +
    +class dazl.model.reading.EventKey[source]
    +
    +
    +static contract_archived(primary_only: bool, template: Any) → Collection[str][source]
    +

    Return the names of events that get raised in response to a ContractCreateEvent +of the specified template type.

    +
    + +
    +
    +static contract_created(primary_only: bool, template: Any) → Collection[str][source]
    +

    Return the names of events that get raised in response to a ContractCreateEvent +of the specified template type.

    +
    + +
    +
    +static contract_exercised(primary_only: bool, template: Any, choice: Any) → Collection[str][source]
    +

    Return the names of events that get raised in response to a ContractExercisedEvent +of the specified choice.

    +
    + +
    +
    +static init() → Collection[str][source]
    +

    Return the names of events that get raised in response to an InitEvent. This is +currently only 'init'.

    +
    + +
    +
    +static offset() → Collection[str][source]
    +

    Return the names of events that get raised in response to a OffsetEvent. This is +currently only 'offset'.

    +
    + +
    +
    +static ready() → Collection[str][source]
    +

    Return the names of events that get raised in response to a ReadyEvent. This is +currently only 'ready'.

    +
    + +
    +
    +static transaction_end() → Collection[str][source]
    +

    Return the names of events that get raised in response to a TransactionEndEvent. +This is currently only 'transaction-end'.

    +
    + +
    +
    +static transaction_start() → Collection[str][source]
    +

    Return the names of events that get raised in response to a TransactionStartEvent. +This is currently only 'transaction-start'.

    +
    + +
    + +

    Type system types

    The dazl.model.types module contains the Python classes used to represent the DAML type diff --git a/docs/genindex.html b/docs/genindex.html index 8b3b87b5..d1cf7421 100644 --- a/docs/genindex.html +++ b/docs/genindex.html @@ -81,6 +81,7 @@

    Index

    | L | M | N + | O | P | R | S @@ -93,6 +94,8 @@

    Index

    A

      +
    • ActiveContractSetEvent (class in dazl.model.reading) +
    • add_event_handler() (dazl.client.bots.Bot method)
    • add_ledger_archived() (dazl.client.api.AIOPartyClient method) @@ -171,14 +174,16 @@

      A

      B

      - +
      -
      +

      O

      + + + +
      +

      P

      + -
      -
    • party_bots() (dazl.client.api.Network method) -
    • +
      • resume() (dazl.client.bots.Bot method)
      • RESUMING (dazl.client.bots.BotState attribute) @@ -642,10 +687,20 @@

        T

          -
        • template_id (dazl.model.core.ContractId attribute) +
        • TransactionEndEvent (class in dazl.model.reading) +
        • +
        • TransactionFilter (class in dazl.model.reading) +
        • +
        • TransactionStartEvent (class in dazl.model.reading)
        • Type (class in dazl.model.types)
        • diff --git a/docs/index.html b/docs/index.html index b61fa993..afbb9e7b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -163,6 +163,7 @@

          Table of Contentsdazl.damlsdk package
        • dazl.model package diff --git a/docs/objects.inv b/docs/objects.inv index 446d3f164fcf63e4fc22b5a1a0ed3c667409c38d..0fe4af3d6eff28f9659ce23362c5bb4ed52f3aa6 100644 GIT binary patch delta 1855 zcmV-F2f+B84y6x}dw)%Hqc{+T@A(x}&0e7<*SUEz*{Rg-B(8C?d!%HLZA}ECB$15w z*KbRF7-Qj>mVC2?-iOv#tJOeG{^L=#|5Av&<}~^oIEu^E*)#q|A*z<3y?Gb|gQqOXzQ!)tcJ-Q-8e^`CLFr3achsOSU$s znShE&MdhUi6oi$g?xrp?%|v;=b|qP<)2ztT9p%;KI$2+S6IyEL=t2490Gey0Vpv_W zczF8G#hUQD{{G|9?=ctX6I!ZT(ljUTalo)DlD(2GRsO&&)v0C$^(TRv zNu=K6M{XcbNPnKEoaS39QzEk+d!xCpNke8PDbZn(;BaKdR9Gl0nGVV8CT|L5VJ(FY z&G#XJT9Q%`>!wm#=GQ_i4RyTX8y3Jq14)fpZ!`>Ry-!&nvv#nz3CS|T!|+N`(xTG) zFf@R9gSLS@UlQ7F1$J4%-Bn0ebsaYq)J0v%JzdQ;g@0+ai3>7OZrC;mD#$`p^|}Z! z=Ne4AzQWQ{I0y7AEfo4%JhNTAQp8m8ir62iei!l;t4jzI>DC%B-|!)$G9BZGXb)F7 zz*=a9SN{^swjFldknH-rXAjErNwwI7rV7V$dImKr{79ZV|GxVF}gfIz_vsm;2<1E$VoN<Upl&paMr%n+r7a~$X%oX{TCxmF2bH`k2^ zbiG$}Aw-ES>E(D8t-aum zT+Bt4zq(a$!L5S-)bTc?Ek2`2G9f8amfQ(g({Ma_IDOY~064FN|IN=ffpIcWmw%I{ zqu$FI8zIwQN|ZhfNh?k=FEccSVA&iHW_L;xvLQy)91FY11EowBHmB9KVny}+n=64l zZF>j$N)&xQ9DT8v&XPrwknzRb*(lhT;;ruzH&~F>{YCd4(!-ja&UImEljjT!>`aDh z2F{(+ngI}-jiP>tiG^BF`@N4c3q4#0C%u&)+MmUiuDN6KGs=BI# z1h0nD|3f5$!!<^mnrAqe(C%F_jSB=?Wis^v%(TV5((V9(^a+vMx_~LIW`D*|ZWC7+q`J)^9<79?+`SaqYv#dX^E0(y zJT(q_d~6(o#smpFHI=D3^`R`NHJdFIT4ciY>05v417-5|*++akTkLM7DLtvbCW>V$ zQab;Vi!6$7qo%}GjK1367Jq81z=##5&XxVL{GNh4Cj&oKR8%yF2$|d%{OoDZn$_) to2O$=Q;+L3*8ba;Ma{#4``^Soz&;Ol*zQ0N%ZB5@BS;8>0V))Yj0_q>11Y`dg^5N$jBgLH9}$}5!d_I z?~?==W7#p1d;_8Hho@hUrw5eiKbkcAFEuY)ij&Vt2?g0!)%24sO8-jIg()m3IjsqW zXKQCv&K6{U6RGYgec*MCSgG{|MN%er6ZvIbhX3HARoL7gtA8yo=K>h2jT$K>$XcUj z0vaSF7S|e3Bf@muP0I>JIJ;cC5rnC{sLOndX>+|!wAbGRGvypTC_g)Z`WkA8uP(cP z`uUymHKGs0{imZpV6M<-n8{Y)yhQGC@L@HmctaJI;lK*3T#*`wlR%A1q)<3XhS;=3 zLhb!WZY0l8S%2mfmlYN{62+Fh<1*BwF|!aDsklgRIHDjjE|f5$V)FXQn?qS#OQA!{ zeN3Pdh)HDJRE}ABE3{NlCm6mV5iHb@T$}Zd}l=A;R;@7%<=PF{9BP6NczESAKvs zSJGeoo0EWh>$Vdt!vOm{tO){3PT_g!?Pdm0%km8u_#KNdNXrzVU{2jo?Bf}FR*3H$ z7~58re18`($dc%G1h1726S!Q=qYXlad<{?fO7Pa_2^zB99Q#4fwj4iX11ImwbZd|& zJw*hiKhER)GawG8f7tDS`R73#Fd1lB$n-oR#7T%;#CmTqE>Z*b85g;J+l`CJ&|Swx zxMvuCkr})Pxti{|6*=YmB}&{J?_9|loM*b^41X;oV{!)RpENlG^vau@vZ{EVGP{9~ zi|^lV;oBnnwVV00*#7KxzU-EMEL!tJHV1B6td;1SUO7kd&aiv{3{0||rQZArxu zp?|?340-$vkp61~A1PO4v-cEx?2Sj-R{9zZ8|v1(#iC`5u*y>n&j^LRwY>3^?hsS( zm}dKcN&3Jk#nvDAEY*YDELw(lp=KD4gt4GF7!@*)M;JXsIil1L^axI9@71|R31K%? z)&sh}E4mUQc`FK>Q(mBcti5PY?0tlo-G8E0zfk;?+4BB%_4v)(`UB+Y`FkMc*W>E- zM+D64^K&?5^>Y8~B?ji_av9vehT?6^P9RupQYX>%H*vX%gQV?Za1i3r|9W ziA2|Bx^%et7&ZKYVvdq7hkf`7Wm>iWeIYsgrZSP}Y?(vVN1MsfKM!MVAAL^6AU>@7>vg)H+;{CP56Y zPb!^aIlhBx^-DTLW!`Y9a=zJsx3$x=Q>UO#59)Mru(P}S$VA<+FUhz2q?=2WtcA7} zBI0DZ2N%f}HK_zLLBR+y6k5y=bBY%*w2oeB_Gy2it8Uk;?H~Q+l7GT-$d2oFfw#W8 z*`QCgKDGL^*QX1K^;@}PkS()jtnBrr9?#(h<5muZw*E_hI;nkXWj7$@9awQNy~Z%i z6@>S!0(;@1;JVdGt**;#DfF2w{Rr#mIVbqja6Rp=rvvB0Jx8P9ZpCz%k|h)*KTW{} z&NTymuvlM8JGGmyKQ7+dP`=A;lGJJHaUE;zzg<~kb4HJUkbaMG8SJp#fgYLPUrjCJ L%su}H@~>cWZJ%7{ diff --git a/docs/searchindex.js b/docs/searchindex.js index 49799c65..0a310310 100644 --- a/docs/searchindex.js +++ b/docs/searchindex.js @@ -1 +1 @@ -Search.setIndex({docnames:["basics","dazl","dazl.cli","dazl.client","dazl.damlast","dazl.damlsdk","dazl.model","dazl.pretty","dazl.protocols","dazl.util","glossary","index","migrating","tutorials","tutorials_message_ingester","tutorials_post_office","tutorials_workflow_state"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["basics.rst","dazl.rst","dazl.cli.rst","dazl.client.rst","dazl.damlast.rst","dazl.damlsdk.rst","dazl.model.rst","dazl.pretty.rst","dazl.protocols.rst","dazl.util.rst","glossary.rst","index.rst","migrating.rst","tutorials.rst","tutorials_message_ingester.rst","tutorials_post_office.rst","tutorials_workflow_state.rst"],objects:{"":{dazl:[1,0,0,"-"]},"dazl.cli":{ls:[2,0,0,"-"],main:[2,4,1,""],print_cmd_help:[2,4,1,""],run:[2,4,1,""]},"dazl.cli.ls":{ListAllCommand:[2,1,1,""]},"dazl.cli.ls.ListAllCommand":{execute:[2,2,1,""],name:[2,3,1,""],parser:[2,2,1,""]},"dazl.client":{api:[3,0,0,"-"],bots:[3,0,0,"-"]},"dazl.client.api":{AIOGlobalClient:[3,1,1,""],AIOPartyClient:[3,1,1,""],GlobalClient:[3,1,1,""],Network:[3,1,1,""],PartyClient:[3,1,1,""],SimpleGlobalClient:[3,1,1,""],SimplePartyClient:[3,1,1,""],simple_client:[3,4,1,""]},"dazl.client.api.AIOGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.AIOPartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.api.Network":{aio_global:[3,2,1,""],aio_party:[3,2,1,""],aio_run:[3,2,1,""],bots:[3,2,1,""],join:[3,2,1,""],parties:[3,2,1,""],party_bots:[3,2,1,""],resolved_config:[3,2,1,""],run_forever:[3,2,1,""],run_until_complete:[3,2,1,""],set_config:[3,2,1,""],shutdown:[3,2,1,""],simple_global:[3,2,1,""],simple_party:[3,2,1,""],start_in_background:[3,2,1,""]},"dazl.client.api.PartyClient":{party:[3,2,1,""],resolved_config:[3,2,1,""]},"dazl.client.api.SimpleGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.SimplePartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.bots":{Bot:[3,1,1,""],BotCollection:[3,1,1,""],BotEntry:[3,1,1,""],BotInvocation:[3,1,1,""],BotState:[3,1,1,""],wrap_as_command_submission:[3,4,1,""]},"dazl.client.bots.Bot":{add_event_handler:[3,2,1,""],entries:[3,2,1,""],event_keys:[3,2,1,""],id:[3,2,1,""],ledger_created:[3,2,1,""],name:[3,2,1,""],notify:[3,2,1,""],party:[3,2,1,""],pause:[3,2,1,""],resume:[3,2,1,""],running:[3,2,1,""],state:[3,2,1,""],stop:[3,2,1,""],wants_any_keys:[3,2,1,""]},"dazl.client.bots.BotCollection":{add_new:[3,2,1,""],add_single:[3,2,1,""],notify:[3,2,1,""],stop_all:[3,2,1,""]},"dazl.client.bots.BotEntry":{filter:[3,3,1,""],source_location:[3,3,1,""]},"dazl.client.bots.BotState":{PAUSED:[3,3,1,""],PAUSING:[3,3,1,""],RESUMING:[3,3,1,""],RUNNING:[3,3,1,""],STARTING:[3,3,1,""],STOPPED:[3,3,1,""],STOPPING:[3,3,1,""]},"dazl.model":{core:[6,0,0,"-"],ledger:[6,0,0,"-"],reading:[6,0,0,"-"],types:[6,0,0,"-"],types_store:[6,0,0,"-"],writing:[6,0,0,"-"]},"dazl.model.core":{ContractId:[6,1,1,""]},"dazl.model.core.ContractId":{contract_id:[6,3,1,""],exercise:[6,2,1,""],for_json:[6,2,1,""],replace:[6,2,1,""],template_id:[6,3,1,""]},"dazl.model.types":{ListType:[6,1,1,""],RecordType:[6,1,1,""],ScalarType:[6,1,1,""],Type:[6,1,1,""],UnsupportedType:[6,1,1,""],VariantType:[6,1,1,""]},"dazl.model.writing":{Command:[6,1,1,""],CreateCommand:[6,1,1,""],ExerciseCommand:[6,1,1,""]},"dazl.model.writing.CreateCommand":{arguments:[6,3,1,""],replace:[6,2,1,""],template:[6,3,1,""]},"dazl.model.writing.ExerciseCommand":{arguments:[6,3,1,""],choice:[6,3,1,""],contract:[6,3,1,""],replace:[6,2,1,""]},"dazl.pretty":{get_pretty_printer:[7,4,1,""],render_daml:[7,0,0,"-"],util:[7,0,0,"-"]},"dazl.protocols":{v0:[8,0,0,"-"],v1:[8,0,0,"-"]},dazl:{cli:[2,0,0,"-"],client:[3,0,0,"-"],damlast:[4,0,0,"-"],damlsdk:[5,0,0,"-"],model:[6,0,0,"-"],pretty:[7,0,0,"-"],protocols:[8,0,0,"-"],util:[9,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"],"3":["py","attribute","Python attribute"],"4":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method","3":"py:attribute","4":"py:function"},terms:{"00z":14,"01t00":14,"byte":3,"case":[3,14,15,16],"class":[2,3,6,15,16],"default":3,"enum":3,"final":[14,15,16],"float":3,"function":[3,5,9,14,15],"import":[6,11,14,15,16],"int":[0,2,3,6,15],"long":3,"new":[3,6,11,12,14,15,16],"public":3,"return":[3,6,14,15,16],"throw":3,"true":3,"try":[3,14,15,16],"while":3,ACS:[3,11],AND:3,But:15,For:[3,14,15],IDs:[3,6],NOT:3,That:14,The:[0,3,6,10,14,15,16],Then:15,There:[6,15],These:16,Use:3,Using:15,__file__:15,__init__:16,__main__:[14,15,16],__name__:[14,15,16],_asyncio:3,_base:2,_before_:3,_main:3,_network_client_impl:3,_networkimpl:3,_or_:3,_party_client_impl:3,_partyclientimpl:3,_render_bas:7,_resolve_nam:16,_run_level:3,abil:15,abl:3,about:[3,12],abov:[14,15,16],abstractset:3,accept:[15,16],accept_message_act:14,accept_the_messag:14,accept_ticket_buyer_invit:16,accept_ticket_seller_invit:16,acceptinviteauthorrol:15,acceptinvitereceiverrol:15,acceptlett:15,acceptmessag:14,acceptsentlett:15,acceptticketbuyerinvit:16,acceptticketsellerinvit:16,access:12,acknowledg:14,acknowledge_message_act:14,acknowledge_the_messag:14,acknowledgingparti:14,acknowlegedlett:15,across:12,acs_find_on:11,action:16,activ:[3,12,14,16],actual:15,add:[3,14,15,16],add_event_handl:3,add_ledger_archiv:[3,12],add_ledger_cr:[3,12],add_ledger_exercis:3,add_ledger_init:[3,12],add_ledger_packages_ad:3,add_ledger_readi:[3,12],add_ledger_transaction_end:3,add_ledger_transaction_start:3,add_new:3,add_singl:3,added:[3,15],adding:[3,15],addit:[3,6,12,15],addition:[],address:15,adject:6,admin_url:3,advanc:3,affili:[14,16],after:[3,14,15,16],afterward:15,against:[3,15],agre:16,agreement:[15,16],aid:6,aio_glob:3,aio_parti:[3,11,12],aio_run:3,aioglobalcli:3,aiopartycli:3,alic:[11,12,14,16],alice_cli:[12,14,16],all:[3,6,11,14,15,16],all_parti:15,allow:[3,15],alongsid:3,alreadi:[3,11],also:[3,14,15,16],altern:3,alwai:[6,15],amount:3,ani:[3,6],anyth:[3,15],anytim:16,apach:[14,16],api:[1,6,11,12,14,16],append:16,appli:[3,6],applic:[3,11,13],appropri:16,arbitrari:3,archiv:[3,11,14,16],arg:2,argpars:2,argument:[3,6,12,15],argumentpars:2,aris:6,around:5,arrai:3,assert:15,asset:[10,11,12,14,16],assign:[14,16],assist:5,associ:[3,14,16],assum:[6,11,14,15,16],async:[3,11,16],asynchron:[3,11],asyncio:[3,12,16],attribut:6,author:15,authorrol:15,automat:15,await:[3,11,16],background:[3,15],base:[2,3,6,12],baseev:3,basi:[14,16],basic:11,becaus:[15,16],been:[3,12,16],befor:[3,6,15,16],begin:3,behalf:3,behavior:[3,6],being:[3,6],below:0,best:16,bin:[14,16],binaryio:3,bind:16,bit:15,blank:15,block:[3,14,15,16],bob:[12,14,16],bob_client:[12,14,16],bodi:15,bool:[0,3,6],bot:[1,11],botcallback:3,botcollect:3,botentri:3,botfilt:3,both:[6,16],botinvoc:3,botstat:3,build:11,builtin:6,buyer:16,calcul:3,calculaterequest:0,calculaterespons:0,call:[3,12,14,15],callabl:3,callback:[3,11,14,15],caller:3,can:[3,6,14,15,16],cancel:16,cannot:[3,14,16],caught:3,caus:14,cdata:[12,14,15,16],certain:14,chang:[3,12],check:3,choic:[3,6,14,15],choice_argu:3,choice_nam:[3,6],choicemetadata:6,choiceref:6,cid:[3,12,14,15,16],clearli:16,cli:[1,11],clicommand:2,client:[1,6,8,10,12,14,15,16],client_mgr:[14,15,16],close:11,cmd:2,code:[3,6,14,15,16],coerc:3,coercion:6,collaps:12,collect:3,column:15,comfort:3,command:[2,3,6,11,14,15,16],commandbuild:3,commandpayload:3,commit:[14,16],common:3,commun:3,complet:[3,16],composit:6,comput:0,config:3,configur:[3,14],connect:[3,11,14,15],consist:12,construct:6,constructor:[0,6],consum:[14,15],contain:[0,1,3,6,7,8,12,14,16],content:15,contextmanag:3,contextu:3,contract:[3,6,11,12,14,15,16],contract_dict:11,contract_id:6,contract_kei:3,contract_stor:16,contractarchiveev:3,contractcontextualdata:3,contractcontextualdatacollect:3,contractcreateev:3,contractexercisedev:3,contractid:[0,3,6,14,15,16],contractstor:16,control:[14,15,16],conveni:[3,15],convent:12,convert:3,copyright:[14,16],core:[0,1,3,11],coroutin:3,correct:3,correspond:[3,14],could:15,cours:14,creat:[3,6,11,13,14,16],create_and_exercis:3,create_cli:[12,14,15,16],create_futur:16,create_if_miss:3,create_initial_workflow_st:16,createa:14,createcommand:6,createdecimallett:15,createintlett:15,createlett:15,createlistintlett:15,createtimelett:15,creation:[14,16],critic:16,ctrl:3,currenc:[],currency_cid:[],current:[3,6],custom:14,daemon:3,dalf:3,damast:[1,11],daml:[0,5,6,11,13],daml_fil:15,daml_ledger_parti:3,daml_ledger_url:3,damlsdk:[1,11],dar:3,data:[0,3,12],date:[0,3],datetim:[0,3],dazl:[0,10,12,14,15,16],deactiv:15,debug:16,decim:[0,3,6,15],declar:3,decor:3,def:[11,14,15,16],defin:[6,14,15,16],del:16,delet:16,deliv:15,demonstr:16,depend:16,deploi:[14,16],describ:[6,14,16],descript:6,design:[14,16],detect:[3,14,16],develop:[15,16],dict:[0,3,6,15,16],dictionari:[0,3],differ:[8,16],difficult:15,digit:[10,11,14,16],directli:[3,6],dirnam:15,disabl:3,disambigu:6,dish:15,dispatch:3,dispos:15,doc_begin:[14,16],doc_end:[14,16],doe:3,domain:6,don:6,done:[3,14,16],down:[3,15],download:[14,16],drain:3,drawn:15,dump_al:[14,15,16],dure:14,each:[14,15,16],easier:16,easili:15,either:[3,6,15],els:[15,16],empti:0,encapsul:16,encount:3,ensur:3,ensure_dar:3,ensure_packag:3,entir:3,entri:3,environ:3,equival:3,error:3,eustac:[],even:15,event:[3,6,11,14,15,16],event_kei:3,eventkei:3,eventu:6,ever:6,everi:15,everyth:15,exampl:[0,11,13,14,15],except:[3,15],execut:[2,3,12,14,15,16],exercis:[3,6,14,15,16],exercise_by_kei:3,exercisecommand:6,exist:[3,6],exit:[3,15,16],exit_cod:[14,15,16],expect:6,expos:[3,5,9,15],expr:0,express:0,factori:3,fals:[3,16],fashion:3,fetch:[3,15],few:15,field:[0,3,6],file:[14,16],filter:3,filter_fn:3,find:[3,16],find_act:[3,11],find_by_id:3,find_histor:3,find_nonempti:3,find_on:3,finish:16,first:[15,16],five:15,flight:3,focu:15,follow:[0,3,14,15,16],for_json:6,format:[7,8,15],formerli:12,forward:[14,16],framework:14,frequent:6,friend:15,friendli:3,from:[3,6,11,12,14,15,16],from_ev:3,fulli:[3,11,15],function_accept_invit:16,function_ingest_the_messag:14,function_multi_creation_depend:16,further:15,futur:[3,16],gener:[3,5,9,14],genesi:[14,16],genesis_contract:14,genesiscontract:16,get:[3,16],get_event_loop:16,get_pretty_print:7,get_tim:3,getlogg:16,gettim:14,give:3,given:[3,16],global:[3,16],globalcli:3,glossari:11,gmbh:[14,16],gracefulli:3,grant:15,grpcio:[],guarante:[3,16],handl:[3,11],handler:[2,3,12,14,15,16],happen:[12,14,15],has:[3,12,14,16],have:[3,11,12,14,15,16],head:3,height:[14,16],hello:11,helper:15,here:[6,14,16],hidden:3,high:3,higher:3,histor:3,how:[14,16],howev:[14,16],http:[11,12,14,16],ident:3,identifi:[3,6,14,16],if_miss:3,ignor:15,immedi:[3,15],impl:3,implement:[3,8,11,14,16],include_archiv:3,incorpor:3,indefinit:3,index:15,indic:[14,15],individu:3,info:[3,16],inform:12,infrastructur:3,ingest:[11,13,16],ingest_messag:14,ingest_the_messag:14,ingestmessag:14,initev:3,initi:[3,11,15,16],input:14,inspect:[11,13],inspector:[14,15,16],instal:3,install_signal_handl:3,instanc:[3,6,15],instanti:[3,6,15],instead:[3,15],instruct:3,integ:0,interact:[1,3],interfac:3,intermedi:16,intern:15,introduc:15,invit:[15,16],invite_ticket_buy:16,invite_ticket_sel:16,inviteasauthor:15,inviteasreceiv:15,inviteauthorrol:15,inviteparticip:15,inviteparticipantsinprogress:16,invitereceiverrol:15,inviteticketbuy:16,inviteticketsel:16,invoc:3,invok:[3,6,14],involv:[6,14,16],is_match:16,isinst:16,issuer:11,item:16,iter:15,its:[6,14,15,16],itself:6,join:[3,15,16],json:6,just:6,keep:15,kei:[0,3,15,16],kind:6,know:6,known:[2,3],kwarg:3,lambda:[12,15],lane:15,lastli:15,later:[11,15],least:3,ledger:[1,3,6,10,11,12,13,14,16],ledger_arch:3,ledger_archiv:3,ledger_cr:3,ledger_exercis:3,ledger_init:3,ledger_packages_ad:3,ledger_readi:[3,11],ledger_run:[14,15,16],ledger_transaction_end:3,ledger_transaction_start:3,ledgercaptureplugin:[14,15,16],ledgerclientmanag:15,ledgermetadata:3,leger:14,length:[0,3],let:15,letter:[11,13],level:[3,6],librari:[3,6,8,10],licens:[14,16],like:15,line:[2,14],list:[0,3,6,14,15,16],listallcommand:2,listen:[3,11,15],listtyp:6,liter:3,live:[14,16],load:11,local:3,localhost:[11,12,14,16],log:[3,16],log_level:3,logger:3,logic:3,longer:[15,16],lookup:16,loop:[3,16],low:6,made:3,mai:[3,16],main:[2,3,11,15],make:15,manag:[3,12,15],manipul:3,manner:[14,16],manual:15,map:0,mark:16,market:15,match:[3,16],maximum:3,mean:3,member:[6,15],member_cli:15,member_party_count:15,messag:[11,13,16],message_ingest:14,messageingest:14,messageingestertest:14,metadata:[3,12],method:[3,6,15],metric:3,metricev:3,migrat:11,mileston:16,min_count:3,minimum:[3,15],model:[0,1,3,7,11,13],modul:[5,6,7,9,11,14,15,16],more:[3,12,14,15,16],most:[3,6,15],move:[14,16],multi:16,multipl:16,must:[6,15,16],name:[0,2,3,6,11,14,15,16],named_arg:6,namedargumentlist:6,nativ:3,necessari:3,need:[3,6,11],network:[3,11,12],networkconfig:3,new_client:[14,15,16],new_datetim:3,new_typ:3,newli:3,newtyp:3,next:16,node:15,non:[3,14],nonconsum:15,none:[3,6,16],nonetyp:3,normal:3,note:[3,6,14,16],notic:15,notif:3,notifi:3,notion:3,now:[3,12,15],num:0,number:3,object:3,occur:[3,14,15,16],off:[3,6],offer_ticket_purchase_agr:16,offerticketpurchaseagr:16,offic:[11,13],old:12,omit:3,on_archiv:[3,12],on_creat:[3,12,14,15,16],on_init:12,on_init_metadata:12,on_readi:[3,12,14,15],on_something_of_valu:[],onc:15,one:[2,3,14,15,16],onli:[3,14,16],onreadi:11,oper:[3,14,15,16],operator_cli:16,operatorrol:14,operatorrolecid:14,option:[3,6,7],order:[3,12,15,16],origin:[3,12],originalmessageingestedtim:14,other:[3,14,15,16],our:[14,16],out:[3,15],outgo:3,output:[3,11,13,15],over:[14,16],owner:11,packag:[11,12],package_id:3,packagesaddedev:3,packagestor:7,param:16,paramet:[3,6,12,14,15],parser:2,parti:[0,3,11,12,14,15,16],particip:[11,13,16],participant_url:[12,14,15,16],participantledgercli:15,party_bot:3,party_cli:3,party_nam:12,partycli:3,partyconfig:3,pass:[6,14],path:[3,15],pathlib:3,paus:3,perform:[14,16],perman:3,perspect:3,phase:16,platflorm:[14,16],platform:[14,16],plugin:[14,15,16],poetri:11,point:[15,16],popen:16,popul:3,port:16,possibl:3,post:[11,13],postman:[11,13],postman_cli:15,postman_parti:15,postmanrol:15,potenti:3,practic:16,pre:6,predecessor:6,prefer:3,present:[3,16],pretti:[1,11],prettyopt:7,prettyprintbas:7,primari:3,print:[7,11,12,15],print_cmd_help:2,proce:16,process:[3,6,15,16],produc:[14,16],product:[0,15],progress:[15,16],project:[14,16],prompt:[14,16],properti:3,protocol:[1,11],provid:[3,12,14,15],purchas:16,purchase_agr:16,purchase_ticket:16,purchaseticket:16,purchs:16,purpos:16,python3:[14,16],python:[0,1,6,10,13],pyyaml:[],queri:3,queu:3,queue:3,quicker:15,rais:3,ran:15,rang:15,react:[14,16],read:[3,6,11],readabl:15,readi:[3,11,15],readyev:[3,11],real:15,realpath:15,receiv:[3,15],receiveraddress:15,receivercid2:15,receivercid:15,receiverrol:15,recommend:[14,16],record:0,recordtyp:6,rectangl:0,refer:[6,14],regist:[3,12,14,15,16],register_event_handl:[14,16],registr:[3,14,15],rejectmessag:14,releas:11,reltim:0,remain:14,remot:3,remov:3,replac:[6,15],repres:[6,16],represent:6,request:[0,3],requestor:14,requestprocessingparti:14,requir:3,reserv:[14,16],resolv:[3,16],resolved_config:3,respect:16,respond:15,respons:15,restart:3,result:[6,15,16],resum:3,reus:6,right:[3,14,16],role:[15,16],rout:15,row:3,rule:6,run:[2,3,11,12,14,15,16],run_forev:[3,12],run_stat:3,run_test:15,run_until_complet:[3,11,14,15,16],runstat:3,runtim:3,safe:3,same:[6,14,16],sampl:[14,16],sample_callback_oncr:14,sample_daml_scenario_ingest_messag:14,sandbox:[11,14,15,16],save:16,save_purchase_agr:16,scalar:6,scalartyp:6,scenario:[14,16],schedul:3,script:15,sdk:[5,14,15,16],search:3,second:3,section:11,see:[3,15],self:16,seller:16,semver:[],send:[3,6,11,13],sender:15,sent:15,sentlett:15,sentlettercid2:15,sentlettercid:15,separ:15,sequenc:[3,6,14,16],sequenti:[14,16],seri:[14,16],serial:8,serv:15,server:[3,11,14,15,16],servic:3,set:[3,11,12,13,14,16],set_config:[3,11,12],set_result:16,set_tim:3,set_up:15,setinitialworkflowst:16,sever:15,shall:[14,16],should:[3,6,15],show:15,shut:3,shutdown:3,side:[1,3,11],sigint:3,signal:3,signatori:[14,15,16],sigquit:3,similar:[14,16],simpl:[2,6],simple_cli:[3,11,15],simple_glob:3,simple_parti:3,simpleglobalcli:3,simplepartycli:3,sinc:14,singl:[0,3,11,12,15,16],situat:[6,14],situt:16,skip:3,snapshot:3,snippet:14,sole:16,some:[0,3,6,11,12,13],somefield:[],sometext:[],someth:3,somethingof:[],sort:15,sortedlett:15,sourc:[2,3,6,7],source_loc:3,sourceloc:3,spdx:[14,16],specif:[0,3,6,15],specifi:[3,6,14,16],split:15,stamp:3,standard:11,start:[3,14,15,16],start_in_background:3,starter:[14,16],state:[3,11,13,14,15],stdout:[14,15,16],step:[14,15,16],stop:[3,15,16],stop_al:3,store:[3,7,12,15,16],str:[0,3,6,7],stream:6,string:6,structur:14,style:3,subclass:6,submiss:3,submit:[3,11,15,16],submit_cr:[3,11],submit_create_and_exercis:3,submit_exercis:3,submit_exercise_by_kei:3,submit_fn:3,submodul:[1,11],subpackag:11,subprocess:16,subscrib:3,subsequ:[14,16],successfulli:[3,14,15],sum:0,suppli:6,support:[3,8],sure:15,switzerland:[14,16],synchron:3,sys:15,system:[1,11],tabl:0,tag:6,take:[3,12],tbc:15,tchoos:14,tear:15,templat:[0,3,6,14,15,16],template_id:6,template_nam:3,termin:[3,14,15],test:[14,15,16],text:[0,15],thank:[],thei:[3,6,15],them:[3,15],thereaft:16,thi:[0,1,3,6,7,8,11,14,15,16],those:[6,14],thread:3,three:16,through:[11,13,14,16],thu:[14,16],ticket:16,ticket_buyer_invit:16,ticket_buyer_rol:16,ticket_purchase_agr:16,ticket_seller_invit:16,ticket_seller_rol:16,ticketbuy:16,ticketbuyerinvit:16,ticketbuyerrol:16,ticketbuyerrole1:16,ticketpurchaseagr:16,ticketpurchaseagreementoff:16,ticketsel:16,ticketsellerinvit:16,ticketsellerrol:16,ticketsellerrole1:16,tickettransactionsinprogress:16,tickettransactiontest:16,time:[0,3,6,11,12,14,15],timedelta:[0,3],timeout:3,told:3,total:[14,16],totext:16,track:3,trade:3,traderequest:14,traderequestacceptedtim:14,traderequestcid:14,traderespons:14,traderesponseacknowledgedtim:14,traderesponsecid:14,transact:[3,16],transaction_limit:16,transactionendev:3,transactionstartev:3,transit:16,transition_to_ticket_transactions_in_progress:16,transition_to_workflow_complet:16,tupl:[3,16],tutori:[11,15],two:[6,12,14],type:[0,1,3,7,11],type_arg:6,type_paramet:6,typeadject:6,typerefer:[3,6],types_stor:7,typevari:6,typic:14,typing_extens:3,under:[14,16],underli:[3,6],union:[3,6],uniqu:3,unit:0,univers:15,unpars:6,unresolvedtyperefer:3,unsortedlett:15,unspecifi:3,unsupportedtyp:6,until:[3,16],upload:3,upon:14,ups:3,url:[3,11,12,14,15,16],usd:[],use:[0,3,15,16],used:[3,6,14,16],useful:[3,15],using:[11,15],util:[1,5,7,11],valid:[0,3],valu:[0,3,6,15,16],variabl:3,variant:0,varianttyp:6,variou:7,venv:[14,16],verbos:16,veri:15,verifi:[14,16],version:[3,11],view:3,wai:3,wait:[3,11,16],walk:[14,16],want:[3,15],wants_any_kei:3,were:[3,12,14,16],what:[14,15],when:[3,6,14,15,16],whenev:3,where:[0,3,6,12,14,15,16],whether:3,which:[3,6,14,15,16],who:15,whose:3,width:0,wish:3,within:[3,16],without:6,word:3,work:[3,6,14,15],workflow:[3,11,13,14,15],workflow_complet:16,workflow_id:3,workflow_st:16,workflow_state_exampl:16,workflow_state_sampl:16,workflow_ticket_transactions_in_progress:16,workflowcomplet:[14,16],workflowsetupinprogress:16,workflowstateexampl:16,workflowtickettransactionsinprogress:16,world:11,would:[3,14],wouldn:15,wrap_as_command_submiss:3,write:[1,3,11,14,16],yet:3,you:[3,6,11,15],your:[6,14,16]},titles:["Basics","dazl package","dazl.cli package","dazl.client package","dazl.damast package","dazl.damlsdk package","dazl.model package","dazl.pretty package","dazl.protocols package","dazl.util package","Glossary","dazl: DA client library for Python","Migrate","Tutorials","Message Ingester","Post Office","Workflow State Example"],titleterms:{api:3,applic:[14,16],archiv:12,basic:0,bot:3,cli:2,client:[3,11],content:[1,2,3,8,11],core:6,creat:[12,15],damast:4,daml:[14,15,16],damlsdk:5,dazl:[1,2,3,4,5,6,7,8,9,11],depend:11,event:12,exampl:16,get:11,glossari:10,ingest:14,initi:12,inspect:15,ledger:15,letter:15,librari:[11,12],listen:12,messag:14,migrat:12,model:[6,14,15,16],modul:[1,2,3,8],offic:15,output:[14,16],packag:[1,2,3,4,5,6,7,8,9],particip:15,post:15,postman:15,pretti:7,protocol:8,python:[11,14,16],readi:12,send:15,set:15,side:6,some:15,start:11,state:16,submodul:[2,3,8],subpackag:1,system:6,tabl:11,through:15,tutori:13,type:6,util:9,workflow:16,write:6}}) \ No newline at end of file +Search.setIndex({docnames:["basics","dazl","dazl.cli","dazl.client","dazl.damlast","dazl.damlsdk","dazl.model","dazl.pretty","dazl.protocols","dazl.util","glossary","index","migrating","tutorials","tutorials_message_ingester","tutorials_post_office","tutorials_workflow_state"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.todo":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["basics.rst","dazl.rst","dazl.cli.rst","dazl.client.rst","dazl.damlast.rst","dazl.damlsdk.rst","dazl.model.rst","dazl.pretty.rst","dazl.protocols.rst","dazl.util.rst","glossary.rst","index.rst","migrating.rst","tutorials.rst","tutorials_message_ingester.rst","tutorials_post_office.rst","tutorials_workflow_state.rst"],objects:{"":{dazl:[1,0,0,"-"]},"dazl.cli":{ls:[2,0,0,"-"],main:[2,4,1,""],print_cmd_help:[2,4,1,""],run:[2,4,1,""]},"dazl.cli.ls":{ListAllCommand:[2,1,1,""]},"dazl.cli.ls.ListAllCommand":{execute:[2,2,1,""],name:[2,3,1,""],parser:[2,2,1,""]},"dazl.client":{api:[3,0,0,"-"],bots:[3,0,0,"-"]},"dazl.client.api":{AIOGlobalClient:[3,1,1,""],AIOPartyClient:[3,1,1,""],GlobalClient:[3,1,1,""],Network:[3,1,1,""],PartyClient:[3,1,1,""],SimpleGlobalClient:[3,1,1,""],SimplePartyClient:[3,1,1,""],simple_client:[3,4,1,""]},"dazl.client.api.AIOGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.AIOPartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.api.Network":{aio_global:[3,2,1,""],aio_party:[3,2,1,""],aio_run:[3,2,1,""],bots:[3,2,1,""],join:[3,2,1,""],parties:[3,2,1,""],party_bots:[3,2,1,""],resolved_config:[3,2,1,""],run_forever:[3,2,1,""],run_until_complete:[3,2,1,""],set_config:[3,2,1,""],shutdown:[3,2,1,""],simple_global:[3,2,1,""],simple_party:[3,2,1,""],start_in_background:[3,2,1,""]},"dazl.client.api.PartyClient":{party:[3,2,1,""],resolved_config:[3,2,1,""]},"dazl.client.api.SimpleGlobalClient":{ensure_dar:[3,2,1,""],ensure_packages:[3,2,1,""],get_time:[3,2,1,""],metadata:[3,2,1,""],set_time:[3,2,1,""]},"dazl.client.api.SimplePartyClient":{add_ledger_archived:[3,2,1,""],add_ledger_created:[3,2,1,""],add_ledger_exercised:[3,2,1,""],add_ledger_init:[3,2,1,""],add_ledger_packages_added:[3,2,1,""],add_ledger_ready:[3,2,1,""],add_ledger_transaction_end:[3,2,1,""],add_ledger_transaction_start:[3,2,1,""],find:[3,2,1,""],find_active:[3,2,1,""],find_by_id:[3,2,1,""],find_historical:[3,2,1,""],find_nonempty:[3,2,1,""],find_one:[3,2,1,""],get_time:[3,2,1,""],ledger_archived:[3,2,1,""],ledger_created:[3,2,1,""],ledger_exercised:[3,2,1,""],ledger_init:[3,2,1,""],ledger_packages_added:[3,2,1,""],ledger_ready:[3,2,1,""],ledger_transaction_end:[3,2,1,""],ledger_transaction_start:[3,2,1,""],ready:[3,2,1,""],set_config:[3,2,1,""],set_time:[3,2,1,""],submit:[3,2,1,""],submit_create:[3,2,1,""],submit_create_and_exercise:[3,2,1,""],submit_exercise:[3,2,1,""],submit_exercise_by_key:[3,2,1,""]},"dazl.client.bots":{Bot:[3,1,1,""],BotCollection:[3,1,1,""],BotEntry:[3,1,1,""],BotInvocation:[3,1,1,""],BotState:[3,1,1,""],wrap_as_command_submission:[3,4,1,""]},"dazl.client.bots.Bot":{add_event_handler:[3,2,1,""],entries:[3,2,1,""],event_keys:[3,2,1,""],id:[3,2,1,""],ledger_created:[3,2,1,""],name:[3,2,1,""],notify:[3,2,1,""],party:[3,2,1,""],pause:[3,2,1,""],resume:[3,2,1,""],running:[3,2,1,""],state:[3,2,1,""],stop:[3,2,1,""],wants_any_keys:[3,2,1,""]},"dazl.client.bots.BotCollection":{add_new:[3,2,1,""],add_single:[3,2,1,""],notify:[3,2,1,""],stop_all:[3,2,1,""]},"dazl.client.bots.BotEntry":{filter:[3,3,1,""],source_location:[3,3,1,""]},"dazl.client.bots.BotState":{PAUSED:[3,3,1,""],PAUSING:[3,3,1,""],RESUMING:[3,3,1,""],RUNNING:[3,3,1,""],STARTING:[3,3,1,""],STOPPED:[3,3,1,""],STOPPING:[3,3,1,""]},"dazl.model":{core:[6,0,0,"-"],ledger:[6,0,0,"-"],reading:[6,0,0,"-"],types:[6,0,0,"-"],types_store:[6,0,0,"-"],writing:[6,0,0,"-"]},"dazl.model.core":{ContractId:[6,1,1,""]},"dazl.model.core.ContractId":{contract_id:[6,3,1,""],exercise:[6,2,1,""],for_json:[6,2,1,""],replace:[6,2,1,""],template_id:[6,3,1,""]},"dazl.model.reading":{ActiveContractSetEvent:[6,1,1,""],BaseTransactionEvent:[6,1,1,""],ContractArchiveEvent:[6,1,1,""],ContractCreateEvent:[6,1,1,""],ContractEvent:[6,1,1,""],ContractExercisedEvent:[6,1,1,""],EventKey:[6,1,1,""],InitEvent:[6,1,1,""],OffsetEvent:[6,1,1,""],PackagesAddedEvent:[6,1,1,""],ReadyEvent:[6,1,1,""],TransactionEndEvent:[6,1,1,""],TransactionFilter:[6,1,1,""],TransactionStartEvent:[6,1,1,""]},"dazl.model.reading.EventKey":{contract_archived:[6,2,1,""],contract_created:[6,2,1,""],contract_exercised:[6,2,1,""],init:[6,2,1,""],offset:[6,2,1,""],ready:[6,2,1,""],transaction_end:[6,2,1,""],transaction_start:[6,2,1,""]},"dazl.model.types":{ListType:[6,1,1,""],RecordType:[6,1,1,""],ScalarType:[6,1,1,""],Type:[6,1,1,""],UnsupportedType:[6,1,1,""],VariantType:[6,1,1,""]},"dazl.model.writing":{Command:[6,1,1,""],CreateCommand:[6,1,1,""],ExerciseCommand:[6,1,1,""]},"dazl.model.writing.CreateCommand":{arguments:[6,3,1,""],replace:[6,2,1,""],template:[6,3,1,""]},"dazl.model.writing.ExerciseCommand":{arguments:[6,3,1,""],choice:[6,3,1,""],contract:[6,3,1,""],replace:[6,2,1,""]},"dazl.pretty":{get_pretty_printer:[7,4,1,""],render_daml:[7,0,0,"-"],util:[7,0,0,"-"]},"dazl.protocols":{v0:[8,0,0,"-"],v1:[8,0,0,"-"]},dazl:{cli:[2,0,0,"-"],client:[3,0,0,"-"],damlast:[4,0,0,"-"],damlsdk:[5,0,0,"-"],model:[6,0,0,"-"],pretty:[7,0,0,"-"],protocols:[8,0,0,"-"],util:[9,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"],"3":["py","attribute","Python attribute"],"4":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method","3":"py:attribute","4":"py:function"},terms:{"00z":14,"01t00":14,"byte":3,"case":[3,14,15,16],"class":[2,3,6,15,16],"default":3,"enum":3,"final":[14,15,16],"float":3,"function":[3,5,9,14,15],"import":[6,11,14,15,16],"int":[0,2,3,6,15],"long":3,"new":[3,6,11,12,14,15,16],"public":3,"return":[3,6,14,15,16],"static":6,"throw":3,"true":[3,6],"try":[3,14,15,16],"while":3,ACS:[3,6,11],AND:3,But:15,For:[3,14,15],IDs:[3,6],NOT:3,That:14,The:[0,3,6,10,14,15,16],Then:15,There:[6,15],These:16,Use:3,Using:15,__file__:15,__init__:16,__main__:[14,15,16],__name__:[14,15,16],_asyncio:3,_base:2,_before_:3,_main:3,_network_client_impl:3,_networkimpl:3,_or_:3,_party_client_impl:3,_partyclientimpl:3,_render_bas:7,_resolve_nam:16,_run_level:3,abil:15,abl:3,about:[3,12],abov:[14,15,16],abstractset:3,accept:[15,16],accept_message_act:14,accept_the_messag:14,accept_ticket_buyer_invit:16,accept_ticket_seller_invit:16,acceptinviteauthorrol:15,acceptinvitereceiverrol:15,acceptlett:15,acceptmessag:14,acceptsentlett:15,acceptticketbuyerinvit:16,acceptticketsellerinvit:16,access:12,acknowledg:14,acknowledge_message_act:14,acknowledge_the_messag:14,acknowledgingparti:14,acknowlegedlett:15,across:12,acs_find_on:11,acting_parti:6,action:16,activ:[3,6,12,14,16],activecontractsetev:6,actual:15,add:[3,14,15,16],add_event_handl:3,add_ledger_archiv:[3,12],add_ledger_cr:[3,12],add_ledger_exercis:3,add_ledger_init:[3,12],add_ledger_packages_ad:3,add_ledger_readi:[3,12],add_ledger_transaction_end:3,add_ledger_transaction_start:3,add_new:3,add_singl:3,added:[3,15],adding:[3,15],addit:[3,6,12,15],addition:[],address:15,adject:6,admin_url:3,advanc:3,affili:[14,16],after:[3,6,14,15,16],afterward:15,against:[3,15],agre:16,agreement:[15,16],aid:6,aio_glob:3,aio_parti:[3,11,12],aio_run:3,aioglobalcli:3,aiopartycli:3,alic:[11,12,14,16],alice_cli:[12,14,16],all:[3,6,11,14,15,16],all_parti:15,allow:[3,15],alongsid:3,alreadi:[3,11],also:[3,14,15,16],altern:3,alwai:[6,15],amount:3,ani:[3,6],anyth:[3,15],anytim:16,apach:[14,16],api:[1,6,11,12,14,16],append:16,appli:[3,6],applic:[3,11,13],appropri:16,arbitrari:3,archiv:[3,6,11,14,16],arg:2,argpars:2,argument:[3,6,12,15],argumentpars:2,aris:6,around:5,arrai:3,assert:15,asset:[10,11,12,14,16],assign:[14,16],assist:5,associ:[3,14,16],assum:[6,11,14,15,16],async:[3,11,16],asynchron:[3,11],asyncio:[3,12,16],attribut:6,author:15,authorrol:15,autom:6,automat:15,await:[3,11,16],background:[3,15],base:[2,3,6,12],baseev:3,basetransactionev:6,basi:[14,16],basic:11,becaus:[15,16],been:[3,6,12,16],befor:[3,6,15,16],begin:[3,6],begun:6,behalf:3,behavior:[3,6],being:[3,6],below:0,best:16,bin:[14,16],binaryio:3,bind:16,bit:15,blank:15,block:[3,14,15,16],bob:[12,14,16],bob_client:[12,14,16],bodi:15,bool:[0,3,6],bot:[1,11],botcallback:3,botcollect:3,botentri:3,botfilt:3,both:[6,16],botinvoc:3,botstat:3,build:11,builtin:6,buyer:16,calcul:3,calculaterequest:0,calculaterespons:0,call:[3,12,14,15],callabl:3,callback:[3,11,14,15],caller:3,can:[3,6,14,15,16],cancel:16,cannot:[3,14,16],caught:3,caus:14,cdata:[6,12,14,15,16],certain:14,chang:[3,12],check:3,child_event_id:6,choic:[3,6,14,15],choice_arg:6,choice_argu:3,choice_nam:[3,6],choicemetadata:6,choiceref:6,cid:[3,6,12,14,15,16],clearli:16,cli:[1,11],clicommand:2,client:[1,6,8,10,12,14,15,16],client_mgr:[14,15,16],close:11,cmd:2,code:[3,6,14,15,16],coerc:3,coercion:6,collaps:12,collect:[3,6],column:15,comfort:3,command:[2,3,6,11,14,15,16],command_id:6,commandbuild:3,commandpayload:3,commit:[14,16],common:3,commun:3,complet:[3,16],composit:6,comput:0,config:3,configur:[3,14],connect:[3,11,14,15],consist:12,construct:6,constructor:[0,6],consum:[6,14,15],contain:[0,1,3,6,7,8,12,14,16],content:15,contextmanag:3,contextu:3,contract:[3,6,11,12,14,15,16],contract_archiv:6,contract_cr:6,contract_creating_event_id:6,contract_dict:11,contract_ev:6,contract_exercis:6,contract_id:6,contract_kei:3,contract_stor:16,contractarchiveev:[3,6],contractcontextualdata:3,contractcontextualdatacollect:3,contractcreateev:[3,6],contractev:6,contractexercisedev:[3,6],contractid:[0,3,6,14,15,16],contractstor:16,control:[14,15,16],conveni:[3,15],convent:12,convert:3,copyright:[14,16],core:[0,1,3,11],coroutin:3,correct:3,correspond:[3,6,14],could:15,cours:14,creat:[3,6,11,13,14,16],create_and_exercis:3,create_cli:[12,14,15,16],create_futur:16,create_if_miss:3,create_initial_workflow_st:16,createa:14,createcommand:6,createdecimallett:15,createintlett:15,createlett:15,createlistintlett:15,createtimelett:15,creation:[14,16],critic:16,ctrl:3,currenc:[],currency_cid:[],current:[3,6],current_offset:6,custom:14,daemon:3,dalf:3,damast:[1,11],daml:[0,5,6,11,13],daml_fil:15,daml_ledger_parti:3,daml_ledger_url:3,damlsdk:[1,11],dar:3,data:[0,3,12],date:[0,3],datetim:[0,3,6],dazl:[0,10,12,14,15,16],deactiv:15,debug:16,decim:[0,3,6,15],declar:3,decor:3,def:[11,14,15,16],defin:[6,14,15,16],del:16,delet:16,deliv:15,demonstr:16,depend:16,deploi:[14,16],describ:[6,14,16],descript:6,design:[14,16],destination_offset:6,detect:[3,6,14,16],develop:[15,16],dict:[0,3,6,15,16],dictionari:[0,3],differ:[8,16],difficult:15,digit:[10,11,14,16],directli:[3,6],dirnam:15,disabl:3,disambigu:6,dish:15,dispatch:3,dispos:15,doc_begin:[14,16],doc_end:[14,16],doe:3,domain:6,don:6,done:[3,14,16],down:[3,15],download:[14,16],drain:3,drawn:15,dump_al:[14,15,16],dure:14,each:[14,15,16],easier:16,easili:15,either:[3,6,15],els:[15,16],empti:0,encapsul:16,encount:[3,6],end:6,ensur:3,ensure_dar:3,ensure_packag:3,entir:3,entri:3,environ:3,equival:3,error:3,eustac:[],even:15,event:[3,6,11,14,15,16],event_id:6,event_kei:3,eventkei:[3,6],eventu:6,ever:6,everi:15,everyth:15,exampl:[0,11,13,14,15],except:[3,15],execut:[2,3,12,14,15,16],exercis:[3,6,14,15,16],exercise_by_kei:3,exercisecommand:6,exist:[3,6],exit:[3,15,16],exit_cod:[14,15,16],expect:6,expos:[3,5,9,15],expr:0,express:0,factori:3,fals:[3,16],fashion:3,fetch:[3,15],few:15,field:[0,3,6],file:[14,16],filter:3,filter_fn:3,find:[3,16],find_act:[3,11],find_by_id:3,find_histor:3,find_nonempti:3,find_on:3,finish:16,first:[15,16],five:15,flight:3,focu:15,follow:[0,3,14,15,16],for_json:6,format:[7,8,15],formerli:12,forward:[14,16],framework:14,frequent:6,friend:15,friendli:3,from:[3,6,11,12,14,15,16],from_ev:3,fulli:[3,11,15],function_accept_invit:16,function_ingest_the_messag:14,function_multi_creation_depend:16,further:15,futur:[3,16],gener:[3,5,9,14],genesi:[14,16],genesis_contract:14,genesiscontract:16,get:[3,6,16],get_event_loop:16,get_pretty_print:7,get_tim:3,getlogg:16,gettim:14,give:3,given:[3,16],global:[3,16],globalcli:3,glossari:11,gmbh:[14,16],gracefulli:3,grant:15,grpcio:[],guarante:[3,16],handl:[3,11],handler:[2,3,12,14,15,16],happen:[12,14,15],has:[3,6,12,14,16],have:[3,6,11,12,14,15,16],head:3,height:[14,16],hello:11,helper:15,here:[6,14,16],hidden:3,high:3,higher:3,histor:3,how:[14,16],howev:[14,16],http:[11,12,14,16],ident:3,identifi:[3,6,14,16],if_miss:3,ignor:15,immedi:[3,15],impl:3,implement:[3,8,11,14,16],include_archiv:3,incorpor:3,indefinit:3,index:15,indic:[14,15],individu:3,info:[3,16],inform:12,infrastructur:3,ingest:[11,13,16],ingest_messag:14,ingest_the_messag:14,ingestmessag:14,init:6,initev:[3,6],initi:[3,6,11,15,16],input:14,inspect:[11,13],inspector:[14,15,16],instal:3,install_signal_handl:3,instanc:[3,6,15],instanti:[3,6,15],instead:[3,15],instruct:3,integ:0,interact:[1,3],interfac:3,intermedi:16,intern:15,introduc:15,invit:[15,16],invite_ticket_buy:16,invite_ticket_sel:16,inviteasauthor:15,inviteasreceiv:15,inviteauthorrol:15,inviteparticip:15,inviteparticipantsinprogress:16,invitereceiverrol:15,inviteticketbuy:16,inviteticketsel:16,invoc:3,invok:[3,6,14],involv:[6,14,16],is_match:16,isinst:16,issuer:11,item:16,iter:15,its:[6,14,15,16],itself:6,join:[3,15,16],json:6,just:6,keep:15,kei:[0,3,15,16],kind:6,know:6,known:[2,3],kwarg:3,lambda:[12,15],lane:15,lastli:15,later:[11,15],least:3,ledger:[1,3,6,10,11,12,13,14,16],ledger_arch:3,ledger_archiv:3,ledger_cr:3,ledger_exercis:3,ledger_id:6,ledger_init:3,ledger_packages_ad:3,ledger_readi:[3,11],ledger_run:[14,15,16],ledger_transaction_end:3,ledger_transaction_start:3,ledgercaptureplugin:[14,15,16],ledgerclientmanag:15,ledgermetadata:3,leger:14,length:[0,3],let:15,letter:[11,13],level:[3,6],librari:[3,6,8,10],licens:[14,16],like:15,line:[2,14],list:[0,3,6,14,15,16],listallcommand:2,listen:[3,11,15],listtyp:6,liter:3,live:[14,16],load:11,local:[3,6],localhost:[11,12,14,16],log:[3,16],log_level:3,logger:3,logic:3,longer:[15,16],lookup:16,loop:[3,16],low:6,made:3,mai:[3,16],main:[2,3,11,15],make:15,manag:[3,12,15],manipul:3,manner:[14,16],manual:15,map:0,mark:16,market:15,match:[3,16],max_block:6,maximum:3,mean:3,member:[6,15],member_cli:15,member_party_count:15,messag:[11,13,16],message_ingest:14,messageingest:14,messageingestertest:14,metadata:[3,12],method:[3,6,15],metric:3,metricev:3,migrat:11,mileston:16,min_count:3,minimum:[3,15],model:[0,1,3,7,11,13],modul:[5,6,7,9,11,14,15,16],more:[3,12,14,15,16],most:[3,6,15],move:[14,16],multi:16,multipl:16,must:[6,15,16],name:[0,2,3,6,11,14,15,16],named_arg:6,namedargumentlist:6,nativ:3,necessari:3,need:[3,6,11],network:[3,11,12],networkconfig:3,new_client:[14,15,16],new_datetim:3,new_typ:[3,6],newli:3,newtyp:[3,6],next:16,node:15,non:[3,14],nonconsum:15,none:[3,6,16],nonetyp:[3,6],normal:3,note:[3,6,14,16],notic:15,notif:3,notifi:3,notion:3,now:[3,12,15],num:0,number:3,object:3,occur:[3,6,14,15,16],off:[3,6],offer_ticket_purchase_agr:16,offerticketpurchaseagr:16,offic:[11,13],offset:6,offsetev:6,old:12,omit:3,on_archiv:[3,12],on_creat:[3,12,14,15,16],on_init:12,on_init_metadata:12,on_readi:[3,12,14,15],on_something_of_valu:[],onc:15,one:[2,3,14,15,16],onli:[3,6,14,16],onreadi:11,oper:[3,14,15,16],operator_cli:16,operatorrol:14,operatorrolecid:14,option:[3,6,7],order:[3,12,15,16],origin:[3,12],originalmessageingestedtim:14,other:[3,6,14,15,16],our:[14,16],out:[3,15],outgo:3,output:[3,11,13,15],over:[14,16],owner:11,packag:[11,12],package_id:3,package_stor:6,packagesaddedev:[3,6],packagestor:[6,7],param:16,paramet:[3,6,12,14,15],parser:2,parti:[0,3,6,11,12,14,15,16],particip:[11,13,16],participant_url:[12,14,15,16],participantledgercli:15,party_bot:3,party_cli:3,party_group:6,party_nam:12,partycli:3,partyconfig:3,pass:[6,14],path:[3,15],pathlib:3,paus:3,perform:[14,16],perman:3,perspect:3,phase:16,platflorm:[14,16],platform:[14,16],plugin:[14,15,16],poetri:11,point:[6,15,16],popen:16,popul:[3,6],port:16,possibl:3,post:[11,13],postman:[11,13],postman_cli:15,postman_parti:15,postmanrol:15,potenti:3,practic:16,pre:6,predecessor:6,prefer:3,present:[3,16],pretti:[1,11],prettyopt:7,prettyprintbas:7,primari:3,primary_onli:6,print:[7,11,12,15],print_cmd_help:2,proce:16,process:[3,6,15,16],produc:[14,16],product:[0,15],progress:[15,16],project:[14,16],prompt:[14,16],properti:3,protocol:[1,11],provid:[3,12,14,15],purchas:16,purchase_agr:16,purchase_ticket:16,purchaseticket:16,purchs:16,purpos:16,python3:[14,16],python:[0,1,6,10,13],pyyaml:[],queri:3,queu:3,queue:3,quicker:15,rais:[3,6],ran:15,rang:15,react:[14,16],read:[1,3,11],readabl:15,readi:[3,6,11,15],readyev:[3,6,11],real:15,realpath:15,receiv:[3,15],receiveraddress:15,receivercid2:15,receivercid:15,receiverrol:15,recommend:[14,16],record:0,recordtyp:6,rectangl:0,refer:[6,14],reflect:6,regist:[3,12,14,15,16],register_event_handl:[14,16],registr:[3,14,15],rejectmessag:14,releas:11,reltim:0,remain:14,remot:3,remov:3,replac:[6,15],repres:[6,16],represent:6,request:[0,3],requestor:14,requestprocessingparti:14,requir:3,reserv:[14,16],resolv:[3,16],resolved_config:3,respect:16,respond:15,respons:[6,15],restart:3,result:[6,15,16],resum:3,reus:6,right:[3,14,16],role:[15,16],rout:15,row:3,rule:6,run:[2,3,11,12,14,15,16],run_forev:[3,12],run_stat:3,run_test:15,run_until_complet:[3,11,14,15,16],runstat:3,runtim:3,safe:3,same:[6,14,16],sampl:[14,16],sample_callback_oncr:14,sample_daml_scenario_ingest_messag:14,sandbox:[11,14,15,16],save:16,save_purchase_agr:16,scalar:6,scalartyp:6,scenario:[14,16],schedul:3,script:15,sdk:[5,14,15,16],search:3,second:3,section:11,see:[3,15],self:16,seller:16,semver:[],send:[3,6,11,13],sender:15,sent:15,sentlett:15,sentlettercid2:15,sentlettercid:15,separ:15,sequenc:[3,6,14,16],sequenti:[14,16],seri:[14,16],serial:8,serv:15,server:[3,11,14,15,16],servic:3,set:[3,6,11,12,13,14,16],set_config:[3,11,12],set_result:16,set_tim:3,set_up:15,setinitialworkflowst:16,sever:15,shall:[14,16],should:[3,6,15],show:15,shut:3,shutdown:3,side:[1,3,11],sigint:3,signal:3,signatori:[14,15,16],sigquit:3,similar:[14,16],simpl:[2,6],simple_cli:[3,11,15],simple_glob:3,simple_parti:3,simpleglobalcli:3,simplepartycli:3,sinc:14,singl:[0,3,11,12,15,16],situat:[6,14],situt:16,skip:3,snapshot:3,snippet:14,sole:16,some:[0,3,6,11,12,13],somefield:[],sometext:[],someth:3,somethingof:[],sort:15,sortedlett:15,sourc:[2,3,6,7],source_loc:3,sourceloc:3,spdx:[14,16],specif:[0,3,6,15],specifi:[3,6,14,16],split:15,stamp:3,standard:11,start:[3,6,14,15,16],start_in_background:3,starter:[14,16],state:[3,6,11,13,14,15],stdout:[14,15,16],step:[14,15,16],stop:[3,15,16],stop_al:3,store:[3,7,12,15,16],str:[0,3,6,7],stream:6,string:6,structur:14,style:3,subclass:6,submiss:3,submit:[3,11,15,16],submit_cr:[3,11],submit_create_and_exercis:3,submit_exercis:3,submit_exercise_by_kei:3,submit_fn:3,submodul:[1,11],subpackag:11,subprocess:16,subscrib:3,subsequ:[14,16],successfulli:[3,14,15],sum:0,suppli:6,support:[3,8],sure:15,switzerland:[14,16],synchron:3,sys:15,system:[1,11],tabl:0,tag:6,take:[3,12],tbc:15,tchoos:14,tear:15,templat:[0,3,6,14,15,16],template_id:6,template_nam:3,termin:[3,14,15],test:[14,15,16],text:[0,15],thank:[],thei:[3,6,15],them:[3,15],thereaft:16,thi:[0,1,3,6,7,8,11,14,15,16],those:[6,14],thread:3,three:16,through:[11,13,14,16],thu:[14,16],ticket:16,ticket_buyer_invit:16,ticket_buyer_rol:16,ticket_purchase_agr:16,ticket_seller_invit:16,ticket_seller_rol:16,ticketbuy:16,ticketbuyerinvit:16,ticketbuyerrol:16,ticketbuyerrole1:16,ticketpurchaseagr:16,ticketpurchaseagreementoff:16,ticketsel:16,ticketsellerinvit:16,ticketsellerrol:16,ticketsellerrole1:16,tickettransactionsinprogress:16,tickettransactiontest:16,time:[0,3,6,11,12,14,15],timedelta:[0,3],timeout:3,told:3,total:[14,16],totext:16,track:3,trade:3,traderequest:14,traderequestacceptedtim:14,traderequestcid:14,traderespons:14,traderesponseacknowledgedtim:14,traderesponsecid:14,transact:[3,6,16],transaction_end:6,transaction_limit:16,transaction_start:6,transactionendev:[3,6],transactionfilt:6,transactionstartev:[3,6],transit:16,transition_to_ticket_transactions_in_progress:16,transition_to_workflow_complet:16,tupl:[3,16],tutori:[11,15],two:[6,12,14],type:[0,1,3,7,11],type_arg:6,type_paramet:6,typeadject:6,typerefer:[3,6],types_stor:[6,7],typevari:6,typic:14,typing_extens:3,under:[14,16],underli:[3,6],union:[3,6],uniqu:3,unit:0,univers:15,unpars:6,unresolvedtyperefer:3,unsortedlett:15,unspecifi:3,unsupportedtyp:6,until:[3,16],upload:3,upon:14,ups:3,url:[3,11,12,14,15,16],usd:[],use:[0,3,15,16],used:[3,6,14,16],useful:[3,15],using:[11,15],util:[1,5,7,11],valid:[0,3],valu:[0,3,6,15,16],variabl:3,variant:0,varianttyp:6,variou:7,venv:[14,16],verbos:16,veri:15,verifi:[14,16],version:[3,11],view:3,wai:3,wait:[3,11,16],walk:[14,16],want:[3,15],wants_any_kei:3,well:6,were:[3,12,14,16],what:[14,15],when:[3,6,14,15,16],whenev:3,where:[0,3,6,12,14,15,16],whether:3,which:[3,6,14,15,16],who:15,whose:3,width:0,wish:3,within:[3,16],without:6,witness_parti:6,word:3,work:[3,6,14,15],workflow:[3,11,13,14,15],workflow_complet:16,workflow_id:[3,6],workflow_st:16,workflow_state_exampl:16,workflow_state_sampl:16,workflow_ticket_transactions_in_progress:16,workflowcomplet:[14,16],workflowsetupinprogress:16,workflowstateexampl:16,workflowtickettransactionsinprogress:16,world:11,would:[3,14],wouldn:15,wrap_as_command_submiss:3,write:[1,3,11,14,16],yet:3,you:[3,6,11,15],your:[6,14,16]},titles:["Basics","dazl package","dazl.cli package","dazl.client package","dazl.damast package","dazl.damlsdk package","dazl.model package","dazl.pretty package","dazl.protocols package","dazl.util package","Glossary","dazl: DA client library for Python","Migrate","Tutorials","Message Ingester","Post Office","Workflow State Example"],titleterms:{api:3,applic:[14,16],archiv:12,basic:0,bot:3,cli:2,client:[3,11],content:[1,2,3,8,11],core:6,creat:[12,15],damast:4,daml:[14,15,16],damlsdk:5,dazl:[1,2,3,4,5,6,7,8,9,11],depend:11,event:12,exampl:16,get:11,glossari:10,ingest:14,initi:12,inspect:15,ledger:15,letter:15,librari:[11,12],listen:12,messag:14,migrat:12,model:[6,14,15,16],modul:[1,2,3,8],offic:15,output:[14,16],packag:[1,2,3,4,5,6,7,8,9],particip:15,post:15,postman:15,pretti:7,protocol:8,python:[11,14,16],read:6,readi:12,send:15,set:15,side:6,some:15,start:11,state:16,submodul:[2,3,8],subpackag:1,system:6,tabl:11,through:15,tutori:13,type:6,util:9,workflow:16,write:6}}) \ No newline at end of file diff --git a/python/dazl/model/reading.py b/python/dazl/model/reading.py index 615b6193..afec23e7 100644 --- a/python/dazl/model/reading.py +++ b/python/dazl/model/reading.py @@ -1,8 +1,58 @@ # Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +# TODO: `automodule reading` directive doesn't appear to work here, have to list each class individually. """ +Read-Side Types +--------------- + This module contains models used on the read-side of the Ledger API. + +.. autoclass:: InitEvent + :members: + +.. autoclass:: InitEvent + :members: + +.. autoclass:: OffsetEvent + :members: + +.. autoclass:: ReadyEvent + :members: + +.. autoclass:: ActiveContractSetEvent + :members: + +.. autoclass:: BaseTransactionEvent + :members: + +.. autoclass:: TransactionStartEvent + :members: + +.. autoclass:: TransactionEndEvent + :members: + +.. autoclass:: ContractEvent + :members: + +.. autoclass:: ContractCreateEvent + :members: + +.. autoclass:: ContractExercisedEvent + :members: + +.. autoclass:: ContractArchiveEvent + :members: + +.. autoclass:: PackagesAddedEvent + :members: + +.. autoclass:: TransactionFilter + :members: + +.. autoclass:: EventKey + :members: + """ from dataclasses import dataclass