From 916951b80704518d400475f8b2f194041137618b Mon Sep 17 00:00:00 2001 From: James Penn Date: Mon, 14 Jun 2021 09:42:12 +0100 Subject: [PATCH 1/9] Removed conda-gitenv dependency --- .gitignore | 3 +- circle.yml | 14 - conda_rpms/__init__.py | 1 - conda_rpms/build_rpm_structure.py | 336 ------------------ conda_rpms/etc/config.yaml.example | 5 - conda_rpms/etc/state.yaml.example | 11 - conda_rpms/generate.py | 151 -------- conda_rpms/templates/env.spec.template | 49 --- conda_rpms/tests/__init__.py | 86 ----- .../tests/integration/gitenv_build_rpms.sh | 38 -- .../integration/gitenv_create_rpmbuild.sh | 81 ----- .../tests/integration/gitenv_install.sh | 72 ---- .../unit/build_rpm_structure/__init__.py | 0 .../test__env_label_filter.py | 28 -- .../test_create_rpmbuild_content.py | 117 ------ .../test_create_rpmbuild_for_env.py | 97 ----- .../test_create_rpmbuild_for_tag.py | 65 ---- conda_rpms/tests/unit/generate/__init__.py | 0 .../tests/unit/generate/test_render_env.py | 37 -- conda_rpms/tests/unit/test_build.py | 42 --- pyproject.toml | 14 + pytest.ini | 5 + requirements.txt | 6 - setup.cfg | 20 ++ setup.py | 86 +---- src/conda_rpms/__init__.py | 1 + {conda_rpms => src/conda_rpms}/build.py | 29 +- src/conda_rpms/conda_compat.py | 101 ++++++ .../conda_rpms/dist}/install.py | 0 src/conda_rpms/generate.py | 269 ++++++++++++++ src/conda_rpms/logger.py | 6 + .../conda_rpms/templates/env.spec.template | 23 +- .../templates/installer.spec.template | 0 .../conda_rpms}/templates/pkg.spec.template | 4 +- {conda_rpms/tests/unit => tests}/__init__.py | 0 tests/unit/test_build.py | 38 ++ tests/unit/test_lockfile.py | 46 +++ 37 files changed, 531 insertions(+), 1350 deletions(-) delete mode 100644 circle.yml delete mode 100644 conda_rpms/__init__.py delete mode 100644 conda_rpms/build_rpm_structure.py delete mode 100644 conda_rpms/etc/config.yaml.example delete mode 100644 conda_rpms/etc/state.yaml.example delete mode 100644 conda_rpms/generate.py delete mode 100644 conda_rpms/templates/env.spec.template delete mode 100644 conda_rpms/tests/__init__.py delete mode 100755 conda_rpms/tests/integration/gitenv_build_rpms.sh delete mode 100755 conda_rpms/tests/integration/gitenv_create_rpmbuild.sh delete mode 100755 conda_rpms/tests/integration/gitenv_install.sh delete mode 100644 conda_rpms/tests/unit/build_rpm_structure/__init__.py delete mode 100644 conda_rpms/tests/unit/build_rpm_structure/test__env_label_filter.py delete mode 100644 conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_content.py delete mode 100644 conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_env.py delete mode 100644 conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_tag.py delete mode 100644 conda_rpms/tests/unit/generate/__init__.py delete mode 100644 conda_rpms/tests/unit/generate/test_render_env.py delete mode 100644 conda_rpms/tests/unit/test_build.py create mode 100755 pyproject.toml create mode 100755 pytest.ini delete mode 100644 requirements.txt create mode 100755 setup.cfg create mode 100644 src/conda_rpms/__init__.py rename {conda_rpms => src/conda_rpms}/build.py (63%) create mode 100755 src/conda_rpms/conda_compat.py rename {conda_rpms => src/conda_rpms/dist}/install.py (100%) create mode 100755 src/conda_rpms/generate.py create mode 100755 src/conda_rpms/logger.py rename conda_rpms/templates/taggedenv.spec.template => src/conda_rpms/templates/env.spec.template (74%) rename {conda_rpms => src/conda_rpms}/templates/installer.spec.template (100%) rename {conda_rpms => src/conda_rpms}/templates/pkg.spec.template (96%) rename {conda_rpms/tests/unit => tests}/__init__.py (100%) mode change 100644 => 100755 create mode 100755 tests/unit/test_build.py create mode 100755 tests/unit/test_lockfile.py diff --git a/.gitignore b/.gitignore index 316fec2..0e66f44 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,11 @@ *.py[co] +rpmbuild/ + # Packages *.egg *.eggs *.egg-info -dist build eggs parts diff --git a/circle.yml b/circle.yml deleted file mode 100644 index 8af79e2..0000000 --- a/circle.yml +++ /dev/null @@ -1,14 +0,0 @@ -machine: - services: - - docker - -dependencies: - override: - - docker pull centos:6 - -test: - override: - # Run, test and (if we have a BINSTAR_TOKEN) upload the distributions. - - ./conda_rpms/tests/integration/gitenv_create_rpmbuild.sh - - ./conda_rpms/tests/integration/gitenv_build_rpms.sh - - ./conda_rpms/tests/integration/gitenv_install.sh diff --git a/conda_rpms/__init__.py b/conda_rpms/__init__.py deleted file mode 100644 index 64f4d06..0000000 --- a/conda_rpms/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = '1.6.0dev0' diff --git a/conda_rpms/build_rpm_structure.py b/conda_rpms/build_rpm_structure.py deleted file mode 100644 index efe6a42..0000000 --- a/conda_rpms/build_rpm_structure.py +++ /dev/null @@ -1,336 +0,0 @@ -#!/usr/bin/env python -""" -Turn the gitenv into RPM spec files which can be built at a later stage. - -""" -from __future__ import print_function - -from fnmatch import fnmatch -import os -import shutil - -import conda.api -import conda.fetch -from conda.resolve import Resolve, MatchSpec -from conda_gitenv import manifest_branch_prefix -from conda_gitenv.deploy import tags_by_label -from conda_gitenv.resolve import tempdir, create_tracking_branches -from git import Repo -import yaml - -import logging -import conda_rpms.generate as generate -import conda_rpms.install as conda_install - - -class Config(dict): - def __init__(self, fname, store=None, key=None): - self.fname = os.path.abspath(os.path.expanduser(fname)) - self._store = store - if store is None: - self._load() - self._key = [] - if key is not None: - self._key = key - - def _load(self): - if not os.path.exists(self.fname): - emsg = 'The configuration file {!r} does not exist.' - raise ValueError(emsg.format(os.path.basename(self.fname))) - with open(self.fname, 'r') as fh: - try: - self._store = yaml.safe_load(fh) - except yaml.YAMLError as e: - emsg = 'YAML error in configuration file {!r}: {}' - line, column = e.problem_mark.line, e.problem_mark.column - ymsg = '{}, line {}, column {}.'.format(e.context, - line+1, - column+1) - raise ValueError(emsg.format(os.path.basename(self.fname), - ymsg)) - - def __getitem__(self, key): - try: - result = self._store[key] - except KeyError: - emsg = 'The YAML file {!r} does not contain key [{}].' - full_key = ']['.join(self._key + [key]) - raise ValueError(emsg.format(os.path.basename(self.fname), - full_key)) - if isinstance(result, dict): - result = Config(self.fname, result, self._key + [key]) - return result - - def __contains__(self, key): - return key in self._store - - def __iter__(self): - return iter(self._store) - - def __len__(self): - return len(self._store) - - def __repr__(self): - return repr(self._store) - - -def create_rpmbuild_for_env(pkgs, target, config): - rpm_prefix = config['rpm']['prefix'] - pkg_cache = os.path.join(target, 'SOURCES') - pkg_names = set(pkg for _, pkg in pkgs) - - if os.path.exists(target): - # The environment we want to deploy already exists. We should - # just double check that there aren't already packages in there which - # we need to remove before we install anything new. - linked = conda_install.linked(target) - for pkg in linked: - if pkg not in pkg_names: - conda_install.unlink(target, pkg) - else: - linked = [] - - if set(linked) == pkg_names: - # We don't need to re-link everything - it is already as expected. - # The downside is that we are not verifying that each package is - # installed correctly. - return - - spec_dir = os.path.join(target, 'SPECS') - if not os.path.exists(spec_dir): - os.makedirs(spec_dir) - - for source, pkg in pkgs: - index = conda.fetch.fetch_index([source], use_cache=False) - pkg_index = {pkg_info['fn']: pkg_info for pkg_info in index.values()} - tar_name = pkg + '.tar.bz2' - pkg_info = pkg_index.get(tar_name, None) - if pkg_info is None: - raise ValueError('Distribution {} is no longer available ' - 'in the channel {}.'.format(tar_name, source)) - if not conda_install.is_fetched(pkg_cache, pkg): - print('Fetching {}'.format(pkg)) - conda.fetch.fetch_pkg(pkg_info, pkg_cache) - spec_path = os.path.join(spec_dir, '{}-pkg-{}.spec'.format(rpm_prefix, - pkg)) - if not os.path.exists(spec_path): - spec = generate.render_dist_spec(os.path.join(pkg_cache, - tar_name), config) - with open(spec_path, 'w') as fh: - fh.write(spec) - - -def create_rpmbuild_for_tag(repo, tag_name, target, config, - api_user=None, api_key=None): - try: - # Python3... - from urllib.parse import urlparse - except ImportError: - # Python2... - from urlparse import urlparse - - rpm_prefix = config['rpm']['prefix'] - print("CREATE FOR {}".format(tag_name)) - tag = repo.tags[tag_name] - # Checkout the tag in a detached head form. - repo.head.reference = tag.commit - repo.head.reset(working_tree=True) - - manifest_fname = os.path.join(repo.working_dir, 'env.manifest') - if not os.path.exists(manifest_fname): - emsg = "The tag '{}' doesn't have a manifested environment." - raise ValueError(emsg.format(tag_name)) - with open(manifest_fname, 'r') as fh: - manifest = sorted(line.strip().split('\t') for line in fh) - if api_user and api_key: - # Inject the API user and key into the channel URLs... - for i, (url, _) in enumerate(manifest): - parts = urlparse(url) - api_url = '{}://{}:{}@{}{}'.format(parts.scheme, api_user, - api_key, parts.netloc, - parts.path) - manifest[i][0] = api_url - - create_rpmbuild_for_env(manifest, target, config) - - index = conda.fetch.fetch_index(list(set([url for url, _ in manifest])), - use_cache=False) - resolver = Resolve(index) - - # To sort, the distributions must match the format of the keys of the index - # For example, most will look like `http://channel::pkg - # However channels on anaconda go by their name rather than their url, - # i.e. `conda-forge::pkg` - dists = [] - for url, pkg in manifest: - anaconda_url = 'https://conda.anaconda.org/' - if url.startswith(anaconda_url): - url = url[len(anaconda_url):] - dists.append('::'.join([os.path.dirname(url), pkg])) - sorted_dists = resolver.dependency_sort(dists) - sorted_pkgs = [dist.split('::')[-1] for dist in sorted_dists] - - spec_fname = os.path.join(repo.working_dir, 'env.spec') - if not os.path.exists(spec_fname): - emsg = "The tag '{}' doesn't have an environment specification." - raise ValueError(emsg.format(tag_name)) - with open(spec_fname, 'r') as fh: - env_spec = yaml.safe_load(fh).get('env', []) - - env_name, tag = tag_name.split('-', 2)[1:] - fname = '{}-env-{}-tag-{}.spec'.format(rpm_prefix, env_name, tag) - with open(os.path.join(target, 'SPECS', fname), 'w') as fh: - fh.write(generate.render_taggedenv(env_name, tag, sorted_pkgs, config, - env_spec)) - - -def _env_label_filter(branch_name, label, env_labels): - """ - Tests whether the current branch_name + label combination matches any of - the desired environment labels. - - """ - item = '{}/{}'.format(branch_name, label) - return any([fnmatch(item, env_label) for env_label in env_labels]) - - -def create_rpmbuild_content(repo, target, config, state, env_labels=None, - api_user=None, api_key=None): - if env_labels is None: - env_labels = ['*'] - - rpm_prefix = config['rpm']['prefix'] - - for branch in repo.branches: - # We only want environment branches, not manifest branches. - if not branch.name.startswith(manifest_branch_prefix): - manifest_branch_name = manifest_branch_prefix + branch.name - # If there is no equivalent manifest branch, we need to - # skip this environment. - if manifest_branch_name not in repo.branches: - continue - branch.checkout() - fname = os.path.join(repo.working_dir, 'labels') - branch_labelled_tags = tags_by_label(fname) - - # Get the number of commits in this branch, and use this as the - # version number in the environment label RPM spec. - commit_num = branch.commit.count() - - # Determine the environment tags that are new or have been changed - # for each branch label, and thus require to have its associated - # RPM build. - if branch.name in state: - # This branch has been built before and has a history ... - labelled_tags = {} - for label, tag in branch_labelled_tags.items(): - if label in state[branch.name] and \ - tag in state[branch.name][label]: - # Skip - the associated RPM already exists. - continue - # This label or this labels tag is new, so register it - # for RPM building. - labelled_tags[label] = tag - else: - # This is a new environment branch, so register all of its - # labels for RPM building. - labelled_tags = branch_labelled_tags - - # Keep track of the labels which have tags - its those we want. - for label, tag in sorted(labelled_tags.items()): - # Only create RPMs for environments that match the given - # pattern. - if _env_label_filter(branch.name, label, env_labels): - create_rpmbuild_for_tag(repo, tag, target, config, - api_user=api_user, - api_key=api_key) - fname = '{}-env-{}-label-{}.spec'.format( - rpm_prefix, branch.name, label) - with open(os.path.join(target, 'SPECS', fname), 'w') as fh: - fh.write(generate.render_env(branch.name, label, - config, tag, commit_num)) - - -def create_rpm_installer(target, config, python_spec='python'): - rpm_prefix = config['rpm']['prefix'] - index = conda.api.get_index() - matches = Resolve(index).get_pkgs(MatchSpec(python_spec)) - if not matches: - raise RuntimeError('No python found in the channels.') - # Pick the latest Python match. - pkg_info = sorted(matches)[-1].info - dist_name = '{}-{}-{}'.format(pkg_info['name'], pkg_info['version'], - pkg_info['build']) - pkg_cache = os.path.join(target, 'SOURCES') - if not conda_install.is_fetched(pkg_cache, dist_name): - print('Fetching {}'.format(dist_name)) - conda.fetch.fetch_pkg(pkg_info, pkg_cache) - - installer_source = os.path.join(os.path.dirname(__file__), 'install.py') - installer_target = os.path.join(pkg_cache, 'install.py') - - shutil.copyfile(installer_source, installer_target) - - spec_dir = os.path.join(target, 'SPECS') - if not os.path.exists(spec_dir): - os.makedirs(spec_dir) - - specfile = os.path.join(spec_dir, '{}-installer.spec'.format(rpm_prefix)) - with open(specfile, 'w') as fh: - fh.write(generate.render_installer(pkg_info, config)) - - -def configure_parser(parser): - parser.add_argument('repo_uri', help='Repo to deploy.') - parser.add_argument('target', help='Location to put the RPMBUILD content.') - parser.add_argument('--config', '-c', type=str, default='config.yaml', - help='YAML configuration filename.') - parser.add_argument('--state', '-s', - help='YAML label RPM state filename.') - parser.add_argument('--env_labels', nargs='+', default=['*'], - help='Pattern to match environment labels to. In the ' - 'form "{environment}/{label}".') - parser.add_argument('--api_user', '-u', action='store', - help='the API user') - parser.add_argument('--api_key', '-k', action='store', - help='the API key') - parser.set_defaults(function=handle_args) - return parser - - -def handle_args(args): - # To reduce the noise coming from conda/conda-build we set - # all loggers to WARN level. - logging.getLogger('').setLevel(logging.WARNING) - for logger_name in logging.Logger.manager.loggerDict.keys(): - logger = logging.getLogger(logger_name) - logger.setLevel(logging.WARNING) - - config = Config(args.config) - state = {} - if args.state is not None: - fname = os.path.abspath(os.path.expanduser(args.state)) - with open(fname, 'r') as fi: - state = yaml.safe_load(fi) or {} - with tempdir() as repo_directory: - repo = Repo.clone_from(args.repo_uri, repo_directory) - create_tracking_branches(repo) - create_rpmbuild_content(repo, args.target, config, state, - env_labels=args.env_labels, - api_user=args.api_user, - api_key=args.api_key) - create_rpm_installer(args.target, config) - - -def main(): - import argparse - - description = 'Deploy the tracked environments.' - parser = argparse.ArgumentParser(description=description) - configure_parser(parser) - args = parser.parse_args() - return args.function(args) - - -if __name__ == '__main__': - main() diff --git a/conda_rpms/etc/config.yaml.example b/conda_rpms/etc/config.yaml.example deleted file mode 100644 index 8d062dc..0000000 --- a/conda_rpms/etc/config.yaml.example +++ /dev/null @@ -1,5 +0,0 @@ -rpm: - prefix: 'SciTools' - -install: - prefix: '/opt/scitools' diff --git a/conda_rpms/etc/state.yaml.example b/conda_rpms/etc/state.yaml.example deleted file mode 100644 index 1819a66..0000000 --- a/conda_rpms/etc/state.yaml.example +++ /dev/null @@ -1,11 +0,0 @@ -branch1: - current: - - env-branch1-1970_01_01 - - env-branch1-1970_02_02 - - env-branch1-1970_03_03 - next: - - env-branch1-1970_04_04 - - env-branch1-1970_04_05 -branch2: - current: - - env-branch2-1980_01_01 diff --git a/conda_rpms/generate.py b/conda_rpms/generate.py deleted file mode 100644 index f054481..0000000 --- a/conda_rpms/generate.py +++ /dev/null @@ -1,151 +0,0 @@ -import os -import jinja2 - - -template_dir = os.path.join(os.path.dirname(__file__), 'templates') -loader = jinja2.FileSystemLoader(template_dir) - -env = jinja2.Environment(loader=loader) -env_trim_blocks = jinja2.Environment(loader=loader, trim_blocks=True) - -pkg_spec_tmpl = env.get_template('pkg.spec.template') -env_spec_tmpl = env_trim_blocks.get_template('env.spec.template') -taggedenv_spec_tmpl = env.get_template('taggedenv.spec.template') -installer_spec_tmpl = env.get_template('installer.spec.template') - -import json -import re -import tarfile -import yaml - -TAG_PATTERN = '^env-\w+-(\d{4}_\d{2}_\d{2}(-\d+)?)$' -tag_pattern = re.compile(TAG_PATTERN) -# Parse out the environment name from the default (.verison) modulefile. -# e.g "set modulesversion 'default-current'" -ENV_PATTERN = '^\s*set\s+modulesversion\s+[\'\"](.*)[\'\"]\s*$' -env_pattern = re.compile(ENV_PATTERN, re.IGNORECASE) - - -def render_dist_spec(dist, config): - with tarfile.open(dist, 'r:bz2') as tar: - m = tar.getmember('info/index.json') - fh = tar.extractfile(m) - import codecs - - reader = codecs.getreader("utf-8") - pkginfo = json.load(reader(fh)) - - try: - m = tar.getmember('info/recipe.json') - except KeyError: - m = None - - if m: - fh = tar.extractfile(m) - meta = yaml.safe_load(reader(fh)) - else: - meta = {} - - meta_about = meta.setdefault('about', {}) - meta_about.setdefault('license', pkginfo.get('license')) - meta_about.setdefault('summary', 'The {} package'.format(pkginfo['name'])) - - rpm_prefix = config['rpm']['prefix'] - install_prefix = config['install']['prefix'] - - return pkg_spec_tmpl.render(pkginfo=pkginfo, - meta=meta, - rpm_prefix=rpm_prefix, - install_prefix=install_prefix) - - -def render_env(branch_name, label, config, tag, commit_num): - rpm_prefix = config['rpm']['prefix'] - summary = 'A {} environment for {}/{}'.format(rpm_prefix, - branch_name, - label) - env_info = {'url': 'http://link/to/gh', - 'name': branch_name, - 'label': label, - 'summary': summary, - 'version': commit_num, - 'prefix': config['install']['prefix']} - module = dict(prefix=None) - - # Configure any registered modulefiles. - if 'module' in config: - # The module prefix must exist. - module['prefix'] = config['module']['prefix'] - # The module file must exist (the modulefile for the tagged envs). - fname = config['module']['file'] - module_loader = jinja2.FileSystemLoader(os.path.dirname(fname)) - module_env = jinja2.Environment(loader=module_loader) - module_template = module_env.get_template(os.path.basename(fname)) - module['file'] = module_template.render(env=env_info) - module['default'] = None - # Configure the optional default modulefile, which provides the - # name of the default environment and label e.g. "default-current". - if 'default' in config['module']: - with open(config['module']['default'], 'r') as fi: - lines = fi.readlines() - for line in lines: - match = env_pattern.match(line) - if match: - module_name, module_label = match.group(1).split('-', 2) - module['name'] = module_name - module['label'] = module_label - break - else: - emsg = ('Cannot find environment name/label within default ' - 'modulefile "{}".') - raise ValueError(emsg.format(config['module']['default'])) - module['default'] = ''.join(lines) - - # When multiple tags are produced in a day, they have an associated count - # addded to the end e.g. env-default-2016_12_05-2, which needs to be parsed - # correctly. - match = tag_pattern.match(tag) - if match is None: - msg = "Cannot create an environment for the tag {}. The name of the " \ - "tag must follow the format " \ - "'env--YYYY-MM-DD(- (optional))'" - raise ValueError(msg.format(tag)) - tag_name = match.group(1) - spec = env_spec_tmpl.render(rpm_prefix=rpm_prefix, env=env_info, - module=module, labelled_tag=tag_name) - return spec - - -def render_taggedenv(env_name, tag, pkgs, config, env_spec): - env_info = {'url': 'http://link/to/gh', - 'name': env_name, - 'tag': tag, - 'summary': 'An environment in which to rejoice.', - 'version': '1', - 'spec': '\n'.join(env_spec)} - rpm_prefix = config['rpm']['prefix'] - install_prefix = config['install']['prefix'] - return taggedenv_spec_tmpl.render(install_prefix=install_prefix, - pkgs=pkgs, - rpm_prefix=rpm_prefix, - env=env_info) - - -def render_installer(pkg_info, config): - rpm_prefix = config['rpm']['prefix'] - install_prefix = config['install']['prefix'] - return installer_spec_tmpl.render(install_prefix=install_prefix, - rpm_prefix=rpm_prefix, - pkg_info=pkg_info) - - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("distribution") - args = parser.parse_args() - #print(render_dist_spec(args.distribution)) - #print(render_env('my_second_env', pkgs=['udunits2-2.2.20-0'])) - print(args) - print(render_installer({'name': 'python', 'version': '2.11.1', - 'build': '0'})) diff --git a/conda_rpms/templates/env.spec.template b/conda_rpms/templates/env.spec.template deleted file mode 100644 index 8c17e53..0000000 --- a/conda_rpms/templates/env.spec.template +++ /dev/null @@ -1,49 +0,0 @@ -Name: {{ rpm_prefix }}-env-{{ env.name }}-label-{{ env.label }} -Version: {{ env.version }} -Release: 0 -Summary: {{ env.summary }} - -License: BSD 3 -{% if env.url %} -URL: {{ env.url }} -{% endif %} -BuildRoot: %{_tmppath}/env-{{ env.name }}-label-{{ env.label }}-{{ env.version }} - -Requires: {{ rpm_prefix }}-env-{{ env.name }}-tag-{{ labelled_tag }} - -%description -This is the {{ env.name }}/{{ env.label }} {{ rpm_prefix }} environment which is currently -pointing at the {{ env.name }}/{{ labelled_tag }} {{ rpm_prefix }} environment via symbolic link. - -%prep -# Clear up any pre-existing build-root. -rm -rf $RPM_BUILD_ROOT/ - -%install -mkdir -p $RPM_BUILD_ROOT{{ env.prefix }}/environments/{{ env.name }} -ln -s {{ env.prefix }}/environments/{{ env.name }}/{{ labelled_tag }} $RPM_BUILD_ROOT{{ env.prefix }}/environments/{{ env.name }}/{{ env.label }} -{% if module.prefix %} -mkdir -p $RPM_BUILD_ROOT{{ module.prefix }} -cat <<'EOF1' > $RPM_BUILD_ROOT{{ module.prefix }}/{{ env.name }}-{{ env.label }} -{{ module.file }} -EOF1 -{% if module.default and env.name == module.name and env.label == module.label %} -cat <<'EOF2' > $RPM_BUILD_ROOT{{ module.prefix }}/.version -{{ module.default }} -EOF2 -{% endif %} -{% endif %} - -# This phase just tidies up after itself. -%clean -rm -rf $RPM_BUILD_ROOT - -%files -# All files in this directory are owned by this RPM. -{{ env.prefix }}/environments/{{ env.name }}/{{ env.label }} -{% if module.prefix %} -{{ module.prefix }}/{{ env.name }}-{{ env.label }} -{% if module.default and env.name == "default" and env.label == "current" %} -{{ module.prefix }}/.version -{% endif %} -{% endif %} diff --git a/conda_rpms/tests/__init__.py b/conda_rpms/tests/__init__.py deleted file mode 100644 index fcaa8c3..0000000 --- a/conda_rpms/tests/__init__.py +++ /dev/null @@ -1,86 +0,0 @@ -import contextlib -import os -import shutil -import tempfile -import unittest - -import mock - - -class CommonTest(unittest.TestCase): - """ - A sub-class of :class:`unittest.TestCase` that provides common - testing functionality. - - """ - def _remove_testcase_patches(self): - """Helper to remove per-testcase patches installed by :meth:`patch`.""" - # Remove all patches made, ignoring errors. - for p in self.testcase_patches: - p.stop() - # Reset per-test patch control variable. - self.testcase_patches.clear() - - def patch(self, *args, **kwargs): - """ - Install a mock.patch, to be removed after the current test. - - The patch is created with mock.patch(*args, **kwargs). - - Returns: - The substitute object returned by patch.start(). - - For example:: - - mock_call = self.patch('module.Class.call', return_value=1) - module_Class_instance.call(3, 4) - self.assertEqual(mock_call.call_args_list, [mock.call(3, 4)]) - - """ - # Make the new patch and start it. - patch = mock.patch(*args, **kwargs) - start_result = patch.start() - - # Create the per-testcases control variable if it does not exist. - # NOTE: this mimics a setUp method, but continues to work when a - # subclass defines its own setUp. - if not hasattr(self, 'testcase_patches'): - self.testcase_patches = {} - - # When installing the first patch, schedule remove-all at cleanup. - if not self.testcase_patches: - self.addCleanup(self._remove_testcase_patches) - - # Record the new patch and start object for reference. - self.testcase_patches[patch] = start_result - - # Return patch replacement object. - return start_result - - @contextlib.contextmanager - def temp_dir(self, suffix='', prefix='tmp', dir=None): - dname = tempfile.mkdtemp(suffix=suffix, - prefix=prefix, - dir=dir) - try: - yield dname - finally: - shutil.rmtree(dname) - - def add_label(self, repo, branch, fname, tag, comment=None): - """ - Create a label file in the specified repository branch - "labels" directory, which contains the provided tag. - - """ - branch.checkout() - dname = os.path.join(repo.working_dir, 'labels') - if not os.path.isdir(dname): - os.makedirs(dname) - fpath = os.path.join(dname, fname) - with open(fpath, 'w') as fo: - fo.write(tag) - self.repo.index.add([fpath]) - if comment is None: - comment = 'Add label {}'.format(fname) - self.repo.index.commit(comment) diff --git a/conda_rpms/tests/integration/gitenv_build_rpms.sh b/conda_rpms/tests/integration/gitenv_build_rpms.sh deleted file mode 100755 index 3d68926..0000000 --- a/conda_rpms/tests/integration/gitenv_build_rpms.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - - -REPO_ROOT=$(cd "$(dirname ${0})/../../.."; pwd;) - -# Test conda-gitenv approach. -cat << EOF | docker run -i \ - -v ${REPO_ROOT}:/repo \ - -a stdin -a stdout -a stderr \ - centos:6 \ - bash || exit ${?} - -yum install -y rpm-build createrepo tar - -rpmbuild -bb --define "_sourcedir /repo/tests/output/gitenv_rpmbuild/SOURCES" /repo/tests/output/gitenv_rpmbuild/SPECS/*.spec --force - -# Put the RPMs in a nice place so we can look at them. -cp -r /root/rpmbuild/RPMS/ /repo/tests/output/gitenv_rpmbuild/ - -createrepo /repo/tests/output/gitenv_rpmbuild/RPMS/ - -rm -rf /etc/yum.repos.d/* - -cat << YUMREPO_EOF > /etc/yum.repos.d/myrepo.repo - -[myrepo] -name = My local repo -baseurl = file:///repo/tests/output/gitenv_rpmbuild/RPMS/ -gpgcheck=0 - -YUMREPO_EOF - -yum install -y TestMyBuild-env-* - -# TODO: Make some assertions!? - -EOF - diff --git a/conda_rpms/tests/integration/gitenv_create_rpmbuild.sh b/conda_rpms/tests/integration/gitenv_create_rpmbuild.sh deleted file mode 100755 index ec3e5e8..0000000 --- a/conda_rpms/tests/integration/gitenv_create_rpmbuild.sh +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env bash - -export OUTDIR=/repo/tests/output -export ENV_REPO=${OUTDIR}/gitenv -export INSTALL_ROOT=/opt/conda - -REPO_ROOT=$(cd "$(dirname ${0})/../../.."; pwd;) - -# Test conda-gitenv approach. -cat << EOF | docker run -i \ - -v ${REPO_ROOT}:/repo \ - -a stdin -a stdout -a stderr \ - centos:6 \ - bash || exit ${?} - -yum install -y rpm-build wget which tar -wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh --no-verbose -bash Miniconda3-latest-Linux-x86_64.sh -b -p ${INSTALL_ROOT} && rm -f Miniconda*.sh -export PATH=${INSTALL_ROOT}/bin:\${PATH} - -export PYTHONPATH=/repo/ - -rm -rf ${INSTALL_ROOT}/pkgs/ -mkdir -p ${OUTDIR}/pkg_cache -ln -s ${OUTDIR}/pkg_cache /opt/conda/pkgs - -conda install --yes -c conda-forge gitpython conda-build-all git - - -git config --global user.email "you@example.com" -git config --global user.name "Your Name" - - -git clone https://github.com/SciTools/conda-gitenv.git -cd conda-gitenv -python setup.py install -cd .. - -mkdir -p ${OUTDIR} ${ENV_REPO} -cd ${ENV_REPO} -git init -cat < env.spec -channels: - - defaults -env: - - python - -SPEC_EOF - -git add env.spec -git commit -m "Added the default environment." -git branch -m default - -conda-gitenv resolve ${OUTDIR}/gitenv -conda-gitenv autotag ${OUTDIR}/gitenv - - -# Label the resolved tag -ENV_TAG=\$(cd ${OUTDIR}/gitenv; git tag -l | grep default | head -n 1) -echo "ENV TAG: \${ENV_TAG}" -git checkout default -mkdir -p labels -echo \${ENV_TAG} > labels/current.txt -git add labels/current.txt -git commit -m "Added the current label to the default environment." - -cat < /repo/conda_rpms/config.yaml -rpm: - prefix: 'TestMyBuild' - -install: - prefix: '/opt/testmybuild' - -CONFIG_EOF - -python /repo/conda_rpms/build_rpm_structure.py ${OUTDIR}/gitenv ${OUTDIR}/gitenv_rpmbuild -c /repo/conda_rpms/config.yaml - -test -f ${OUTDIR}/gitenv_rpmbuild/SPECS/TestMyBuild-installer.spec - -EOF - diff --git a/conda_rpms/tests/integration/gitenv_install.sh b/conda_rpms/tests/integration/gitenv_install.sh deleted file mode 100755 index 4d507ee..0000000 --- a/conda_rpms/tests/integration/gitenv_install.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash - - -REPO_ROOT=$(cd "$(dirname ${0})/../../.."; pwd;) - -cat << 'EOF' | docker run -i \ - -v ${REPO_ROOT}:/repo \ - -a stdin -a stdout -a stderr \ - centos:6 \ - bash || exit ${?} - - -export MINICONDA_DIR=${HOME}/miniconda - -echo "Install conda" -# ------------------ -yum install -y wget -wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh --no-verbose -bash Miniconda3-latest-Linux-x86_64.sh -b -p ${MINICONDA_DIR} && rm -f Miniconda*.sh - -export PATH=${MINICONDA_DIR}/bin:${PATH} - -conda config --set always_yes yes --set changeps1 no --set show_channel_urls yes - - -echo "Create an environment with the noarch package `tqdm`" -# --------------------------------------------------------- -# This will ensure that the noarch package and all it's dependencies are -# downloaded and in the cache. -TQDM_VERSION=4.19.8 -conda create -n test-env -c conda-forge tqdm=${TQDM_VERSION} python=3.6 -source activate test-env -conda uninstall tqdm -source deactivate - - -echo "Check no tqdm pyc files remain" -# ----------------------------------- -if [ -d /root/miniconda/envs/test-env/lib/python3.6/site-packages/tqdm ]; then - echo "The noarch packages tqdm was not successfully uninstalled." - exit 1 -fi - -echo "Create an env containing the python that will be used to run the installer" -# ------------------------------------------------------------------------------- -conda create -n test-installer python -source activate test-installer - - -echo "Run the conda_rpms installer" -# --------------------------------- -# Get the name of the noarch_package, e.g. tqdm-4.19.8-py_0 -noarch_tqdm=$(basename $(find ${MINICONDA_DIR}/pkgs -type d -name "tqdm-${TQDM_VERSION}-py*")) -echo ${noarch_tqdm} -python /repo/conda_rpms/install.py --pkgs-dir=${MINICONDA_DIR}/pkgs --prefix=${MINICONDA_DIR}/envs/test-env --link ${noarch_tqdm} - - -echo "Check that everything is there" -# ----------------------------------- -source activate test-env - -echo 'Check pyc files have been compiled:' -ls /root/miniconda/envs/test-env/lib/python3.6/site-packages/tqdm/*/*pyc - -echo 'Check the noarch package imports' -python -c "import tqdm" - -echo 'Check the entrypoint exists' -which tqdm - -EOF - diff --git a/conda_rpms/tests/unit/build_rpm_structure/__init__.py b/conda_rpms/tests/unit/build_rpm_structure/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/conda_rpms/tests/unit/build_rpm_structure/test__env_label_filter.py b/conda_rpms/tests/unit/build_rpm_structure/test__env_label_filter.py deleted file mode 100644 index 82d786e..0000000 --- a/conda_rpms/tests/unit/build_rpm_structure/test__env_label_filter.py +++ /dev/null @@ -1,28 +0,0 @@ -from conda_rpms.build_rpm_structure import _env_label_filter -import conda_rpms.tests as tests - - -class Test(tests.CommonTest): - def test_match_environment_wildcard(self): - self.assertTrue(_env_label_filter('default', 'current', - ['*'])) - - def test_match_environment_label_wildcard(self): - self.assertTrue(_env_label_filter('default', 'current', - ['default/*'])) - - def test_no_match_environment_label_wildcard(self): - self.assertFalse(_env_label_filter('default', 'current', - ['experimental/*'])) - - def test_match_environment_label_specific(self): - self.assertTrue(_env_label_filter('default', 'current', - ['default/current', 'default/next'])) - - def test_no_match_environment_label_specific(self): - self.assertFalse(_env_label_filter('experimental', 'current', - ['default/current', 'default/next'])) - - -if __name__ == '__main__': - unittest.main() diff --git a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_content.py b/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_content.py deleted file mode 100644 index 6d0b955..0000000 --- a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_content.py +++ /dev/null @@ -1,117 +0,0 @@ -import os -import shutil -import unittest - -from conda_gitenv import manifest_branch_prefix -import conda_gitenv.tests.integration.setup_samples as setup_samples - -from conda_rpms.build_rpm_structure import create_rpmbuild_content -import conda_rpms.tests as tests - - -class Test(tests.CommonTest): - def setUp(self): - name = 'conda_rpms_{}'.format(self._testMethodName) - self.repo = setup_samples.create_repo(name) - self.bname = 'default' - self.env_spec = """ - channels: - - defaults - env: - - python - """ - # Require to create a dummy manifest branch. - self.repo.create_head(manifest_branch_prefix + self.bname) - self.branch = setup_samples.add_env(self.repo, self.bname, - self.env_spec) - func = 'conda_rpms.build_rpm_structure.create_rpmbuild_for_tag' - self.mock_create_tag = self.patch(func) - func = 'conda_rpms.generate.render_env' - self.mock_render_env = self.patch(func, return_value='dummy-env') - self.config = dict(rpm=dict(prefix='prefix')) - self.ctag = 'env-{}-2017_01_01'.format(self.bname) - self.add_label(self.repo, self.branch, 'current.txt', self.ctag) - self.ntag = 'env-{}-2017_02_02'.format(self.bname) - self.add_label(self.repo, self.branch, 'next.txt', self.ntag) - self.count = self.branch.commit.count() - - def tearDown(self): - if os.path.exists(self.repo.working_dir): - shutil.rmtree(self.repo.working_dir) - - def _check_full_build(self, dname, state): - create_rpmbuild_content(self.repo, dname, self.config, state) - self.assertEqual(self.mock_create_tag.call_count, 2) - expected = [((self.repo, self.ctag, dname, self.config),), - ((self.repo, self.ntag, dname, self.config),)] - self.assertEqual(self.mock_create_tag.call_args_list, expected) - self.assertEqual(self.mock_render_env.call_count, 2) - expected = [((self.bname, 'current', self.config, self.ctag, - self.count),), - ((self.bname, 'next', self.config, self.ntag, - self.count),)] - self.assertEqual(self.mock_render_env.call_args_list, expected) - - def test_build_all_with_no_state(self): - with self.temp_dir() as dname: - # Make the expected RPM build SPECS directory. - os.makedirs(os.path.join(dname, 'SPECS')) - # Test - no prior build, so both labels build. - state = {} - self._check_full_build(dname, state) - - def test_build_all_with_no_state_match(self): - with self.temp_dir() as dname: - # Make the expected RPM build SPECS directory. - os.makedirs(os.path.join(dname, 'SPECS')) - # Test - prior build of current label but mismatching tag, - # so both labels build. - tag = 'env-{}-2018_01_01'.format(self.bname) - state = dict(default=dict(current=tag)) - self._check_full_build(dname, state) - - def test_build_next_skip_current(self): - with self.temp_dir() as dname: - # Make the expected RPM build SPECS directory. - os.makedirs(os.path.join(dname, 'SPECS')) - # Test - prior build of current label with matching tag, - # so only next label builds. - state = dict(default=dict(current=self.ctag)) - create_rpmbuild_content(self.repo, dname, self.config, state) - self.assertEqual(self.mock_create_tag.call_count, 1) - expected = [((self.repo, self.ntag, dname, self.config),)] - self.assertEqual(self.mock_create_tag.call_args_list, expected) - self.assertEqual(self.mock_render_env.call_count, 1) - expected = [((self.bname, 'next', self.config, self.ntag, - self.count),)] - self.assertEqual(self.mock_render_env.call_args_list, expected) - - def test_build_current_skip_next(self): - with self.temp_dir() as dname: - # Make the expected RPM build SPECS directory. - os.makedirs(os.path.join(dname, 'SPECS')) - # Test - prior build of next label with matching tag, - # so only current label builds. - state = dict(default=dict(next=self.ntag)) - create_rpmbuild_content(self.repo, dname, self.config, state) - self.assertEqual(self.mock_create_tag.call_count, 1) - expected = [((self.repo, self.ctag, dname, self.config),)] - self.assertEqual(self.mock_create_tag.call_args_list, expected) - self.assertEqual(self.mock_render_env.call_count, 1) - expected = [((self.bname, 'current', self.config, self.ctag, - self.count),)] - self.assertEqual(self.mock_render_env.call_args_list, expected) - - def test_build_skip_all(self): - with self.temp_dir() as dname: - # Make the expected RPM build SPECS directory. - os.makedirs(os.path.join(dname, 'SPECS')) - # Test - prior build of both labels, so no artifacts are built. - state = dict(default=dict(current=self.ctag, next=self.ntag)) - create_rpmbuild_content(self.repo, dname, self.config, state) - self.assertEqual(self.mock_create_tag.call_count, 0) - self.assertEqual(self.mock_render_env.call_count, 0) - - -if __name__ == '__main__': - unittest.main() diff --git a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_env.py b/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_env.py deleted file mode 100644 index 9e46930..0000000 --- a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_env.py +++ /dev/null @@ -1,97 +0,0 @@ -from mock import call, patch, sentinel -import os -import unittest - -import conda_rpms.tests as tests -from conda_rpms.build_rpm_structure import create_rpmbuild_for_env - - -class Test(tests.CommonTest): - def setUp(self): - self.pkgs = [['url1', 'pkg1'], - ['url2', 'pkg2']] - self.prefix = 'Prefix' - self.config = dict(rpm=dict(prefix=self.prefix)) - self.patch('conda_rpms.install.unlink') - - def test_pkg_all_linked(self): - func = 'conda_rpms.install.linked' - with patch(func, return_value=list(zip(*self.pkgs))[1]): - with self.temp_dir() as target: - create_rpmbuild_for_env(self.pkgs, target, self.config) - spec_dir = os.path.join(target, 'SPECS') - self.assertFalse(os.path.isdir(spec_dir)) - - @patch('conda.fetch.fetch_index', return_value={}) - @patch('conda_rpms.install.linked', return_value=[]) - def test_pkg_unavailable(self, mlinked, mindex): - with self.temp_dir() as target: - emsg = 'no longer available in the channel' - with self.assertRaisesRegexp(ValueError, emsg): - create_rpmbuild_for_env(self.pkgs, target, self.config) - - @patch('conda_rpms.generate.render_dist_spec', return_value='spec') - @patch('conda_rpms.install.is_fetched', return_value=True) - @patch('conda.fetch.fetch_index', - return_value={'dummy0': {'fn': 'pkg1.tar.bz2'}, - 'dummy1': {'fn': 'pkg2.tar.bz2'}}) - @patch('conda_rpms.install.linked', return_value=[]) - def test_pkg_render(self, mlinked, mindex, mfetched, mrender): - with self.temp_dir() as target: - create_rpmbuild_for_env(self.pkgs, target, self.config) - spec_dir = os.path.join(target, 'SPECS') - self.assertTrue(os.path.isdir(spec_dir)) - expected = [call(['url1'], use_cache=False), - call(['url2'], use_cache=False)] - self.assertEqual(mindex.call_args_list, expected) - srcs_dir = os.path.join(target, 'SOURCES') - expected = [call(srcs_dir, 'pkg1'), - call(srcs_dir, 'pkg2')] - self.assertEqual(mfetched.call_args_list, expected) - expected = [call(os.path.join(srcs_dir, 'pkg1.tar.bz2'), - self.config), - call(os.path.join(srcs_dir, 'pkg2.tar.bz2'), - self.config)] - self.assertEqual(mrender.call_args_list, expected) - fname = '{}-pkg-{}.spec' - specs = [os.path.join(spec_dir, fname.format(self.prefix, 'pkg1')), - os.path.join(spec_dir, fname.format(self.prefix, 'pkg2'))] - for spec in specs: - self.assertTrue(os.path.isfile(spec)) - - @patch('conda_rpms.generate.render_dist_spec', return_value='spec') - @patch('conda.fetch.fetch_pkg') - @patch('conda_rpms.install.is_fetched', return_value=False) - @patch('conda.fetch.fetch_index', - return_value={'dummy0': {'fn': 'pkg1.tar.bz2'}, - 'dummy1': {'fn': 'pkg2.tar.bz2'}}) - @patch('conda_rpms.install.linked', return_value=[]) - def test_pkg_fetch_render(self, mlinked, mindex, mfetched, mpkg, mrender): - with self.temp_dir() as target: - create_rpmbuild_for_env(self.pkgs, target, self.config) - spec_dir = os.path.join(target, 'SPECS') - self.assertTrue(os.path.isdir(spec_dir)) - expected = [call(['url1'], use_cache=False), - call(['url2'], use_cache=False)] - self.assertEqual(mindex.call_args_list, expected) - srcs_dir = os.path.join(target, 'SOURCES') - expected = [call(srcs_dir, 'pkg1'), - call(srcs_dir, 'pkg2')] - self.assertEqual(mfetched.call_args_list, expected) - expected = [call({'fn': 'pkg1.tar.bz2'}, srcs_dir), - call({'fn': 'pkg2.tar.bz2'}, srcs_dir)] - self.assertEqual(mpkg.call_args_list, expected) - expected = [call(os.path.join(srcs_dir, 'pkg1.tar.bz2'), - self.config), - call(os.path.join(srcs_dir, 'pkg2.tar.bz2'), - self.config)] - self.assertEqual(mrender.call_args_list, expected) - fname = '{}-pkg-{}.spec' - specs = [os.path.join(spec_dir, fname.format(self.prefix, 'pkg1')), - os.path.join(spec_dir, fname.format(self.prefix, 'pkg2'))] - for spec in specs: - self.assertTrue(os.path.isfile(spec)) - - -if __name__ == '__main__': - unittest.main() diff --git a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_tag.py b/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_tag.py deleted file mode 100644 index 06e70be..0000000 --- a/conda_rpms/tests/unit/build_rpm_structure/test_create_rpmbuild_for_tag.py +++ /dev/null @@ -1,65 +0,0 @@ -from mock import patch, MagicMock -import os - -import conda_rpms.tests as tests -from conda_rpms.build_rpm_structure import create_rpmbuild_for_tag - - -CONFIG = {'rpm' : {'prefix' : 'SciTools'}, - 'install' : {'prefix' : 'test_install_location'}} - -ENV_SPEC = """channels: - - https://conda.anaconda.org/conda-forge/linux-64 -env: - - python -""" - -ENV_MANIFEST ="""https://conda.anaconda.org/conda-forge/linux-64\tca-certificates-2018.1.18-0 -https://conda.anaconda.org/conda-forge/linux-64\tncurses-5.9-10 -https://conda.anaconda.org/conda-forge/linux-64\topenssl-1.0.2n-0 -https://conda.anaconda.org/conda-forge/linux-64\tpython-3.6.4-0 -https://conda.anaconda.org/conda-forge/linux-64\tsqlite-3.20.1-2 -https://conda.anaconda.org/conda-forge/linux-64\ttk-8.6.7-0 -https://conda.anaconda.org/conda-forge/linux-64\txz-5.2.3-0 -https://conda.anaconda.org/conda-forge/linux-64\tzlib-1.2.11-0 -""" - - -class Test(tests.CommonTest): - @patch('conda_rpms.build_rpm_structure.create_rpmbuild_for_env') - def test_sorted_order(self, a): - with self.temp_dir() as target: - with self.temp_dir() as temp_repo: - # Create fake env.spec and manifest files - with open(os.path.join(temp_repo, 'env.spec'), 'w') as \ - env_spec_file: - env_spec_file.write(ENV_SPEC) - with open(os.path.join(temp_repo, 'env.manifest'), 'w') as \ - env_manifest_file: - env_manifest_file.write(ENV_MANIFEST) - - # Set up arguments for call to create_rpmbuild_for_tag - repo = MagicMock() - repo.working_dir = temp_repo - tag_name = 'env-default-2018_03_26' - # Create directory that the spec file will be written to - os.mkdir(os.path.join(target, 'SPECS')) - create_rpmbuild_for_tag(repo, tag_name, target, CONFIG) - - # Compare the written spec file with what we'd expect - with open(os.path.join(target, 'SPECS', - 'SciTools-env-default-tag-2018_03_26.spec'), - 'r') as fh: - result_order = [] - for line in fh.readlines(): - # Parse the lines of the spec file that are formatted as - # ` {INSTALL} xz-5.2.3-0\n` - line = line.strip() - if line.startswith('${INSTALL}'): - result_order.append(line.split(' ')[1]) - - expected_order = ['ca-certificates-2018.1.18-0', 'ncurses-5.9-10', - 'tk-8.6.7-0', 'xz-5.2.3-0', 'zlib-1.2.11-0', - 'openssl-1.0.2n-0', 'sqlite-3.20.1-2', - 'python-3.6.4-0'] - self.assertEqual(expected_order,result_order) \ No newline at end of file diff --git a/conda_rpms/tests/unit/generate/__init__.py b/conda_rpms/tests/unit/generate/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/conda_rpms/tests/unit/generate/test_render_env.py b/conda_rpms/tests/unit/generate/test_render_env.py deleted file mode 100644 index ae5e32e..0000000 --- a/conda_rpms/tests/unit/generate/test_render_env.py +++ /dev/null @@ -1,37 +0,0 @@ -import unittest - -from conda_rpms.generate import render_env - - -class Test_tag(unittest.TestCase): - def check(self, tag, branch_name='default', expected=None): - config = {'install': {'prefix': '/data/local'}, - 'rpm': {'prefix': 'Tools'} - } - r = render_env(branch_name=branch_name, label='next', config=config, - tag=tag, commit_num=30) - result_requires = [ - line for line in r.split('\n') if line.startswith('Requires: ')] - self.assertEqual(result_requires, expected) - - def test_tag(self): - self.check(tag='env-default-2016_12_15', - expected=['Requires: Tools-env-default-tag-2016_12_15']) - - def test_tag_with_count(self): - self.check(tag='env-default-2016_12_15-2', - expected=['Requires: Tools-env-default-tag-2016_12_15-2']) - - def test_alphanumeric_branch_name(self): - branch = 'default12' - self.check(tag='env-{}-2016_12_15-2'.format(branch), - branch_name=branch, - expected=['Requires: Tools-env-default12-tag-2016_12_15-2']) - - def test_bad_tag(self): - msg = "Cannot create an environment for the tag" - with self.assertRaisesRegexp(ValueError, msg): - self.check(tag='env-defa-ult-2016_12_15-2') - -if __name__ == '__main__': - unittest.main() diff --git a/conda_rpms/tests/unit/test_build.py b/conda_rpms/tests/unit/test_build.py deleted file mode 100644 index 5ad3652..0000000 --- a/conda_rpms/tests/unit/test_build.py +++ /dev/null @@ -1,42 +0,0 @@ -import textwrap -import unittest - -from conda_rpms.build import name_version_release - - -class Test_name_version_release(unittest.TestCase): - def _check_output(self, spec): - expected = {'name': 'foo', 'release':'2', 'version':'1'} - actual = name_version_release(textwrap.dedent(spec).split('\n')) - self.assertEqual(expected, actual) - - def test_multiple_names(self): - spec = """ - Name: foo - Version: 1 - Release: 2 - Name: bar - """ - self._check_output(spec) - - def test_multiple_versions(self): - spec = """ - Name: foo - Version: 1 - Release: 2 - Version: 3 - """ - self._check_output(spec) - - def test_multiple_releases(self): - spec = """ - Name: foo - Version: 1 - Release: 2 - Release: 3 - """ - self._check_output(spec) - - -if __name__ == '__main__': - unittest.main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100755 index 0000000..1b7e703 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,14 @@ +[build-system] +requires = ["setuptools", "wheel", "setuptools_scm[toml]>=6.0"] +build-backend = "setuptools.build_meta" + +[project.optional-dependencies] +test = [ + "pytest", + "pytest-datafiles", + "mock", + "pytest-cov[all]" +] + +[tool.setuptools_scm] +write_to = "src/conda_rpms/_version.py" \ No newline at end of file diff --git a/pytest.ini b/pytest.ini new file mode 100755 index 0000000..e85f408 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +minversion = 6.0 +addopts = -ra -q +testpaths = + tests \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index ca5f456..0000000 --- a/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -jinja2 -gitpython -conda-build-all -pyyaml -setuptools -mock diff --git a/setup.cfg b/setup.cfg new file mode 100755 index 0000000..074c62c --- /dev/null +++ b/setup.cfg @@ -0,0 +1,20 @@ +[metadata] +name = conda_rpms +license = BSD 3-Clause License +keywords = conda, rpm +version = attr: conda_rpms.__version__ + +[options] +packages=find: +package_dir= + =src +install_requires= + jinja2 + ensureconda + conda_package_handling + +[options.extras_require] +test = pytest; mock; pytest-cov + +[options.packages.find] +where = src \ No newline at end of file diff --git a/setup.py b/setup.py index 0b42872..864b617 100644 --- a/setup.py +++ b/setup.py @@ -1,84 +1,2 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os -from setuptools import setup - - -NAME = 'conda_rpms' -DIR = os.path.abspath(os.path.dirname(__file__)) - - -def extract_packages(): - packages = [] - root = os.path.join(DIR, NAME) - offset = len(os.path.dirname(root)) + 1 - for dpath, dnames, fnames in os.walk(root): - if os.path.exists(os.path.join(dpath, '__init__.py')): - package = dpath[offset:].replace(os.path.sep, '.') - packages.append(package) - return packages - - -def extract_version(): - version = None - fname = os.path.join(DIR, NAME, '__init__.py') - with open(fname) as fin: - for line in fin: - if (line.startswith('__version__')): - _, version = line.split('=') - version = version.strip()[1:-1] # Remove quotation. - break - return version - - -def read(*parts): - result = None - fname = os.path.join(DIR, *parts) - if os.path.isfile(fname): - with open(fname, 'rb') as fh: - result = fh.read().decode('utf-8') - return result - - -def extract_description(): - description = read('README.rst') - if description is None: - description = 'conda-rpms' - return description - - -def extract_requirements(): - require = read('requirements.txt') - return [r.strip() for r in require.splitlines()] - - -setup_args = dict( - name = NAME, - version = extract_version(), - description = 'conda-rpms', - long_description = extract_description(), - platforms = ['Linux', 'Mac OS X', 'Windows'], - package_data = {NAME: ['templates/*.template']}, - license = 'BSD 3-clause', - packages = extract_packages(), - classifiers = [ - 'License :: OSI Approved :: BSD License', - 'Development Status :: 1 - Planning Development Status', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Operating System :: OS Independent', - 'Intended Audience :: Science/Research', - 'Intended Audience :: Developers', - 'Natural Language :: English', - 'Topic :: Scientific/Engineering', - 'Topic :: Software Development :: Libraries'], - install_requires = extract_requirements(), - test_suite = '{}.tests'.format(NAME), -) - - -if __name__ == "__main__": - setup(**setup_args) +import setuptools +setuptools.setup() \ No newline at end of file diff --git a/src/conda_rpms/__init__.py b/src/conda_rpms/__init__.py new file mode 100644 index 0000000..c7810fb --- /dev/null +++ b/src/conda_rpms/__init__.py @@ -0,0 +1 @@ +__version__ = "2.0.dev0" diff --git a/conda_rpms/build.py b/src/conda_rpms/build.py similarity index 63% rename from conda_rpms/build.py rename to src/conda_rpms/build.py index f925641..970f677 100644 --- a/conda_rpms/build.py +++ b/src/conda_rpms/build.py @@ -6,11 +6,14 @@ import os import glob import subprocess +import typing +from pathlib import Path +from .logger import log -def name_version_release(spec_fh): +def name_version_release(spec_fh: typing.Iterable[str]) -> typing.Dict[str, str]: """ - Take the name, version and release number from the given filehandle pointing at a sepc file. + Take the name, version and release number from the given filehandle pointing at a spec file. """ content = {} for line in spec_fh: @@ -23,20 +26,26 @@ def name_version_release(spec_fh): return content -def build_new(rpmbuild_dir, rpm_directory): +def build_new(rpmbuild_dir: str, rpm_directory: str) -> None: """We rely on spec naming conventions to check that the build RPMs actually exist.""" - specs_directory = os.path.join(rpmbuild_dir, 'SPECS') - sources_directory = os.path.join(rpmbuild_dir, 'SOURCES') + build_dir = Path(rpmbuild_dir).resolve() + specs_directory = build_dir / "SPECS" for spec in sorted(glob.glob(os.path.join(specs_directory, '*.spec'))): - spec_path = os.path.join(specs_directory, spec) rpm_name = spec[:-5] - with open(spec_path, 'r') as fh: + with open(spec, 'r') as fh: spec_info = name_version_release(fh) rpm_name = '{name}-{version}-{release}.x86_64.rpm'.format(**spec_info) - if not os.path.exists(os.path.join(rpm_directory, rpm_name)): - subprocess.check_call(['rpmbuild', '-bb', '--define', "_topdir {}".format(rpmbuild_dir), - spec_path, '--force']) + rpm = Path(rpm_directory) / "x86_64" / rpm_name + if not rpm.exists(): + log.info(f"Building {spec} to {rpm}") + subprocess.check_call([ + 'rpmbuild', '-bb', + '--define', "_topdir {}".format(build_dir), + spec, '--force' + ]) + else: + log.info(f"RPM {rpm} already exists, skipping.") if __name__ == '__main__': diff --git a/src/conda_rpms/conda_compat.py b/src/conda_rpms/conda_compat.py new file mode 100755 index 0000000..28574ea --- /dev/null +++ b/src/conda_rpms/conda_compat.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from dataclasses import dataclass, asdict, fields +from pathlib import Path +from typing import Iterable, List, Optional + +from conda.api import PackageCacheData +from conda_package_handling.api import create as create_conda_tarball + +from .logger import log + + +class SpecTarget: + _ident = "__none__" + _id_string = "UndefinedSpec" + + @property + def id(self) -> str: + return self._id_string.format(**asdict(self)) + + +@dataclass +class CondaPackage(SpecTarget): + # The subset of conda package information we require + _ident = "pkg" + _id_string = "{name}-{version}-{build}" + name: str + version: str + build: str + url: str + package_tarball_full_path: str + extracted_package_dir: str + fn: str + + @classmethod + def from_url(cls, url: str) -> CondaPackage: + cached_pkgs = PackageCacheData.query_all(url) + if not cached_pkgs: + raise ValueError(f"No cache for {url}") + if len(cached_pkgs) > 1: + log.warn(f"Multiple cache records found for {url}, using the first.") + return CondaPackage( + *[getattr(cached_pkgs[0], f.name) for f in fields(CondaPackage)] + ) + + +@dataclass +class CondaEnvironment(SpecTarget): + _ident = "env" + _id_string = "{name}-{version}" + name: str + version: str + summary: Optional[str] + + +def read_conda_lockfile(lockfile: Iterable[str]) -> List[str]: + """Returns a list of package urls included in conda lock file. + + The file must include an @EXPLICIT marker. + """ + seen_explicit = False + + urls = [] + for line in lockfile: + line = line.strip() + if not line: + continue + if line.startswith("#"): + continue + if line == "@EXPLICIT": + seen_explicit = True + continue + urls.append(line) + if not seen_explicit: + raise ValueError("Provided lockfile does not include @EXPLICIT tag.") + return urls + + +def make_package_tarball(pkg: CondaPackage) -> Path: + """Return the path to a package's associated tar.bz2 tarball. + + If the conda pacakge is in the .conda format, this function + will also convert to the .tar.bz2 format and place it alongside + the .conda package. + + Returns the path to the tarball on disk. + """ + if not pkg.package_tarball_full_path.endswith(".tar.bz2"): + # we need to deal with the new .conda file type. + # Luckily, there is a library to do this so we will use it + # to convert .conda files into .tar.bz2 files and save them + # alongside the .conda and extracted package in the conda cache + cache_dir = Path(pkg.extracted_package_dir).parent + new_fn = pkg.fn.replace(".conda", ".tar.bz2") + tarball = create_conda_tarball( + pkg.extracted_package_dir, file_list=None, out_fn=str(cache_dir / new_fn) + ) + log.info(f"Created tar.bz2 from {pkg.fn}") + else: + tarball = pkg.package_tarball_full_path + return Path(tarball) diff --git a/conda_rpms/install.py b/src/conda_rpms/dist/install.py similarity index 100% rename from conda_rpms/install.py rename to src/conda_rpms/dist/install.py diff --git a/src/conda_rpms/generate.py b/src/conda_rpms/generate.py new file mode 100755 index 0000000..bc5ea1d --- /dev/null +++ b/src/conda_rpms/generate.py @@ -0,0 +1,269 @@ +# documentation on the conda API +# https://docs.conda.io/projects/conda/en/latest/api/index.html + +from __future__ import annotations + +from dataclasses import dataclass, asdict +import json +import os +import shutil +from pathlib import Path +import sys +from typing import Iterable, List, NamedTuple, Optional, Union + +import jinja2 +import yaml + +from .logger import log +from .conda_compat import ( + CondaPackage, + CondaEnvironment, + make_package_tarball, + read_conda_lockfile, +) + +# configure the installer to use the same version +# of python as the invoker of this routine +INSTALLER_VERSION = "{0}.{1}.{2}".format(*sys.version_info) + + +@dataclass +class PackageSpec: + package: CondaPackage # full name of the package + spec: Path # the path to a written RPM spec file + tarball: Path # the path the associated tar.bz2 tarball of files + + +_module_dir = Path(__file__).resolve().parent +install_script_path = _module_dir / "dist/install.py" +template_dir = _module_dir / "templates" + +loader = jinja2.FileSystemLoader(template_dir) +env = jinja2.Environment(loader=loader) +pkg_spec_tmpl = env.get_template("pkg.spec.template") +env_spec_tmpl = env.get_template("env.spec.template") +installer_spec_tmpl = env.get_template("installer.spec.template") + + +def render_package_spec(pkg_dir: Path, rpm_namespace: str, install_prefix: Path) -> str: + """Render an package RPM spec. + + This relies on the conda package cache having already + downloaded and extracted the specific pacakge and + stored it in the local cache. + + Returns the rendered RPM spec as a string. + """ + if not pkg_dir.exists(): + raise FileNotFoundError(f"Package dir {pkg_dir} does not exist.") + + with open(pkg_dir / "info/index.json", "r") as fh: + pkginfo = json.load(fh) + + recipe_yaml = pkg_dir / "info/recipe/meta.yaml" + if recipe_yaml.exists(): + with open(recipe_yaml, "r") as fh: + meta = yaml.safe_load(fh) + else: + meta = {} + + meta_about = meta.setdefault("about", {}) + meta_about.setdefault("license", pkginfo.get("license")) + meta_about.setdefault("summary", "The {} package".format(pkginfo["name"])) + + return pkg_spec_tmpl.render( + pkginfo=pkginfo, + meta=meta, + rpm_prefix=rpm_namespace, + install_prefix=install_prefix, + ) + + +def write_spec(spec: str, filename: Path, overwrite=True) -> Path: + if filename.exists(): + with open(filename, "r") as fh: + existing_spec = fh.read() + if spec == existing_spec: + log.info(f"Spec {filename} already exists and is identical, continue.") + return filename + else: + if overwrite: + log.warn(f"Spec {filename} will be overwritten.") + else: + log.warn(f"Spec {filename} exists and is different. Abort!") + raise AttributeError( + "Spec differs from existing and overwrite=False" + ) + + log.info(f"Writing spec {filename}") + with open(filename, "w") as fh: + fh.write(spec) + return filename + + +def render_environment_spec( + environment: CondaEnvironment, + packages: List[CondaPackage], + install_prefix: Path, + rpm_namespace: str, +) -> str: + return env_spec_tmpl.render( + env=asdict(environment), + pkgs=[p.id for p in packages], + install_prefix=str(install_prefix), + rpm_prefix=rpm_namespace, + ) + + +def write_package_rpm_spec( + pkg: CondaPackage, outdir: Path, install_prefix: Path, rpm_namespace: str +) -> Path: + pkg_dir = Path(pkg.extracted_package_dir) + spec = render_package_spec(pkg_dir, rpm_namespace, install_prefix) + spec_filename = "{namespace}-pkg-{id}.spec".format( + namespace=rpm_namespace, id=pkg.id + ) + return write_spec(spec, outdir / "SPECS" / spec_filename) + + +def write_environment_rpm_spec( + environment: CondaEnvironment, + packages: List[CondaPackage], + outdir: Path, + install_prefix: Path, + rpm_namespace: str, +) -> Path: + """Write an environment RPM spec to disk. + + An environment spec consists of: + + 1. Dependencies on all package RPMs that make up the environment. + 2. A dependency on the Installer package required to deploy the environment on the host. + + Writes an rpm .spec file to `outdir/SPECS`. + """ + spec = render_environment_spec(environment, packages, install_prefix, rpm_namespace) + spec_filename = f"{rpm_namespace}-env-{environment.id}.spec" + return write_spec(spec, outdir / "SPECS" / spec_filename) + + +def render_installer_rpm_spec( + python_package: CondaPackage, install_prefix: Path, rpm_namespace: str +) -> str: + return installer_spec_tmpl.render( + install_prefix=install_prefix, rpm_prefix=rpm_namespace, pkg_info=python_package + ) + + +def write_installer_rpm_spec( + python_package: CondaPackage, outdir: Path, install_prefix: Path, rpm_namespace: str +) -> Path: + spec = render_installer_rpm_spec(python_package, install_prefix, rpm_namespace) + spec_filename = f"{rpm_namespace}-installer.spec" + return write_spec(spec, outdir / "SPECS" / spec_filename, overwrite=False) + + +def create_installer( + py_ver: str, outdir: Path, install_prefix: Path, rpm_namespace: str +) -> PackageSpec: + pkg = CondaPackage.from_url(f"python=={py_ver}") + spec = write_installer_rpm_spec(pkg, outdir, install_prefix, rpm_namespace) + tarball = make_package_tarball(pkg) + shutil.copy(install_script_path, outdir / "SOURCES") + return PackageSpec(pkg, spec, tarball) + + +def environment_to_rpms( + name: str, + lockfile: Path, + outdir: Path, + install_prefix: Path = Path("/opt/conda-dist"), + rpm_namespace: str = "CondaDist", +): + """Take an explicit conda lock file and turn it into a set of RPMs.""" + config = outdir, install_prefix, rpm_namespace + + with open(lockfile, "r") as f: + urls = read_conda_lockfile(f) + + if not outdir.is_dir(): + outdir.mkdir() + + log.info(f"Generating RPM environment from {lockfile}.") + log.info(f"{len(urls)} packages to be rendered.") + + log.info(f"Checking conda cache for pacakges.") + pkgs = [CondaPackage.from_url(url) for url in urls] + + log.info("Rendering all package specs.") + specdir = outdir / "SPECS" + specdir.mkdir(exist_ok=True) + specs: List[PackageSpec] = [create_rpm_spec(pkg, *config) for pkg in pkgs] + + log.info("Rendering installer") + installer = create_installer(INSTALLER_VERSION, *config) + specs.append(installer) + + log.info("Copying sources") + sourcedir = outdir / "SOURCES" + sourcedir.mkdir(exist_ok=True) + for spec in specs: + shutil.copy(spec.tarball, sourcedir) + + environment = CondaEnvironment(args.name, "1.0", None) + write_environment_rpm_spec(environment, pkgs, outdir, install_prefix, rpm_namespace) + + +def create_rpm_spec(pkg, outdir, install_prefix, rpm_namespace): + spec = write_package_rpm_spec(pkg, outdir, install_prefix, rpm_namespace) + tarball = make_package_tarball(pkg) + return PackageSpec(pkg.id, spec, tarball) + + +if __name__ == "__main__": + import argparse + from textwrap import dedent + + from tqdm.contrib.logging import logging_redirect_tqdm + + parser = argparse.ArgumentParser() + parser.add_argument( + "file", help="The conda lockfile to produce an RPM package for." + ) + parser.add_argument( + "--name", "-n", required=True, help="The name of the environment to be created." + ) + parser.add_argument( + "--output", + "-o", + default="rpmbuild", + help="The directory to write out the RPM spec files and sources. Default: rpmbuild", + ) + parser.add_argument( + "--rpm-namespace", + default="CondaDist", + help=dedent( + r"""The namespace of the RPMs produced. e.g. a package will be named + {rpm-namespace}-{package}.rpm""" + ), + ) + parser.add_argument( + "--install-prefix", + "-p", + default="/opt/conda-dist", + help=dedent( + r"""The destination prefix where packages will be + installed by the RPM. + The environment will go to {install-prefix}/envs/{name}. + Shared packages will go to {install-prefix}/pkgs/{package}""" + ), + ) + args = parser.parse_args() + + environment_to_rpms( + args.name, + Path(args.file), + Path(args.output), + Path(args.install_prefix), + args.rpm_namespace, + ) diff --git a/src/conda_rpms/logger.py b/src/conda_rpms/logger.py new file mode 100755 index 0000000..1c70c8a --- /dev/null +++ b/src/conda_rpms/logger.py @@ -0,0 +1,6 @@ +import logging + +logging.basicConfig() + +log = logging.getLogger('conda_rpms') +log.setLevel(logging.INFO) \ No newline at end of file diff --git a/conda_rpms/templates/taggedenv.spec.template b/src/conda_rpms/templates/env.spec.template similarity index 74% rename from conda_rpms/templates/taggedenv.spec.template rename to src/conda_rpms/templates/env.spec.template index 048be02..f7b3dc0 100644 --- a/conda_rpms/templates/taggedenv.spec.template +++ b/src/conda_rpms/templates/env.spec.template @@ -1,15 +1,12 @@ -{% set env_dir = '{}/environments/{}/{}'.format(install_prefix, env.name, env.tag) %} +{% set env_dir = '{}/environments/{}/{}'.format(install_prefix, env.name, env.version) %} -Name: {{ rpm_prefix }}-env-{{ env.name }}-tag-{{ env.tag }} +Name: {{ rpm_prefix }}-env-{{ env.name }} Version: {{ env.version }} Release: 0 -Summary: {{ env.summary }} +Summary: {{ env.summary }} License: BSD 3 -{% if env.url -%} -URL: {{ env.url }} -{%- endif %} -BuildRoot: %{_tmppath}/env-{{ env.name }}-tag-{{ env.tag }}-{{env.version}} +BuildRoot: %{_tmppath}/env-{{ env.name }}-{{env.version}} Requires: {{ rpm_prefix}}-installer {% for pkg in pkgs -%} @@ -18,21 +15,13 @@ Requires: {{ rpm_prefix }}-pkg-{{ pkg }} %description -This is the {{ env.name }}-{{env.tag}} {{rpm_prefix}} environment, described as: +This is the {{ env.name }} {{rpm_prefix}} environment, described as: - {{ env.summary|indent }} - -Unlike normal RPMs, {{rpm_prefix}} environment RPMs create a software stack at +Unlike normal RPMs, {{rpm_prefix}} environment RPMs create a conda environment at install time (i.e. they are not pre-built). This allows the environments to share assets that otherwise wouldn't be sharable, thus making environments themselves very lightweight. -{% if env.spec -%} -This environment has been generated with the following conda specification: - - {{ env.spec|indent }} -{%- endif %} - %prep # Clear up any pre-existing build-root. rm -rf $RPM_BUILD_ROOT/ diff --git a/conda_rpms/templates/installer.spec.template b/src/conda_rpms/templates/installer.spec.template similarity index 100% rename from conda_rpms/templates/installer.spec.template rename to src/conda_rpms/templates/installer.spec.template diff --git a/conda_rpms/templates/pkg.spec.template b/src/conda_rpms/templates/pkg.spec.template similarity index 96% rename from conda_rpms/templates/pkg.spec.template rename to src/conda_rpms/templates/pkg.spec.template index 3c19d88..f969362 100644 --- a/conda_rpms/templates/pkg.spec.template +++ b/src/conda_rpms/templates/pkg.spec.template @@ -3,7 +3,7 @@ Name: {{ rpm_prefix }}-pkg-{{ pkg_id }} Version: 1 Release: 0 -Summary: {{ meta.about.summary }} +Summary: {{ meta.about.summary | replace("\n", " ") }} License: {{ pkginfo.license or 'unknown' }} {% if meta.about.url %} @@ -27,7 +27,7 @@ AutoReqProv: no This is a conda distribution for {{ pkg_id }}, which can be linked by other RPMs but not used directly. - + {{ meta.about.summary }} diff --git a/conda_rpms/tests/unit/__init__.py b/tests/__init__.py old mode 100644 new mode 100755 similarity index 100% rename from conda_rpms/tests/unit/__init__.py rename to tests/__init__.py diff --git a/tests/unit/test_build.py b/tests/unit/test_build.py new file mode 100755 index 0000000..5267cc7 --- /dev/null +++ b/tests/unit/test_build.py @@ -0,0 +1,38 @@ +import textwrap + +from conda_rpms.build import name_version_release + + +def _check_output(spec): + expected = {'name': 'foo', 'release':'2', 'version':'1'} + actual = name_version_release(textwrap.dedent(spec).split('\n')) + assert expected == actual + +def test_multiple_names(): + spec = """ + Name: foo + Version: 1 + Release: 2 + Name: bar + """ + _check_output(spec) + +def test_multiple_versions(): + # should return the first version number + spec = """ + Name: foo + Version: 1 + Release: 2 + Version: 3 + """ + _check_output(spec) + +def test_multiple_releases(): + # should return the first Release number + spec = """ + Name: foo + Version: 1 + Release: 2 + Release: 3 + """ + _check_output(spec) \ No newline at end of file diff --git a/tests/unit/test_lockfile.py b/tests/unit/test_lockfile.py new file mode 100755 index 0000000..aca3d75 --- /dev/null +++ b/tests/unit/test_lockfile.py @@ -0,0 +1,46 @@ +import pytest + +from conda_rpms.conda_compat import read_conda_lockfile + +# def test_parse_url(): +# url = "https://conda.anaconda.org/conda-forge/linux-64/astropy-4.2.1-py37h27cfd23_1.tar.bz2" +# pkg = parse_conda_url(url) +# assert pkg.name == "astropy" +# assert pkg.build == "py37h27cfd23_1" +# assert pkg.format == "tar.bz2" +# assert pkg.url == url + +# url = "https://conda.anaconda.org/conda-forge/linux-64/invalid-packagename.conda" +# with pytest.raises(ValueError) as execinfo: +# parse_conda_url(url) +# assert "Cannot parse name" in str(execinfo.value) + +# url = "https://conda.anaconda.org/conda-forge/linux-64/invalid-package-format.zip" +# with pytest.raises(ValueError) as execinfo: +# parse_conda_url(url) +# assert "file format" in str(execinfo.value) + +# TODO: mock conda PackageCacheQuery instead of the parse_url above + + +def test_read_conda_lockfile(): + file = """# platform: linux-64 +# env_hash: 2785ad92fa19c56df4d0b4315d6fea121ca9b6092185d5ea016d9571ef85efca +@EXPLICIT +https://conda.anaconda.org/conda-forge/linux-64/ca-certificates-2021.5.30-ha878542_0.tar.bz2#6a777890e94194dc94a29a76d2a7e721 +https://conda.anaconda.org/conda-forge/noarch/font-ttf-dejavu-sans-mono-2.37-hab24e00_0.tar.bz2#0c96522c6bdaed4b1566d11387caaf45 +https://conda.anaconda.org/conda-forge/noarch/font-ttf-inconsolata-3.000-h77eed37_0.tar.bz2#34893075a5c9e55cdafac56607368fc6 +https://conda.anaconda.org/conda-forge/noarch/font-ttf-source-code-pro-2.038-h77eed37_0.tar.bz2#4d59c254e01d9cde7957100457e2d5fb +https://conda.anaconda.org/conda-forge/noarch/font-ttf-ubuntu-0.83-hab24e00_0.tar.bz2#19410c3df09dfb12d1206132a1d357c5 +https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.35.1-hea4e1c9_2.tar.bz2#83610dba766a186bdc7a116053b782a4 +https://conda.anaconda.org/conda-forge/linux-64/libgfortran5-9.3.0-hff62375_19.tar.bz2#c2d8da3cb171e4aa642d20c6e4e42a04 +https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-ng-9.3.0-h6de172a_19.tar.bz2#cd9a24a8dde03ec0cf0e603b0bea85a1 +https://conda.anaconda.org/conda-forge/linux-64/mpi-1.0-mpich.tar.bz2#c1fcff3417b5a22bbc4cf6e8c23648cf +https://conda.anaconda.org/conda-forge/linux-64/mysql-common-8.0.23-ha770c72_2.tar.bz2#ce876d0c998e1e2eb1dc67b01937737f +https://conda.anaconda.org/conda-forge/noarch/fonts-conda-forge-1-0.tar.bz2#f766549260d6815b0c52253f1fb1bb29 +https://conda.anaconda.org/conda-forge/linux-64/libgfortran-ng-9.3.0-hff62375_19.tar.bz2#aea379bd68fdcdf9499fa1453f852ac1 +https://conda.anaconda.org/conda-forge/linux-64/libgomp-9.3.0-h2828fa1_19.tar.bz2#ab0a307912033126da02507b59e79ec9""".split('\n') + pkgs = read_conda_lockfile(file) + assert len(pkgs) == 13 + assert pkgs[0].name == "ca-certificates" + From 2f623d15cf8014dd02408fe4edbf3c9e1e894ed6 Mon Sep 17 00:00:00 2001 From: James Penn Date: Mon, 14 Jun 2021 10:00:36 +0100 Subject: [PATCH 2/9] Removed tmp docs --- tmp_overview_docs/css/style.css | 35 - tmp_overview_docs/js/d3.v3.min.js | 5 - tmp_overview_docs/js/dagre-d3.js | 17572 ----------------- tmp_overview_docs/scitools-env-workflow.html | 271 - tmp_overview_docs/wheels.png | Bin 7799 -> 0 bytes 5 files changed, 17883 deletions(-) delete mode 100644 tmp_overview_docs/css/style.css delete mode 100644 tmp_overview_docs/js/d3.v3.min.js delete mode 100644 tmp_overview_docs/js/dagre-d3.js delete mode 100644 tmp_overview_docs/scitools-env-workflow.html delete mode 100644 tmp_overview_docs/wheels.png diff --git a/tmp_overview_docs/css/style.css b/tmp_overview_docs/css/style.css deleted file mode 100644 index 06db0ca..0000000 --- a/tmp_overview_docs/css/style.css +++ /dev/null @@ -1,35 +0,0 @@ -body { - width: 960px; - margin: 0 auto; - color: #333; - font-weight: 300; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serf; -} - -h1 { - font-size: 3em; - font-weight: 300; -} - -h2 { - font-size: 1.5em; - font-weight: 300; -} - -section { - margin-bottom: 3em; -} - -section p { - text-align: justify; -} - -svg { - border: 1px solid #ccc; - overflow: hidden; - margin: 0 auto; -} - -pre { - border: 1px solid #ccc; -} diff --git a/tmp_overview_docs/js/d3.v3.min.js b/tmp_overview_docs/js/d3.v3.min.js deleted file mode 100644 index 1664873..0000000 --- a/tmp_overview_docs/js/d3.v3.min.js +++ /dev/null @@ -1,5 +0,0 @@ -!function(){function n(n){return n&&(n.ownerDocument||n.document||n).documentElement}function t(n){return n&&(n.ownerDocument&&n.ownerDocument.defaultView||n.document&&n||n.defaultView)}function e(n,t){return t>n?-1:n>t?1:n>=t?0:NaN}function r(n){return null===n?NaN:+n}function i(n){return!isNaN(n)}function u(n){return{left:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)<0?r=u+1:i=u}return r},right:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)>0?i=u:r=u+1}return r}}}function o(n){return n.length}function a(n){for(var t=1;n*t%1;)t*=10;return t}function l(n,t){for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}function c(){this._=Object.create(null)}function f(n){return(n+="")===bo||n[0]===_o?_o+n:n}function s(n){return(n+="")[0]===_o?n.slice(1):n}function h(n){return f(n)in this._}function p(n){return(n=f(n))in this._&&delete this._[n]}function g(){var n=[];for(var t in this._)n.push(s(t));return n}function v(){var n=0;for(var t in this._)++n;return n}function d(){for(var n in this._)return!1;return!0}function y(){this._=Object.create(null)}function m(n){return n}function M(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function x(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e=0,r=wo.length;r>e;++e){var i=wo[e]+t;if(i in n)return i}}function b(){}function _(){}function w(n){function t(){for(var t,r=e,i=-1,u=r.length;++ie;e++)for(var i,u=n[e],o=0,a=u.length;a>o;o++)(i=u[o])&&t(i,o,e);return n}function Z(n){return ko(n,qo),n}function V(n){var t,e;return function(r,i,u){var o,a=n[u].update,l=a.length;for(u!=e&&(e=u,t=0),i>=t&&(t=i+1);!(o=a[t])&&++t0&&(n=n.slice(0,a));var c=To.get(n);return c&&(n=c,l=B),a?t?i:r:t?b:u}function $(n,t){return function(e){var r=ao.event;ao.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{ao.event=r}}}function B(n,t){var e=$(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function W(e){var r=".dragsuppress-"+ ++Do,i="click"+r,u=ao.select(t(e)).on("touchmove"+r,S).on("dragstart"+r,S).on("selectstart"+r,S);if(null==Ro&&(Ro="onselectstart"in e?!1:x(e.style,"userSelect")),Ro){var o=n(e).style,a=o[Ro];o[Ro]="none"}return function(n){if(u.on(r,null),Ro&&(o[Ro]=a),n){var t=function(){u.on(i,null)};u.on(i,function(){S(),t()},!0),setTimeout(t,0)}}}function J(n,e){e.changedTouches&&(e=e.changedTouches[0]);var r=n.ownerSVGElement||n;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Po){var u=t(n);if(u.scrollX||u.scrollY){r=ao.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Po=!(o.f||o.e),r.remove()}}return Po?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(n.getScreenCTM().inverse()),[i.x,i.y]}var a=n.getBoundingClientRect();return[e.clientX-a.left-n.clientLeft,e.clientY-a.top-n.clientTop]}function G(){return ao.event.changedTouches[0].identifier}function K(n){return n>0?1:0>n?-1:0}function Q(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function nn(n){return n>1?0:-1>n?Fo:Math.acos(n)}function tn(n){return n>1?Io:-1>n?-Io:Math.asin(n)}function en(n){return((n=Math.exp(n))-1/n)/2}function rn(n){return((n=Math.exp(n))+1/n)/2}function un(n){return((n=Math.exp(2*n))-1)/(n+1)}function on(n){return(n=Math.sin(n/2))*n}function an(){}function ln(n,t,e){return this instanceof ln?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof ln?new ln(n.h,n.s,n.l):_n(""+n,wn,ln):new ln(n,t,e)}function cn(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?u+(o-u)*n/60:180>n?o:240>n?u+(o-u)*(240-n)/60:u}function i(n){return Math.round(255*r(n))}var u,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,u=2*e-o,new mn(i(n+120),i(n),i(n-120))}function fn(n,t,e){return this instanceof fn?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof fn?new fn(n.h,n.c,n.l):n instanceof hn?gn(n.l,n.a,n.b):gn((n=Sn((n=ao.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new fn(n,t,e)}function sn(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new hn(e,Math.cos(n*=Yo)*t,Math.sin(n)*t)}function hn(n,t,e){return this instanceof hn?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof hn?new hn(n.l,n.a,n.b):n instanceof fn?sn(n.h,n.c,n.l):Sn((n=mn(n)).r,n.g,n.b):new hn(n,t,e)}function pn(n,t,e){var r=(n+16)/116,i=r+t/500,u=r-e/200;return i=vn(i)*na,r=vn(r)*ta,u=vn(u)*ea,new mn(yn(3.2404542*i-1.5371385*r-.4985314*u),yn(-.969266*i+1.8760108*r+.041556*u),yn(.0556434*i-.2040259*r+1.0572252*u))}function gn(n,t,e){return n>0?new fn(Math.atan2(e,t)*Zo,Math.sqrt(t*t+e*e),n):new fn(NaN,NaN,n)}function vn(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function dn(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function yn(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function mn(n,t,e){return this instanceof mn?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof mn?new mn(n.r,n.g,n.b):_n(""+n,mn,cn):new mn(n,t,e)}function Mn(n){return new mn(n>>16,n>>8&255,255&n)}function xn(n){return Mn(n)+""}function bn(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function _n(n,t,e){var r,i,u,o=0,a=0,l=0;if(r=/([a-z]+)\((.*)\)/.exec(n=n.toLowerCase()))switch(i=r[2].split(","),r[1]){case"hsl":return e(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(Nn(i[0]),Nn(i[1]),Nn(i[2]))}return(u=ua.get(n))?t(u.r,u.g,u.b):(null==n||"#"!==n.charAt(0)||isNaN(u=parseInt(n.slice(1),16))||(4===n.length?(o=(3840&u)>>4,o=o>>4|o,a=240&u,a=a>>4|a,l=15&u,l=l<<4|l):7===n.length&&(o=(16711680&u)>>16,a=(65280&u)>>8,l=255&u)),t(o,a,l))}function wn(n,t,e){var r,i,u=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-u,l=(o+u)/2;return a?(i=.5>l?a/(o+u):a/(2-o-u),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=NaN,i=l>0&&1>l?0:r),new ln(r,i,l)}function Sn(n,t,e){n=kn(n),t=kn(t),e=kn(e);var r=dn((.4124564*n+.3575761*t+.1804375*e)/na),i=dn((.2126729*n+.7151522*t+.072175*e)/ta),u=dn((.0193339*n+.119192*t+.9503041*e)/ea);return hn(116*i-16,500*(r-i),200*(i-u))}function kn(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Nn(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function En(n){return"function"==typeof n?n:function(){return n}}function An(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),Cn(t,e,n,r)}}function Cn(n,t,e,r){function i(){var n,t=l.status;if(!t&&Ln(l)||t>=200&&300>t||304===t){try{n=e.call(u,l)}catch(r){return void o.error.call(u,r)}o.load.call(u,n)}else o.error.call(u,l)}var u={},o=ao.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,c=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(n)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(n){var t=ao.event;ao.event=n;try{o.progress.call(u,l)}finally{ao.event=t}},u.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",u)},u.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",u):t},u.responseType=function(n){return arguments.length?(c=n,u):c},u.response=function(n){return e=n,u},["get","post"].forEach(function(n){u[n]=function(){return u.send.apply(u,[n].concat(co(arguments)))}}),u.send=function(e,r,i){if(2===arguments.length&&"function"==typeof r&&(i=r,r=null),l.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),l.setRequestHeader)for(var f in a)l.setRequestHeader(f,a[f]);return null!=t&&l.overrideMimeType&&l.overrideMimeType(t),null!=c&&(l.responseType=c),null!=i&&u.on("error",i).on("load",function(n){i(null,n)}),o.beforesend.call(u,l),l.send(null==r?null:r),u},u.abort=function(){return l.abort(),u},ao.rebind(u,o,"on"),null==r?u:u.get(zn(r))}function zn(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function Ln(n){var t=n.responseType;return t&&"text"!==t?n.response:n.responseText}function qn(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var i=e+t,u={c:n,t:i,n:null};return aa?aa.n=u:oa=u,aa=u,la||(ca=clearTimeout(ca),la=1,fa(Tn)),u}function Tn(){var n=Rn(),t=Dn()-n;t>24?(isFinite(t)&&(clearTimeout(ca),ca=setTimeout(Tn,t)),la=0):(la=1,fa(Tn))}function Rn(){for(var n=Date.now(),t=oa;t;)n>=t.t&&t.c(n-t.t)&&(t.c=null),t=t.n;return n}function Dn(){for(var n,t=oa,e=1/0;t;)t.c?(t.t8?function(n){return n/e}:function(n){return n*e},symbol:n}}function jn(n){var t=n.decimal,e=n.thousands,r=n.grouping,i=n.currency,u=r&&e?function(n,t){for(var i=n.length,u=[],o=0,a=r[0],l=0;i>0&&a>0&&(l+a+1>t&&(a=Math.max(1,t-l)),u.push(n.substring(i-=a,i+a)),!((l+=a+1)>t));)a=r[o=(o+1)%r.length];return u.reverse().join(e)}:m;return function(n){var e=ha.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"-",l=e[4]||"",c=e[5],f=+e[6],s=e[7],h=e[8],p=e[9],g=1,v="",d="",y=!1,m=!0;switch(h&&(h=+h.substring(1)),(c||"0"===r&&"="===o)&&(c=r="0",o="="),p){case"n":s=!0,p="g";break;case"%":g=100,d="%",p="f";break;case"p":g=100,d="%",p="r";break;case"b":case"o":case"x":case"X":"#"===l&&(v="0"+p.toLowerCase());case"c":m=!1;case"d":y=!0,h=0;break;case"s":g=-1,p="r"}"$"===l&&(v=i[0],d=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=pa.get(p)||Fn;var M=c&&s;return function(n){var e=d;if(y&&n%1)return"";var i=0>n||0===n&&0>1/n?(n=-n,"-"):"-"===a?"":a;if(0>g){var l=ao.formatPrefix(n,h);n=l.scale(n),e=l.symbol+d}else n*=g;n=p(n,h);var x,b,_=n.lastIndexOf(".");if(0>_){var w=m?n.lastIndexOf("e"):-1;0>w?(x=n,b=""):(x=n.substring(0,w),b=n.substring(w))}else x=n.substring(0,_),b=t+n.substring(_+1);!c&&s&&(x=u(x,1/0));var S=v.length+x.length+b.length+(M?0:i.length),k=f>S?new Array(S=f-S+1).join(r):"";return M&&(x=u(k+x,k.length?f-b.length:1/0)),i+=v,n=x+b,("<"===o?i+n+k:">"===o?k+i+n:"^"===o?k.substring(0,S>>=1)+i+n+k.substring(S):i+(M?n:k+n))+e}}}function Fn(n){return n+""}function Hn(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function On(n,t,e){function r(t){var e=n(t),r=u(e,1);return r-t>t-e?e:r}function i(e){return t(e=n(new va(e-1)),1),e}function u(n,e){return t(n=new va(+n),e),n}function o(n,r,u){var o=i(n),a=[];if(u>1)for(;r>o;)e(o)%u||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{va=Hn;var r=new Hn;return r._=n,o(r,t,e)}finally{va=Date}}n.floor=n,n.round=r,n.ceil=i,n.offset=u,n.range=o;var l=n.utc=In(n);return l.floor=l,l.round=In(r),l.ceil=In(i),l.offset=In(u),l.range=a,n}function In(n){return function(t,e){try{va=Hn;var r=new Hn;return r._=t,n(r,e)._}finally{va=Date}}}function Yn(n){function t(n){function t(t){for(var e,i,u,o=[],a=-1,l=0;++aa;){if(r>=c)return-1;if(i=t.charCodeAt(a++),37===i){if(o=t.charAt(a++),u=C[o in ya?t.charAt(a++):o],!u||(r=u(n,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){_.lastIndex=0;var r=_.exec(t.slice(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){x.lastIndex=0;var r=x.exec(t.slice(e));return r?(n.w=b.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){N.lastIndex=0;var r=N.exec(t.slice(e));return r?(n.m=E.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.slice(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,A.c.toString(),t,r)}function l(n,t,r){return e(n,A.x.toString(),t,r)}function c(n,t,r){return e(n,A.X.toString(),t,r)}function f(n,t,e){var r=M.get(t.slice(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var s=n.dateTime,h=n.date,p=n.time,g=n.periods,v=n.days,d=n.shortDays,y=n.months,m=n.shortMonths;t.utc=function(n){function e(n){try{va=Hn;var t=new va;return t._=n,r(t)}finally{va=Date}}var r=t(n);return e.parse=function(n){try{va=Hn;var t=r.parse(n);return t&&t._}finally{va=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ct;var M=ao.map(),x=Vn(v),b=Xn(v),_=Vn(d),w=Xn(d),S=Vn(y),k=Xn(y),N=Vn(m),E=Xn(m);g.forEach(function(n,t){M.set(n.toLowerCase(),t)});var A={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return m[n.getMonth()]},B:function(n){return y[n.getMonth()]},c:t(s),d:function(n,t){return Zn(n.getDate(),t,2)},e:function(n,t){return Zn(n.getDate(),t,2)},H:function(n,t){return Zn(n.getHours(),t,2)},I:function(n,t){return Zn(n.getHours()%12||12,t,2)},j:function(n,t){return Zn(1+ga.dayOfYear(n),t,3)},L:function(n,t){return Zn(n.getMilliseconds(),t,3)},m:function(n,t){return Zn(n.getMonth()+1,t,2)},M:function(n,t){return Zn(n.getMinutes(),t,2)},p:function(n){return g[+(n.getHours()>=12)]},S:function(n,t){return Zn(n.getSeconds(),t,2)},U:function(n,t){return Zn(ga.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return Zn(ga.mondayOfYear(n),t,2)},x:t(h),X:t(p),y:function(n,t){return Zn(n.getFullYear()%100,t,2)},Y:function(n,t){return Zn(n.getFullYear()%1e4,t,4)},Z:at,"%":function(){return"%"}},C={a:r,A:i,b:u,B:o,c:a,d:tt,e:tt,H:rt,I:rt,j:et,L:ot,m:nt,M:it,p:f,S:ut,U:Bn,w:$n,W:Wn,x:l,X:c,y:Gn,Y:Jn,Z:Kn,"%":lt};return t}function Zn(n,t,e){var r=0>n?"-":"",i=(r?-n:n)+"",u=i.length;return r+(e>u?new Array(e-u+1).join(t)+i:i)}function Vn(n){return new RegExp("^(?:"+n.map(ao.requote).join("|")+")","i")}function Xn(n){for(var t=new c,e=-1,r=n.length;++e68?1900:2e3)}function nt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function tt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function et(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function rt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function it(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function ut(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function ot(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function at(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=xo(t)/60|0,i=xo(t)%60;return e+Zn(r,"0",2)+Zn(i,"0",2)}function lt(n,t,e){Ma.lastIndex=0;var r=Ma.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function ct(n){for(var t=n.length,e=-1;++e=0?1:-1,a=o*e,l=Math.cos(t),c=Math.sin(t),f=u*c,s=i*l+f*Math.cos(a),h=f*o*Math.sin(a);ka.add(Math.atan2(h,s)),r=n,i=l,u=c}var t,e,r,i,u;Na.point=function(o,a){Na.point=n,r=(t=o)*Yo,i=Math.cos(a=(e=a)*Yo/2+Fo/4),u=Math.sin(a)},Na.lineEnd=function(){n(t,e)}}function dt(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function yt(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function mt(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function Mt(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function xt(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function bt(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function _t(n){return[Math.atan2(n[1],n[0]),tn(n[2])]}function wt(n,t){return xo(n[0]-t[0])a;++a)i.point((e=n[a])[0],e[1]);return void i.lineEnd()}var l=new Tt(e,n,null,!0),c=new Tt(e,null,l,!1);l.o=c,u.push(l),o.push(c),l=new Tt(r,n,null,!1),c=new Tt(r,null,l,!0),l.o=c,u.push(l),o.push(c)}}),o.sort(t),qt(u),qt(o),u.length){for(var a=0,l=e,c=o.length;c>a;++a)o[a].e=l=!l;for(var f,s,h=u[0];;){for(var p=h,g=!0;p.v;)if((p=p.n)===h)return;f=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(g)for(var a=0,c=f.length;c>a;++a)i.point((s=f[a])[0],s[1]);else r(p.x,p.n.x,1,i);p=p.n}else{if(g){f=p.p.z;for(var a=f.length-1;a>=0;--a)i.point((s=f[a])[0],s[1])}else r(p.x,p.p.x,-1,i);p=p.p}p=p.o,f=p.z,g=!g}while(!p.v);i.lineEnd()}}}function qt(n){if(t=n.length){for(var t,e,r=0,i=n[0];++r0){for(b||(u.polygonStart(),b=!0),u.lineStart();++o1&&2&t&&e.push(e.pop().concat(e.shift())),p.push(e.filter(Dt))}var p,g,v,d=t(u),y=i.invert(r[0],r[1]),m={point:o,lineStart:l,lineEnd:c,polygonStart:function(){m.point=f,m.lineStart=s,m.lineEnd=h,p=[],g=[]},polygonEnd:function(){m.point=o,m.lineStart=l,m.lineEnd=c,p=ao.merge(p);var n=Ot(y,g);p.length?(b||(u.polygonStart(),b=!0),Lt(p,Ut,n,e,u)):n&&(b||(u.polygonStart(),b=!0),u.lineStart(),e(null,null,1,u),u.lineEnd()),b&&(u.polygonEnd(),b=!1),p=g=null},sphere:function(){u.polygonStart(),u.lineStart(),e(null,null,1,u),u.lineEnd(),u.polygonEnd()}},M=Pt(),x=t(M),b=!1;return m}}function Dt(n){return n.length>1}function Pt(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:b,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Ut(n,t){return((n=n.x)[0]<0?n[1]-Io-Uo:Io-n[1])-((t=t.x)[0]<0?t[1]-Io-Uo:Io-t[1])}function jt(n){var t,e=NaN,r=NaN,i=NaN;return{lineStart:function(){n.lineStart(),t=1},point:function(u,o){var a=u>0?Fo:-Fo,l=xo(u-e);xo(l-Fo)0?Io:-Io),n.point(i,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(u,r),t=0):i!==a&&l>=Fo&&(xo(e-i)Uo?Math.atan((Math.sin(t)*(u=Math.cos(r))*Math.sin(e)-Math.sin(r)*(i=Math.cos(t))*Math.sin(n))/(i*u*o)):(t+r)/2}function Ht(n,t,e,r){var i;if(null==n)i=e*Io,r.point(-Fo,i),r.point(0,i),r.point(Fo,i),r.point(Fo,0),r.point(Fo,-i),r.point(0,-i),r.point(-Fo,-i),r.point(-Fo,0),r.point(-Fo,i);else if(xo(n[0]-t[0])>Uo){var u=n[0]a;++a){var c=t[a],f=c.length;if(f)for(var s=c[0],h=s[0],p=s[1]/2+Fo/4,g=Math.sin(p),v=Math.cos(p),d=1;;){d===f&&(d=0),n=c[d];var y=n[0],m=n[1]/2+Fo/4,M=Math.sin(m),x=Math.cos(m),b=y-h,_=b>=0?1:-1,w=_*b,S=w>Fo,k=g*M;if(ka.add(Math.atan2(k*_*Math.sin(w),v*x+k*Math.cos(w))),u+=S?b+_*Ho:b,S^h>=e^y>=e){var N=mt(dt(s),dt(n));bt(N);var E=mt(i,N);bt(E);var A=(S^b>=0?-1:1)*tn(E[2]);(r>A||r===A&&(N[0]||N[1]))&&(o+=S^b>=0?1:-1)}if(!d++)break;h=y,g=M,v=x,s=n}}return(-Uo>u||Uo>u&&-Uo>ka)^1&o}function It(n){function t(n,t){return Math.cos(n)*Math.cos(t)>u}function e(n){var e,u,l,c,f;return{lineStart:function(){c=l=!1,f=1},point:function(s,h){var p,g=[s,h],v=t(s,h),d=o?v?0:i(s,h):v?i(s+(0>s?Fo:-Fo),h):0;if(!e&&(c=l=v)&&n.lineStart(),v!==l&&(p=r(e,g),(wt(e,p)||wt(g,p))&&(g[0]+=Uo,g[1]+=Uo,v=t(g[0],g[1]))),v!==l)f=0,v?(n.lineStart(),p=r(g,e),n.point(p[0],p[1])):(p=r(e,g),n.point(p[0],p[1]),n.lineEnd()),e=p;else if(a&&e&&o^v){var y;d&u||!(y=r(g,e,!0))||(f=0,o?(n.lineStart(),n.point(y[0][0],y[0][1]),n.point(y[1][0],y[1][1]),n.lineEnd()):(n.point(y[1][0],y[1][1]),n.lineEnd(),n.lineStart(),n.point(y[0][0],y[0][1])))}!v||e&&wt(e,g)||n.point(g[0],g[1]),e=g,l=v,u=d},lineEnd:function(){l&&n.lineEnd(),e=null},clean:function(){return f|(c&&l)<<1}}}function r(n,t,e){var r=dt(n),i=dt(t),o=[1,0,0],a=mt(r,i),l=yt(a,a),c=a[0],f=l-c*c;if(!f)return!e&&n;var s=u*l/f,h=-u*c/f,p=mt(o,a),g=xt(o,s),v=xt(a,h);Mt(g,v);var d=p,y=yt(g,d),m=yt(d,d),M=y*y-m*(yt(g,g)-1);if(!(0>M)){var x=Math.sqrt(M),b=xt(d,(-y-x)/m);if(Mt(b,g),b=_t(b),!e)return b;var _,w=n[0],S=t[0],k=n[1],N=t[1];w>S&&(_=w,w=S,S=_);var E=S-w,A=xo(E-Fo)E;if(!A&&k>N&&(_=k,k=N,N=_),C?A?k+N>0^b[1]<(xo(b[0]-w)Fo^(w<=b[0]&&b[0]<=S)){var z=xt(d,(-y+x)/m);return Mt(z,g),[b,_t(z)]}}}function i(t,e){var r=o?n:Fo-n,i=0;return-r>t?i|=1:t>r&&(i|=2),-r>e?i|=4:e>r&&(i|=8),i}var u=Math.cos(n),o=u>0,a=xo(u)>Uo,l=ve(n,6*Yo);return Rt(t,e,l,o?[0,-n]:[-Fo,n-Fo])}function Yt(n,t,e,r){return function(i){var u,o=i.a,a=i.b,l=o.x,c=o.y,f=a.x,s=a.y,h=0,p=1,g=f-l,v=s-c;if(u=n-l,g||!(u>0)){if(u/=g,0>g){if(h>u)return;p>u&&(p=u)}else if(g>0){if(u>p)return;u>h&&(h=u)}if(u=e-l,g||!(0>u)){if(u/=g,0>g){if(u>p)return;u>h&&(h=u)}else if(g>0){if(h>u)return;p>u&&(p=u)}if(u=t-c,v||!(u>0)){if(u/=v,0>v){if(h>u)return;p>u&&(p=u)}else if(v>0){if(u>p)return;u>h&&(h=u)}if(u=r-c,v||!(0>u)){if(u/=v,0>v){if(u>p)return;u>h&&(h=u)}else if(v>0){if(h>u)return;p>u&&(p=u)}return h>0&&(i.a={x:l+h*g,y:c+h*v}),1>p&&(i.b={x:l+p*g,y:c+p*v}),i}}}}}}function Zt(n,t,e,r){function i(r,i){return xo(r[0]-n)0?0:3:xo(r[0]-e)0?2:1:xo(r[1]-t)0?1:0:i>0?3:2}function u(n,t){return o(n.x,t.x)}function o(n,t){var e=i(n,1),r=i(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function l(n){for(var t=0,e=d.length,r=n[1],i=0;e>i;++i)for(var u,o=1,a=d[i],l=a.length,c=a[0];l>o;++o)u=a[o],c[1]<=r?u[1]>r&&Q(c,u,n)>0&&++t:u[1]<=r&&Q(c,u,n)<0&&--t,c=u;return 0!==t}function c(u,a,l,c){var f=0,s=0;if(null==u||(f=i(u,l))!==(s=i(a,l))||o(u,a)<0^l>0){do c.point(0===f||3===f?n:e,f>1?r:t);while((f=(f+l+4)%4)!==s)}else c.point(a[0],a[1])}function f(i,u){return i>=n&&e>=i&&u>=t&&r>=u}function s(n,t){f(n,t)&&a.point(n,t)}function h(){C.point=g,d&&d.push(y=[]),S=!0,w=!1,b=_=NaN}function p(){v&&(g(m,M),x&&w&&E.rejoin(),v.push(E.buffer())),C.point=s,w&&a.lineEnd()}function g(n,t){n=Math.max(-Ha,Math.min(Ha,n)),t=Math.max(-Ha,Math.min(Ha,t));var e=f(n,t);if(d&&y.push([n,t]),S)m=n,M=t,x=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:b,y:_},b:{x:n,y:t}};A(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}b=n,_=t,w=e}var v,d,y,m,M,x,b,_,w,S,k,N=a,E=Pt(),A=Yt(n,t,e,r),C={point:s,lineStart:h,lineEnd:p,polygonStart:function(){a=E,v=[],d=[],k=!0},polygonEnd:function(){a=N,v=ao.merge(v);var t=l([n,r]),e=k&&t,i=v.length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),c(null,null,1,a),a.lineEnd()),i&&Lt(v,u,t,c,a),a.polygonEnd()),v=d=y=null}};return C}}function Vt(n){var t=0,e=Fo/3,r=ae(n),i=r(t,e);return i.parallels=function(n){return arguments.length?r(t=n[0]*Fo/180,e=n[1]*Fo/180):[t/Fo*180,e/Fo*180]},i}function Xt(n,t){function e(n,t){var e=Math.sqrt(u-2*i*Math.sin(t))/i;return[e*Math.sin(n*=i),o-e*Math.cos(n)]}var r=Math.sin(n),i=(r+Math.sin(t))/2,u=1+r*(2*i-r),o=Math.sqrt(u)/i;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/i,tn((u-(n*n+e*e)*i*i)/(2*i))]},e}function $t(){function n(n,t){Ia+=i*n-r*t,r=n,i=t}var t,e,r,i;$a.point=function(u,o){$a.point=n,t=r=u,e=i=o},$a.lineEnd=function(){n(t,e)}}function Bt(n,t){Ya>n&&(Ya=n),n>Va&&(Va=n),Za>t&&(Za=t),t>Xa&&(Xa=t)}function Wt(){function n(n,t){o.push("M",n,",",t,u)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function i(){o.push("Z")}var u=Jt(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return u=Jt(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Jt(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Gt(n,t){Ca+=n,za+=t,++La}function Kt(){function n(n,r){var i=n-t,u=r-e,o=Math.sqrt(i*i+u*u);qa+=o*(t+n)/2,Ta+=o*(e+r)/2,Ra+=o,Gt(t=n,e=r)}var t,e;Wa.point=function(r,i){Wa.point=n,Gt(t=r,e=i)}}function Qt(){Wa.point=Gt}function ne(){function n(n,t){var e=n-r,u=t-i,o=Math.sqrt(e*e+u*u);qa+=o*(r+n)/2,Ta+=o*(i+t)/2,Ra+=o,o=i*n-r*t,Da+=o*(r+n),Pa+=o*(i+t),Ua+=3*o,Gt(r=n,i=t)}var t,e,r,i;Wa.point=function(u,o){Wa.point=n,Gt(t=r=u,e=i=o)},Wa.lineEnd=function(){n(t,e)}}function te(n){function t(t,e){n.moveTo(t+o,e),n.arc(t,e,o,0,Ho)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function i(){a.point=t}function u(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:i,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=i,a.point=t},pointRadius:function(n){return o=n,a},result:b};return a}function ee(n){function t(n){return(a?r:e)(n)}function e(t){return ue(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){M=NaN,S.point=u,t.lineStart()}function u(e,r){var u=dt([e,r]),o=n(e,r);i(M,x,m,b,_,w,M=o[0],x=o[1],m=e,b=u[0],_=u[1],w=u[2],a,t),t.point(M,x)}function o(){S.point=e,t.lineEnd()}function l(){ -r(),S.point=c,S.lineEnd=f}function c(n,t){u(s=n,h=t),p=M,g=x,v=b,d=_,y=w,S.point=u}function f(){i(M,x,m,b,_,w,p,g,s,v,d,y,a,t),S.lineEnd=o,o()}var s,h,p,g,v,d,y,m,M,x,b,_,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=l},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function i(t,e,r,a,l,c,f,s,h,p,g,v,d,y){var m=f-t,M=s-e,x=m*m+M*M;if(x>4*u&&d--){var b=a+p,_=l+g,w=c+v,S=Math.sqrt(b*b+_*_+w*w),k=Math.asin(w/=S),N=xo(xo(w)-1)u||xo((m*z+M*L)/x-.5)>.3||o>a*p+l*g+c*v)&&(i(t,e,r,a,l,c,A,C,N,b/=S,_/=S,w,d,y),y.point(A,C),i(A,C,N,b,_,w,f,s,h,p,g,v,d,y))}}var u=.5,o=Math.cos(30*Yo),a=16;return t.precision=function(n){return arguments.length?(a=(u=n*n)>0&&16,t):Math.sqrt(u)},t}function re(n){var t=ee(function(t,e){return n([t*Zo,e*Zo])});return function(n){return le(t(n))}}function ie(n){this.stream=n}function ue(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function oe(n){return ae(function(){return n})()}function ae(n){function t(n){return n=a(n[0]*Yo,n[1]*Yo),[n[0]*h+l,c-n[1]*h]}function e(n){return n=a.invert((n[0]-l)/h,(c-n[1])/h),n&&[n[0]*Zo,n[1]*Zo]}function r(){a=Ct(o=se(y,M,x),u);var n=u(v,d);return l=p-n[0]*h,c=g+n[1]*h,i()}function i(){return f&&(f.valid=!1,f=null),t}var u,o,a,l,c,f,s=ee(function(n,t){return n=u(n,t),[n[0]*h+l,c-n[1]*h]}),h=150,p=480,g=250,v=0,d=0,y=0,M=0,x=0,b=Fa,_=m,w=null,S=null;return t.stream=function(n){return f&&(f.valid=!1),f=le(b(o,s(_(n)))),f.valid=!0,f},t.clipAngle=function(n){return arguments.length?(b=null==n?(w=n,Fa):It((w=+n)*Yo),i()):w},t.clipExtent=function(n){return arguments.length?(S=n,_=n?Zt(n[0][0],n[0][1],n[1][0],n[1][1]):m,i()):S},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(p=+n[0],g=+n[1],r()):[p,g]},t.center=function(n){return arguments.length?(v=n[0]%360*Yo,d=n[1]%360*Yo,r()):[v*Zo,d*Zo]},t.rotate=function(n){return arguments.length?(y=n[0]%360*Yo,M=n[1]%360*Yo,x=n.length>2?n[2]%360*Yo:0,r()):[y*Zo,M*Zo,x*Zo]},ao.rebind(t,s,"precision"),function(){return u=n.apply(this,arguments),t.invert=u.invert&&e,r()}}function le(n){return ue(n,function(t,e){n.point(t*Yo,e*Yo)})}function ce(n,t){return[n,t]}function fe(n,t){return[n>Fo?n-Ho:-Fo>n?n+Ho:n,t]}function se(n,t,e){return n?t||e?Ct(pe(n),ge(t,e)):pe(n):t||e?ge(t,e):fe}function he(n){return function(t,e){return t+=n,[t>Fo?t-Ho:-Fo>t?t+Ho:t,e]}}function pe(n){var t=he(n);return t.invert=he(-n),t}function ge(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*r+a*i;return[Math.atan2(l*u-f*o,a*r-c*i),tn(f*u+l*o)]}var r=Math.cos(n),i=Math.sin(n),u=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*u-l*o;return[Math.atan2(l*u+c*o,a*r+f*i),tn(f*r-a*i)]},e}function ve(n,t){var e=Math.cos(n),r=Math.sin(n);return function(i,u,o,a){var l=o*t;null!=i?(i=de(e,i),u=de(e,u),(o>0?u>i:i>u)&&(i+=o*Ho)):(i=n+o*Ho,u=n-.5*l);for(var c,f=i;o>0?f>u:u>f;f-=l)a.point((c=_t([e,-r*Math.cos(f),-r*Math.sin(f)]))[0],c[1])}}function de(n,t){var e=dt(t);e[0]-=n,bt(e);var r=nn(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Uo)%(2*Math.PI)}function ye(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function me(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function Me(n){return n.source}function xe(n){return n.target}function be(n,t,e,r){var i=Math.cos(t),u=Math.sin(t),o=Math.cos(r),a=Math.sin(r),l=i*Math.cos(n),c=i*Math.sin(n),f=o*Math.cos(e),s=o*Math.sin(e),h=2*Math.asin(Math.sqrt(on(r-t)+i*o*on(e-n))),p=1/Math.sin(h),g=h?function(n){var t=Math.sin(n*=h)*p,e=Math.sin(h-n)*p,r=e*l+t*f,i=e*c+t*s,o=e*u+t*a;return[Math.atan2(i,r)*Zo,Math.atan2(o,Math.sqrt(r*r+i*i))*Zo]}:function(){return[n*Zo,t*Zo]};return g.distance=h,g}function _e(){function n(n,i){var u=Math.sin(i*=Yo),o=Math.cos(i),a=xo((n*=Yo)-t),l=Math.cos(a);Ja+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*u-e*o*l)*a),e*u+r*o*l),t=n,e=u,r=o}var t,e,r;Ga.point=function(i,u){t=i*Yo,e=Math.sin(u*=Yo),r=Math.cos(u),Ga.point=n},Ga.lineEnd=function(){Ga.point=Ga.lineEnd=b}}function we(n,t){function e(t,e){var r=Math.cos(t),i=Math.cos(e),u=n(r*i);return[u*i*Math.sin(t),u*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),i=t(r),u=Math.sin(i),o=Math.cos(i);return[Math.atan2(n*u,r*o),Math.asin(r&&e*u/r)]},e}function Se(n,t){function e(n,t){o>0?-Io+Uo>t&&(t=-Io+Uo):t>Io-Uo&&(t=Io-Uo);var e=o/Math.pow(i(t),u);return[e*Math.sin(u*n),o-e*Math.cos(u*n)]}var r=Math.cos(n),i=function(n){return Math.tan(Fo/4+n/2)},u=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(i(t)/i(n)),o=r*Math.pow(i(n),u)/u;return u?(e.invert=function(n,t){var e=o-t,r=K(u)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/u,2*Math.atan(Math.pow(o/r,1/u))-Io]},e):Ne}function ke(n,t){function e(n,t){var e=u-t;return[e*Math.sin(i*n),u-e*Math.cos(i*n)]}var r=Math.cos(n),i=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),u=r/i+n;return xo(i)i;i++){for(;r>1&&Q(n[e[r-2]],n[e[r-1]],n[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function qe(n,t){return n[0]-t[0]||n[1]-t[1]}function Te(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Re(n,t,e,r){var i=n[0],u=e[0],o=t[0]-i,a=r[0]-u,l=n[1],c=e[1],f=t[1]-l,s=r[1]-c,h=(a*(l-c)-s*(i-u))/(s*o-a*f);return[i+h*o,l+h*f]}function De(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Pe(){rr(this),this.edge=this.site=this.circle=null}function Ue(n){var t=cl.pop()||new Pe;return t.site=n,t}function je(n){Be(n),ol.remove(n),cl.push(n),rr(n)}function Fe(n){var t=n.circle,e=t.x,r=t.cy,i={x:e,y:r},u=n.P,o=n.N,a=[n];je(n);for(var l=u;l.circle&&xo(e-l.circle.x)f;++f)c=a[f],l=a[f-1],nr(c.edge,l.site,c.site,i);l=a[0],c=a[s-1],c.edge=Ke(l.site,c.site,null,i),$e(l),$e(c)}function He(n){for(var t,e,r,i,u=n.x,o=n.y,a=ol._;a;)if(r=Oe(a,o)-u,r>Uo)a=a.L;else{if(i=u-Ie(a,o),!(i>Uo)){r>-Uo?(t=a.P,e=a):i>-Uo?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var l=Ue(n);if(ol.insert(t,l),t||e){if(t===e)return Be(t),e=Ue(t.site),ol.insert(l,e),l.edge=e.edge=Ke(t.site,l.site),$e(t),void $e(e);if(!e)return void(l.edge=Ke(t.site,l.site));Be(t),Be(e);var c=t.site,f=c.x,s=c.y,h=n.x-f,p=n.y-s,g=e.site,v=g.x-f,d=g.y-s,y=2*(h*d-p*v),m=h*h+p*p,M=v*v+d*d,x={x:(d*m-p*M)/y+f,y:(h*M-v*m)/y+s};nr(e.edge,c,g,x),l.edge=Ke(c,n,null,x),e.edge=Ke(n,g,null,x),$e(t),$e(e)}}function Oe(n,t){var e=n.site,r=e.x,i=e.y,u=i-t;if(!u)return r;var o=n.P;if(!o)return-(1/0);e=o.site;var a=e.x,l=e.y,c=l-t;if(!c)return a;var f=a-r,s=1/u-1/c,h=f/c;return s?(-h+Math.sqrt(h*h-2*s*(f*f/(-2*c)-l+c/2+i-u/2)))/s+r:(r+a)/2}function Ie(n,t){var e=n.N;if(e)return Oe(e,t);var r=n.site;return r.y===t?r.x:1/0}function Ye(n){this.site=n,this.edges=[]}function Ze(n){for(var t,e,r,i,u,o,a,l,c,f,s=n[0][0],h=n[1][0],p=n[0][1],g=n[1][1],v=ul,d=v.length;d--;)if(u=v[d],u&&u.prepare())for(a=u.edges,l=a.length,o=0;l>o;)f=a[o].end(),r=f.x,i=f.y,c=a[++o%l].start(),t=c.x,e=c.y,(xo(r-t)>Uo||xo(i-e)>Uo)&&(a.splice(o,0,new tr(Qe(u.site,f,xo(r-s)Uo?{x:s,y:xo(t-s)Uo?{x:xo(e-g)Uo?{x:h,y:xo(t-h)Uo?{x:xo(e-p)=-jo)){var p=l*l+c*c,g=f*f+s*s,v=(s*p-c*g)/h,d=(l*g-f*p)/h,s=d+a,y=fl.pop()||new Xe;y.arc=n,y.site=i,y.x=v+o,y.y=s+Math.sqrt(v*v+d*d),y.cy=s,n.circle=y;for(var m=null,M=ll._;M;)if(y.yd||d>=a)return;if(h>g){if(u){if(u.y>=c)return}else u={x:d,y:l};e={x:d,y:c}}else{if(u){if(u.yr||r>1)if(h>g){if(u){if(u.y>=c)return}else u={x:(l-i)/r,y:l};e={x:(c-i)/r,y:c}}else{if(u){if(u.yp){if(u){if(u.x>=a)return}else u={x:o,y:r*o+i};e={x:a,y:r*a+i}}else{if(u){if(u.xu||s>o||r>h||i>p)){if(g=n.point){var g,v=t-n.x,d=e-n.y,y=v*v+d*d;if(l>y){var m=Math.sqrt(l=y);r=t-m,i=e-m,u=t+m,o=e+m,a=g}}for(var M=n.nodes,x=.5*(f+h),b=.5*(s+p),_=t>=x,w=e>=b,S=w<<1|_,k=S+4;k>S;++S)if(n=M[3&S])switch(3&S){case 0:c(n,f,s,x,b);break;case 1:c(n,x,s,h,b);break;case 2:c(n,f,b,x,p);break;case 3:c(n,x,b,h,p)}}}(n,r,i,u,o),a}function vr(n,t){n=ao.rgb(n),t=ao.rgb(t);var e=n.r,r=n.g,i=n.b,u=t.r-e,o=t.g-r,a=t.b-i;return function(n){return"#"+bn(Math.round(e+u*n))+bn(Math.round(r+o*n))+bn(Math.round(i+a*n))}}function dr(n,t){var e,r={},i={};for(e in n)e in t?r[e]=Mr(n[e],t[e]):i[e]=n[e];for(e in t)e in n||(i[e]=t[e]);return function(n){for(e in r)i[e]=r[e](n);return i}}function yr(n,t){return n=+n,t=+t,function(e){return n*(1-e)+t*e}}function mr(n,t){var e,r,i,u=hl.lastIndex=pl.lastIndex=0,o=-1,a=[],l=[];for(n+="",t+="";(e=hl.exec(n))&&(r=pl.exec(t));)(i=r.index)>u&&(i=t.slice(u,i),a[o]?a[o]+=i:a[++o]=i),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,l.push({i:o,x:yr(e,r)})),u=pl.lastIndex;return ur;++r)a[(e=l[r]).i]=e.x(n);return a.join("")})}function Mr(n,t){for(var e,r=ao.interpolators.length;--r>=0&&!(e=ao.interpolators[r](n,t)););return e}function xr(n,t){var e,r=[],i=[],u=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(Mr(n[e],t[e]));for(;u>e;++e)i[e]=n[e];for(;o>e;++e)i[e]=t[e];return function(n){for(e=0;a>e;++e)i[e]=r[e](n);return i}}function br(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function _r(n){return function(t){return 1-n(1-t)}}function wr(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function Sr(n){return n*n}function kr(n){return n*n*n}function Nr(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function Er(n){return function(t){return Math.pow(t,n)}}function Ar(n){return 1-Math.cos(n*Io)}function Cr(n){return Math.pow(2,10*(n-1))}function zr(n){return 1-Math.sqrt(1-n*n)}function Lr(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/Ho*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*Ho/t)}}function qr(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Tr(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Rr(n,t){n=ao.hcl(n),t=ao.hcl(t);var e=n.h,r=n.c,i=n.l,u=t.h-e,o=t.c-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return sn(e+u*n,r+o*n,i+a*n)+""}}function Dr(n,t){n=ao.hsl(n),t=ao.hsl(t);var e=n.h,r=n.s,i=n.l,u=t.h-e,o=t.s-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return cn(e+u*n,r+o*n,i+a*n)+""}}function Pr(n,t){n=ao.lab(n),t=ao.lab(t);var e=n.l,r=n.a,i=n.b,u=t.l-e,o=t.a-r,a=t.b-i;return function(n){return pn(e+u*n,r+o*n,i+a*n)+""}}function Ur(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function jr(n){var t=[n.a,n.b],e=[n.c,n.d],r=Hr(t),i=Fr(t,e),u=Hr(Or(e,t,-i))||0;t[0]*e[1]180?t+=360:t-n>180&&(n+=360),r.push({i:e.push(Ir(e)+"rotate(",null,")")-2,x:yr(n,t)})):t&&e.push(Ir(e)+"rotate("+t+")")}function Vr(n,t,e,r){n!==t?r.push({i:e.push(Ir(e)+"skewX(",null,")")-2,x:yr(n,t)}):t&&e.push(Ir(e)+"skewX("+t+")")}function Xr(n,t,e,r){if(n[0]!==t[0]||n[1]!==t[1]){var i=e.push(Ir(e)+"scale(",null,",",null,")");r.push({i:i-4,x:yr(n[0],t[0])},{i:i-2,x:yr(n[1],t[1])})}else 1===t[0]&&1===t[1]||e.push(Ir(e)+"scale("+t+")")}function $r(n,t){var e=[],r=[];return n=ao.transform(n),t=ao.transform(t),Yr(n.translate,t.translate,e,r),Zr(n.rotate,t.rotate,e,r),Vr(n.skew,t.skew,e,r),Xr(n.scale,t.scale,e,r),n=t=null,function(n){for(var t,i=-1,u=r.length;++i=0;)e.push(i[r])}function oi(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(u=n.children)&&(i=u.length))for(var i,u,o=-1;++oe;++e)(t=n[e][1])>i&&(r=e,i=t);return r}function yi(n){return n.reduce(mi,0)}function mi(n,t){return n+t[1]}function Mi(n,t){return xi(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function xi(n,t){for(var e=-1,r=+n[0],i=(n[1]-r)/t,u=[];++e<=t;)u[e]=i*e+r;return u}function bi(n){return[ao.min(n),ao.max(n)]}function _i(n,t){return n.value-t.value}function wi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function Si(n,t){n._pack_next=t,t._pack_prev=n}function ki(n,t){var e=t.x-n.x,r=t.y-n.y,i=n.r+t.r;return.999*i*i>e*e+r*r}function Ni(n){function t(n){f=Math.min(n.x-n.r,f),s=Math.max(n.x+n.r,s),h=Math.min(n.y-n.r,h),p=Math.max(n.y+n.r,p)}if((e=n.children)&&(c=e.length)){var e,r,i,u,o,a,l,c,f=1/0,s=-(1/0),h=1/0,p=-(1/0);if(e.forEach(Ei),r=e[0],r.x=-r.r,r.y=0,t(r),c>1&&(i=e[1],i.x=i.r,i.y=0,t(i),c>2))for(u=e[2],zi(r,i,u),t(u),wi(r,u),r._pack_prev=u,wi(u,i),i=r._pack_next,o=3;c>o;o++){zi(r,i,u=e[o]);var g=0,v=1,d=1;for(a=i._pack_next;a!==i;a=a._pack_next,v++)if(ki(a,u)){g=1;break}if(1==g)for(l=r._pack_prev;l!==a._pack_prev&&!ki(l,u);l=l._pack_prev,d++);g?(d>v||v==d&&i.ro;o++)u=e[o],u.x-=y,u.y-=m,M=Math.max(M,u.r+Math.sqrt(u.x*u.x+u.y*u.y));n.r=M,e.forEach(Ai)}}function Ei(n){n._pack_next=n._pack_prev=n}function Ai(n){delete n._pack_next,delete n._pack_prev}function Ci(n,t,e,r){var i=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,i)for(var u=-1,o=i.length;++u=0;)t=i[u],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function Pi(n,t,e){return n.a.parent===t.parent?n.a:e}function Ui(n){return 1+ao.max(n,function(n){return n.y})}function ji(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Fi(n){var t=n.children;return t&&t.length?Fi(t[0]):n}function Hi(n){var t,e=n.children;return e&&(t=e.length)?Hi(e[t-1]):n}function Oi(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function Ii(n,t){var e=n.x+t[3],r=n.y+t[0],i=n.dx-t[1]-t[3],u=n.dy-t[0]-t[2];return 0>i&&(e+=i/2,i=0),0>u&&(r+=u/2,u=0),{x:e,y:r,dx:i,dy:u}}function Yi(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Zi(n){return n.rangeExtent?n.rangeExtent():Yi(n.range())}function Vi(n,t,e,r){var i=e(n[0],n[1]),u=r(t[0],t[1]);return function(n){return u(i(n))}}function Xi(n,t){var e,r=0,i=n.length-1,u=n[r],o=n[i];return u>o&&(e=r,r=i,i=e,e=u,u=o,o=e),n[r]=t.floor(u),n[i]=t.ceil(o),n}function $i(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:Sl}function Bi(n,t,e,r){var i=[],u=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]2?Bi:Vi,l=r?Wr:Br;return o=i(n,t,l,e),a=i(t,n,l,Mr),u}function u(n){return o(n)}var o,a;return u.invert=function(n){return a(n)},u.domain=function(t){return arguments.length?(n=t.map(Number),i()):n},u.range=function(n){return arguments.length?(t=n,i()):t},u.rangeRound=function(n){return u.range(n).interpolate(Ur)},u.clamp=function(n){return arguments.length?(r=n,i()):r},u.interpolate=function(n){return arguments.length?(e=n,i()):e},u.ticks=function(t){return Qi(n,t)},u.tickFormat=function(t,e){return nu(n,t,e)},u.nice=function(t){return Gi(n,t),i()},u.copy=function(){return Wi(n,t,e,r)},i()}function Ji(n,t){return ao.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Gi(n,t){return Xi(n,$i(Ki(n,t)[2])),Xi(n,$i(Ki(n,t)[2])),n}function Ki(n,t){null==t&&(t=10);var e=Yi(n),r=e[1]-e[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),u=t/r*i;return.15>=u?i*=10:.35>=u?i*=5:.75>=u&&(i*=2),e[0]=Math.ceil(e[0]/i)*i,e[1]=Math.floor(e[1]/i)*i+.5*i,e[2]=i,e}function Qi(n,t){return ao.range.apply(ao,Ki(n,t))}function nu(n,t,e){var r=Ki(n,t);if(e){var i=ha.exec(e);if(i.shift(),"s"===i[8]){var u=ao.formatPrefix(Math.max(xo(r[0]),xo(r[1])));return i[7]||(i[7]="."+tu(u.scale(r[2]))),i[8]="f",e=ao.format(i.join("")),function(n){return e(u.scale(n))+u.symbol}}i[7]||(i[7]="."+eu(i[8],r)),e=i.join("")}else e=",."+tu(r[2])+"f";return ao.format(e)}function tu(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function eu(n,t){var e=tu(t[2]);return n in kl?Math.abs(e-tu(Math.max(xo(t[0]),xo(t[1]))))+ +("e"!==n):e-2*("%"===n)}function ru(n,t,e,r){function i(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function u(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(i(t))}return o.invert=function(t){return u(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(i)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(i)),o):t},o.nice=function(){var t=Xi(r.map(i),e?Math:El);return n.domain(t),r=t.map(u),o},o.ticks=function(){var n=Yi(r),o=[],a=n[0],l=n[1],c=Math.floor(i(a)),f=Math.ceil(i(l)),s=t%1?2:t;if(isFinite(f-c)){if(e){for(;f>c;c++)for(var h=1;s>h;h++)o.push(u(c)*h);o.push(u(c))}else for(o.push(u(c));c++0;h--)o.push(u(c)*h);for(c=0;o[c]l;f--);o=o.slice(c,f)}return o},o.tickFormat=function(n,e){if(!arguments.length)return Nl;arguments.length<2?e=Nl:"function"!=typeof e&&(e=ao.format(e));var r=Math.max(1,t*n/o.ticks().length);return function(n){var o=n/u(Math.round(i(n)));return t-.5>o*t&&(o*=t),r>=o?e(n):""}},o.copy=function(){return ru(n.copy(),t,e,r)},Ji(o,n)}function iu(n,t,e){function r(t){return n(i(t))}var i=uu(t),u=uu(1/t);return r.invert=function(t){return u(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(i)),r):e},r.ticks=function(n){return Qi(e,n)},r.tickFormat=function(n,t){return nu(e,n,t)},r.nice=function(n){return r.domain(Gi(e,n))},r.exponent=function(o){return arguments.length?(i=uu(t=o),u=uu(1/t),n.domain(e.map(i)),r):t},r.copy=function(){return iu(n.copy(),t,e)},Ji(r,n)}function uu(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function ou(n,t){function e(e){return u[((i.get(e)||("range"===t.t?i.set(e,n.push(e)):NaN))-1)%u.length]}function r(t,e){return ao.range(n.length).map(function(n){return t+e*n})}var i,u,o;return e.domain=function(r){if(!arguments.length)return n;n=[],i=new c;for(var u,o=-1,a=r.length;++oe?[NaN,NaN]:[e>0?a[e-1]:n[0],et?NaN:t/u+n,[t,t+1/u]},r.copy=function(){return lu(n,t,e)},i()}function cu(n,t){function e(e){return e>=e?t[ao.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return cu(n,t)},e}function fu(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Qi(n,t)},t.tickFormat=function(t,e){return nu(n,t,e)},t.copy=function(){return fu(n)},t}function su(){return 0}function hu(n){return n.innerRadius}function pu(n){return n.outerRadius}function gu(n){return n.startAngle}function vu(n){return n.endAngle}function du(n){return n&&n.padAngle}function yu(n,t,e,r){return(n-e)*t-(t-r)*n>0?0:1}function mu(n,t,e,r,i){var u=n[0]-t[0],o=n[1]-t[1],a=(i?r:-r)/Math.sqrt(u*u+o*o),l=a*o,c=-a*u,f=n[0]+l,s=n[1]+c,h=t[0]+l,p=t[1]+c,g=(f+h)/2,v=(s+p)/2,d=h-f,y=p-s,m=d*d+y*y,M=e-r,x=f*p-h*s,b=(0>y?-1:1)*Math.sqrt(Math.max(0,M*M*m-x*x)),_=(x*y-d*b)/m,w=(-x*d-y*b)/m,S=(x*y+d*b)/m,k=(-x*d+y*b)/m,N=_-g,E=w-v,A=S-g,C=k-v;return N*N+E*E>A*A+C*C&&(_=S,w=k),[[_-l,w-c],[_*e/M,w*e/M]]}function Mu(n){function t(t){function o(){c.push("M",u(n(f),a))}for(var l,c=[],f=[],s=-1,h=t.length,p=En(e),g=En(r);++s1?n.join("L"):n+"Z"}function bu(n){return n.join("L")+"Z"}function _u(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t1&&i.push("H",r[0]),i.join("")}function wu(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t1){a=t[1],u=n[l],l++,r+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(u[0]-a[0])+","+(u[1]-a[1])+","+u[0]+","+u[1];for(var c=2;c9&&(i=3*t/Math.sqrt(i),o[a]=i*e,o[a+1]=i*r));for(a=-1;++a<=l;)i=(n[Math.min(l,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),u.push([i||0,o[a]*i||0]);return u}function Fu(n){return n.length<3?xu(n):n[0]+Au(n,ju(n))}function Hu(n){for(var t,e,r,i=-1,u=n.length;++i=t?o(n-t):void(f.c=o)}function o(e){var i=g.active,u=g[i];u&&(u.timer.c=null,u.timer.t=NaN,--g.count,delete g[i],u.event&&u.event.interrupt.call(n,n.__data__,u.index));for(var o in g)if(r>+o){var c=g[o];c.timer.c=null,c.timer.t=NaN,--g.count,delete g[o]}f.c=a,qn(function(){return f.c&&a(e||1)&&(f.c=null,f.t=NaN),1},0,l),g.active=r,v.event&&v.event.start.call(n,n.__data__,t),p=[],v.tween.forEach(function(e,r){(r=r.call(n,n.__data__,t))&&p.push(r)}),h=v.ease,s=v.duration}function a(i){for(var u=i/s,o=h(u),a=p.length;a>0;)p[--a].call(n,o);return u>=1?(v.event&&v.event.end.call(n,n.__data__,t),--g.count?delete g[r]:delete n[e],1):void 0}var l,f,s,h,p,g=n[e]||(n[e]={active:0,count:0}),v=g[r];v||(l=i.time,f=qn(u,0,l),v=g[r]={tween:new c,time:l,timer:f,delay:i.delay,duration:i.duration,ease:i.ease,index:t},i=null,++g.count)}function no(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate("+(isFinite(r)?r:e(n))+",0)"})}function to(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate(0,"+(isFinite(r)?r:e(n))+")"})}function eo(n){return n.toISOString()}function ro(n,t,e){function r(t){return n(t)}function i(n,e){var r=n[1]-n[0],i=r/e,u=ao.bisect(Kl,i);return u==Kl.length?[t.year,Ki(n.map(function(n){return n/31536e6}),e)[2]]:u?t[i/Kl[u-1]1?{floor:function(t){for(;e(t=n.floor(t));)t=io(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=io(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Yi(r.domain()),u=null==n?i(e,10):"number"==typeof n?i(e,n):!n.range&&[{range:n},t];return u&&(n=u[0],t=u[1]),n.range(e[0],io(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return ro(n.copy(),t,e)},Ji(r,n)}function io(n){return new Date(n)}function uo(n){return JSON.parse(n.responseText)}function oo(n){var t=fo.createRange();return t.selectNode(fo.body),t.createContextualFragment(n.responseText)}var ao={version:"3.5.17"},lo=[].slice,co=function(n){return lo.call(n)},fo=this.document;if(fo)try{co(fo.documentElement.childNodes)[0].nodeType}catch(so){co=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}if(Date.now||(Date.now=function(){return+new Date}),fo)try{fo.createElement("DIV").style.setProperty("opacity",0,"")}catch(ho){var po=this.Element.prototype,go=po.setAttribute,vo=po.setAttributeNS,yo=this.CSSStyleDeclaration.prototype,mo=yo.setProperty;po.setAttribute=function(n,t){go.call(this,n,t+"")},po.setAttributeNS=function(n,t,e){vo.call(this,n,t,e+"")},yo.setProperty=function(n,t,e){mo.call(this,n,t+"",e)}}ao.ascending=e,ao.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:NaN},ao.min=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i=r){e=r;break}for(;++ir&&(e=r)}else{for(;++i=r){e=r;break}for(;++ir&&(e=r)}return e},ao.max=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i=r){e=r;break}for(;++ie&&(e=r)}else{for(;++i=r){e=r;break}for(;++ie&&(e=r)}return e},ao.extent=function(n,t){var e,r,i,u=-1,o=n.length;if(1===arguments.length){for(;++u=r){e=i=r;break}for(;++ur&&(e=r),r>i&&(i=r))}else{for(;++u=r){e=i=r;break}for(;++ur&&(e=r),r>i&&(i=r))}return[e,i]},ao.sum=function(n,t){var e,r=0,u=n.length,o=-1;if(1===arguments.length)for(;++o1?l/(f-1):void 0},ao.deviation=function(){var n=ao.variance.apply(this,arguments);return n?Math.sqrt(n):n};var Mo=u(e);ao.bisectLeft=Mo.left,ao.bisect=ao.bisectRight=Mo.right,ao.bisector=function(n){return u(1===n.length?function(t,r){return e(n(t),r)}:n)},ao.shuffle=function(n,t,e){(u=arguments.length)<3&&(e=n.length,2>u&&(t=0));for(var r,i,u=e-t;u;)i=Math.random()*u--|0,r=n[u+t],n[u+t]=n[i+t],n[i+t]=r;return n},ao.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},ao.pairs=function(n){for(var t,e=0,r=n.length-1,i=n[0],u=new Array(0>r?0:r);r>e;)u[e]=[t=i,i=n[++e]];return u},ao.transpose=function(n){if(!(i=n.length))return[];for(var t=-1,e=ao.min(n,o),r=new Array(e);++t=0;)for(r=n[i],t=r.length;--t>=0;)e[--o]=r[t];return e};var xo=Math.abs;ao.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),(t-n)/e===1/0)throw new Error("infinite range");var r,i=[],u=a(xo(e)),o=-1;if(n*=u,t*=u,e*=u,0>e)for(;(r=n+e*++o)>t;)i.push(r/u);else for(;(r=n+e*++o)=u.length)return r?r.call(i,o):e?o.sort(e):o;for(var l,f,s,h,p=-1,g=o.length,v=u[a++],d=new c;++p=u.length)return n;var r=[],i=o[e++];return n.forEach(function(n,i){r.push({key:n,values:t(i,e)})}),i?r.sort(function(n,t){return i(n.key,t.key)}):r}var e,r,i={},u=[],o=[];return i.map=function(t,e){return n(e,t,0)},i.entries=function(e){return t(n(ao.map,e,0),0)},i.key=function(n){return u.push(n),i},i.sortKeys=function(n){return o[u.length-1]=n,i},i.sortValues=function(n){return e=n,i},i.rollup=function(n){return r=n,i},i},ao.set=function(n){var t=new y;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},l(y,{has:h,add:function(n){return this._[f(n+="")]=!0,n},remove:p,values:g,size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,s(t))}}),ao.behavior={},ao.rebind=function(n,t){for(var e,r=1,i=arguments.length;++r=0&&(r=n.slice(e+1),n=n.slice(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},ao.event=null,ao.requote=function(n){return n.replace(So,"\\$&")};var So=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ko={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},No=function(n,t){return t.querySelector(n)},Eo=function(n,t){return t.querySelectorAll(n)},Ao=function(n,t){var e=n.matches||n[x(n,"matchesSelector")];return(Ao=function(n,t){return e.call(n,t)})(n,t)};"function"==typeof Sizzle&&(No=function(n,t){return Sizzle(n,t)[0]||null},Eo=Sizzle,Ao=Sizzle.matchesSelector),ao.selection=function(){return ao.select(fo.documentElement)};var Co=ao.selection.prototype=[];Co.select=function(n){var t,e,r,i,u=[];n=A(n);for(var o=-1,a=this.length;++o=0&&"xmlns"!==(e=n.slice(0,t))&&(n=n.slice(t+1)),Lo.hasOwnProperty(e)?{space:Lo[e],local:n}:n}},Co.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=ao.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(z(t,n[t]));return this}return this.each(z(n,t))},Co.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=T(n)).length,i=-1;if(t=e.classList){for(;++ii){if("string"!=typeof n){2>i&&(e="");for(r in n)this.each(P(r,n[r],e));return this}if(2>i){var u=this.node();return t(u).getComputedStyle(u,null).getPropertyValue(n)}r=""}return this.each(P(n,e,r))},Co.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(U(t,n[t]));return this}return this.each(U(n,t))},Co.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},Co.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},Co.append=function(n){return n=j(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},Co.insert=function(n,t){return n=j(n),t=A(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},Co.remove=function(){return this.each(F)},Co.data=function(n,t){function e(n,e){var r,i,u,o=n.length,s=e.length,h=Math.min(o,s),p=new Array(s),g=new Array(s),v=new Array(o);if(t){var d,y=new c,m=new Array(o);for(r=-1;++rr;++r)g[r]=H(e[r]);for(;o>r;++r)v[r]=n[r]}g.update=p,g.parentNode=p.parentNode=v.parentNode=n.parentNode,a.push(g),l.push(p),f.push(v)}var r,i,u=-1,o=this.length;if(!arguments.length){for(n=new Array(o=(r=this[0]).length);++uu;u++){i.push(t=[]),t.parentNode=(e=this[u]).parentNode;for(var a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return E(i)},Co.order=function(){for(var n=-1,t=this.length;++n=0;)(e=r[i])&&(u&&u!==e.nextSibling&&u.parentNode.insertBefore(e,u),u=e);return this},Co.sort=function(n){n=I.apply(this,arguments);for(var t=-1,e=this.length;++tn;n++)for(var e=this[n],r=0,i=e.length;i>r;r++){var u=e[r];if(u)return u}return null},Co.size=function(){var n=0;return Y(this,function(){++n}),n};var qo=[];ao.selection.enter=Z,ao.selection.enter.prototype=qo,qo.append=Co.append,qo.empty=Co.empty,qo.node=Co.node,qo.call=Co.call,qo.size=Co.size,qo.select=function(n){for(var t,e,r,i,u,o=[],a=-1,l=this.length;++ar){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(X(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(X(n,t,e))};var To=ao.map({mouseenter:"mouseover",mouseleave:"mouseout"});fo&&To.forEach(function(n){"on"+n in fo&&To.remove(n)});var Ro,Do=0;ao.mouse=function(n){return J(n,k())};var Po=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;ao.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=k().changedTouches),t)for(var r,i=0,u=t.length;u>i;++i)if((r=t[i]).identifier===e)return J(n,r)},ao.behavior.drag=function(){function n(){this.on("mousedown.drag",u).on("touchstart.drag",o)}function e(n,t,e,u,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-M[0],e=r[1]-M[1],g|=n|e,M=r,p({type:"drag",x:r[0]+c[0],y:r[1]+c[1],dx:n,dy:e}))}function l(){t(h,v)&&(y.on(u+d,null).on(o+d,null),m(g),p({type:"dragend"}))}var c,f=this,s=ao.event.target.correspondingElement||ao.event.target,h=f.parentNode,p=r.of(f,arguments),g=0,v=n(),d=".drag"+(null==v?"":"-"+v),y=ao.select(e(s)).on(u+d,a).on(o+d,l),m=W(s),M=t(h,v);i?(c=i.apply(f,arguments),c=[c.x-M[0],c.y-M[1]]):c=[0,0],p({type:"dragstart"})}}var r=N(n,"drag","dragstart","dragend"),i=null,u=e(b,ao.mouse,t,"mousemove","mouseup"),o=e(G,ao.touch,m,"touchmove","touchend");return n.origin=function(t){return arguments.length?(i=t,n):i},ao.rebind(n,r,"on")},ao.touches=function(n,t){return arguments.length<2&&(t=k().touches),t?co(t).map(function(t){var e=J(n,t);return e.identifier=t.identifier,e}):[]};var Uo=1e-6,jo=Uo*Uo,Fo=Math.PI,Ho=2*Fo,Oo=Ho-Uo,Io=Fo/2,Yo=Fo/180,Zo=180/Fo,Vo=Math.SQRT2,Xo=2,$o=4;ao.interpolateZoom=function(n,t){var e,r,i=n[0],u=n[1],o=n[2],a=t[0],l=t[1],c=t[2],f=a-i,s=l-u,h=f*f+s*s;if(jo>h)r=Math.log(c/o)/Vo,e=function(n){return[i+n*f,u+n*s,o*Math.exp(Vo*n*r)]};else{var p=Math.sqrt(h),g=(c*c-o*o+$o*h)/(2*o*Xo*p),v=(c*c-o*o-$o*h)/(2*c*Xo*p),d=Math.log(Math.sqrt(g*g+1)-g),y=Math.log(Math.sqrt(v*v+1)-v);r=(y-d)/Vo,e=function(n){var t=n*r,e=rn(d),a=o/(Xo*p)*(e*un(Vo*t+d)-en(d));return[i+a*f,u+a*s,o*e/rn(Vo*t+d)]}}return e.duration=1e3*r,e},ao.behavior.zoom=function(){function n(n){n.on(L,s).on(Wo+".zoom",p).on("dblclick.zoom",g).on(R,h)}function e(n){return[(n[0]-k.x)/k.k,(n[1]-k.y)/k.k]}function r(n){return[n[0]*k.k+k.x,n[1]*k.k+k.y]}function i(n){k.k=Math.max(A[0],Math.min(A[1],n))}function u(n,t){t=r(t),k.x+=n[0]-t[0],k.y+=n[1]-t[1]}function o(t,e,r,o){t.__chart__={x:k.x,y:k.y,k:k.k},i(Math.pow(2,o)),u(d=e,r),t=ao.select(t),C>0&&(t=t.transition().duration(C)),t.call(n.event)}function a(){b&&b.domain(x.range().map(function(n){return(n-k.x)/k.k}).map(x.invert)),w&&w.domain(_.range().map(function(n){return(n-k.y)/k.k}).map(_.invert))}function l(n){z++||n({type:"zoomstart"})}function c(n){a(),n({type:"zoom",scale:k.k,translate:[k.x,k.y]})}function f(n){--z||(n({type:"zoomend"}),d=null)}function s(){function n(){a=1,u(ao.mouse(i),h),c(o)}function r(){s.on(q,null).on(T,null),p(a),f(o)}var i=this,o=D.of(i,arguments),a=0,s=ao.select(t(i)).on(q,n).on(T,r),h=e(ao.mouse(i)),p=W(i);Il.call(i),l(o)}function h(){function n(){var n=ao.touches(g);return p=k.k,n.forEach(function(n){n.identifier in d&&(d[n.identifier]=e(n))}),n}function t(){var t=ao.event.target;ao.select(t).on(x,r).on(b,a),_.push(t);for(var e=ao.event.changedTouches,i=0,u=e.length;u>i;++i)d[e[i].identifier]=null;var l=n(),c=Date.now();if(1===l.length){if(500>c-M){var f=l[0];o(g,f,d[f.identifier],Math.floor(Math.log(k.k)/Math.LN2)+1),S()}M=c}else if(l.length>1){var f=l[0],s=l[1],h=f[0]-s[0],p=f[1]-s[1];y=h*h+p*p}}function r(){var n,t,e,r,o=ao.touches(g);Il.call(g);for(var a=0,l=o.length;l>a;++a,r=null)if(e=o[a],r=d[e.identifier]){if(t)break;n=e,t=r}if(r){var f=(f=e[0]-n[0])*f+(f=e[1]-n[1])*f,s=y&&Math.sqrt(f/y);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+r[0])/2,(t[1]+r[1])/2],i(s*p)}M=null,u(n,t),c(v)}function a(){if(ao.event.touches.length){for(var t=ao.event.changedTouches,e=0,r=t.length;r>e;++e)delete d[t[e].identifier];for(var i in d)return void n()}ao.selectAll(_).on(m,null),w.on(L,s).on(R,h),N(),f(v)}var p,g=this,v=D.of(g,arguments),d={},y=0,m=".zoom-"+ao.event.changedTouches[0].identifier,x="touchmove"+m,b="touchend"+m,_=[],w=ao.select(g),N=W(g);t(),l(v),w.on(L,null).on(R,t)}function p(){var n=D.of(this,arguments);m?clearTimeout(m):(Il.call(this),v=e(d=y||ao.mouse(this)),l(n)),m=setTimeout(function(){m=null,f(n)},50),S(),i(Math.pow(2,.002*Bo())*k.k),u(d,v),c(n)}function g(){var n=ao.mouse(this),t=Math.log(k.k)/Math.LN2;o(this,n,e(n),ao.event.shiftKey?Math.ceil(t)-1:Math.floor(t)+1)}var v,d,y,m,M,x,b,_,w,k={x:0,y:0,k:1},E=[960,500],A=Jo,C=250,z=0,L="mousedown.zoom",q="mousemove.zoom",T="mouseup.zoom",R="touchstart.zoom",D=N(n,"zoomstart","zoom","zoomend");return Wo||(Wo="onwheel"in fo?(Bo=function(){return-ao.event.deltaY*(ao.event.deltaMode?120:1)},"wheel"):"onmousewheel"in fo?(Bo=function(){return ao.event.wheelDelta},"mousewheel"):(Bo=function(){return-ao.event.detail},"MozMousePixelScroll")),n.event=function(n){n.each(function(){var n=D.of(this,arguments),t=k;Hl?ao.select(this).transition().each("start.zoom",function(){k=this.__chart__||{x:0,y:0,k:1},l(n)}).tween("zoom:zoom",function(){var e=E[0],r=E[1],i=d?d[0]:e/2,u=d?d[1]:r/2,o=ao.interpolateZoom([(i-k.x)/k.k,(u-k.y)/k.k,e/k.k],[(i-t.x)/t.k,(u-t.y)/t.k,e/t.k]);return function(t){var r=o(t),a=e/r[2];this.__chart__=k={x:i-r[0]*a,y:u-r[1]*a,k:a},c(n)}}).each("interrupt.zoom",function(){f(n)}).each("end.zoom",function(){f(n)}):(this.__chart__=k,l(n),c(n),f(n))})},n.translate=function(t){return arguments.length?(k={x:+t[0],y:+t[1],k:k.k},a(),n):[k.x,k.y]},n.scale=function(t){return arguments.length?(k={x:k.x,y:k.y,k:null},i(+t),a(),n):k.k},n.scaleExtent=function(t){return arguments.length?(A=null==t?Jo:[+t[0],+t[1]],n):A},n.center=function(t){return arguments.length?(y=t&&[+t[0],+t[1]],n):y},n.size=function(t){return arguments.length?(E=t&&[+t[0],+t[1]],n):E},n.duration=function(t){return arguments.length?(C=+t,n):C},n.x=function(t){return arguments.length?(b=t,x=t.copy(),k={x:0,y:0,k:1},n):b},n.y=function(t){return arguments.length?(w=t,_=t.copy(),k={x:0,y:0,k:1},n):w},ao.rebind(n,D,"on")};var Bo,Wo,Jo=[0,1/0];ao.color=an,an.prototype.toString=function(){return this.rgb()+""},ao.hsl=ln;var Go=ln.prototype=new an;Go.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,this.l/n)},Go.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,n*this.l)},Go.rgb=function(){return cn(this.h,this.s,this.l)},ao.hcl=fn;var Ko=fn.prototype=new an;Ko.brighter=function(n){return new fn(this.h,this.c,Math.min(100,this.l+Qo*(arguments.length?n:1)))},Ko.darker=function(n){return new fn(this.h,this.c,Math.max(0,this.l-Qo*(arguments.length?n:1)))},Ko.rgb=function(){return sn(this.h,this.c,this.l).rgb()},ao.lab=hn;var Qo=18,na=.95047,ta=1,ea=1.08883,ra=hn.prototype=new an;ra.brighter=function(n){return new hn(Math.min(100,this.l+Qo*(arguments.length?n:1)),this.a,this.b)},ra.darker=function(n){return new hn(Math.max(0,this.l-Qo*(arguments.length?n:1)),this.a,this.b)},ra.rgb=function(){return pn(this.l,this.a,this.b)},ao.rgb=mn;var ia=mn.prototype=new an;ia.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,i=30;return t||e||r?(t&&i>t&&(t=i),e&&i>e&&(e=i),r&&i>r&&(r=i),new mn(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new mn(i,i,i)},ia.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new mn(n*this.r,n*this.g,n*this.b)},ia.hsl=function(){return wn(this.r,this.g,this.b)},ia.toString=function(){return"#"+bn(this.r)+bn(this.g)+bn(this.b)};var ua=ao.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ua.forEach(function(n,t){ua.set(n,Mn(t))}),ao.functor=En,ao.xhr=An(m),ao.dsv=function(n,t){function e(n,e,u){arguments.length<3&&(u=e,e=null);var o=Cn(n,t,null==e?r:i(e),u);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:i(n)):e},o}function r(n){return e.parse(n.responseText)}function i(n){return function(t){return e.parse(t.responseText,n)}}function u(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),l=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var i=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(i(n),e)}:i})},e.parseRows=function(n,t){function e(){if(f>=c)return o;if(i)return i=!1,u;var t=f;if(34===n.charCodeAt(t)){for(var e=t;e++f;){var r=n.charCodeAt(f++),a=1;if(10===r)i=!0;else if(13===r)i=!0,10===n.charCodeAt(f)&&(++f,++a);else if(r!==l)continue;return n.slice(t,f-a)}return n.slice(t)}for(var r,i,u={},o={},a=[],c=n.length,f=0,s=0;(r=e())!==o;){for(var h=[];r!==u&&r!==o;)h.push(r),r=e();t&&null==(h=t(h,s++))||a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new y,i=[];return t.forEach(function(n){for(var t in n)r.has(t)||i.push(r.add(t))}),[i.map(o).join(n)].concat(t.map(function(t){return i.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(u).join("\n")},e},ao.csv=ao.dsv(",","text/csv"),ao.tsv=ao.dsv(" ","text/tab-separated-values");var oa,aa,la,ca,fa=this[x(this,"requestAnimationFrame")]||function(n){setTimeout(n,17)};ao.timer=function(){qn.apply(this,arguments)},ao.timer.flush=function(){Rn(),Dn()},ao.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var sa=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Un);ao.formatPrefix=function(n,t){var e=0;return(n=+n)&&(0>n&&(n*=-1),t&&(n=ao.round(n,Pn(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),sa[8+e/3]};var ha=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,pa=ao.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=ao.round(n,Pn(n,t))).toFixed(Math.max(0,Math.min(20,Pn(n*(1+1e-15),t))))}}),ga=ao.time={},va=Date;Hn.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){da.setUTCDate.apply(this._,arguments)},setDay:function(){da.setUTCDay.apply(this._,arguments)},setFullYear:function(){da.setUTCFullYear.apply(this._,arguments)},setHours:function(){da.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){da.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){da.setUTCMinutes.apply(this._,arguments)},setMonth:function(){da.setUTCMonth.apply(this._,arguments)},setSeconds:function(){da.setUTCSeconds.apply(this._,arguments)},setTime:function(){da.setTime.apply(this._,arguments)}};var da=Date.prototype;ga.year=On(function(n){return n=ga.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),ga.years=ga.year.range,ga.years.utc=ga.year.utc.range,ga.day=On(function(n){var t=new va(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),ga.days=ga.day.range,ga.days.utc=ga.day.utc.range,ga.dayOfYear=function(n){var t=ga.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=ga[n]=On(function(n){return(n=ga.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});ga[n+"s"]=e.range,ga[n+"s"].utc=e.utc.range,ga[n+"OfYear"]=function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)}}),ga.week=ga.sunday,ga.weeks=ga.sunday.range,ga.weeks.utc=ga.sunday.utc.range,ga.weekOfYear=ga.sundayOfYear;var ya={"-":"",_:" ",0:"0"},ma=/^\s*\d+/,Ma=/^%/;ao.locale=function(n){return{numberFormat:jn(n),timeFormat:Yn(n)}};var xa=ao.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], -shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ao.format=xa.numberFormat,ao.geo={},ft.prototype={s:0,t:0,add:function(n){st(n,this.t,ba),st(ba.s,this.s,this),this.s?this.t+=ba.t:this.s=ba.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ba=new ft;ao.geo.stream=function(n,t){n&&_a.hasOwnProperty(n.type)?_a[n.type](n,t):ht(n,t)};var _a={Feature:function(n,t){ht(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,i=e.length;++rn?4*Fo+n:n,Na.lineStart=Na.lineEnd=Na.point=b}};ao.geo.bounds=function(){function n(n,t){M.push(x=[f=n,h=n]),s>t&&(s=t),t>p&&(p=t)}function t(t,e){var r=dt([t*Yo,e*Yo]);if(y){var i=mt(y,r),u=[i[1],-i[0],0],o=mt(u,i);bt(o),o=_t(o);var l=t-g,c=l>0?1:-1,v=o[0]*Zo*c,d=xo(l)>180;if(d^(v>c*g&&c*t>v)){var m=o[1]*Zo;m>p&&(p=m)}else if(v=(v+360)%360-180,d^(v>c*g&&c*t>v)){var m=-o[1]*Zo;s>m&&(s=m)}else s>e&&(s=e),e>p&&(p=e);d?g>t?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t):h>=f?(f>t&&(f=t),t>h&&(h=t)):t>g?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t)}else n(t,e);y=r,g=t}function e(){b.point=t}function r(){x[0]=f,x[1]=h,b.point=n,y=null}function i(n,e){if(y){var r=n-g;m+=xo(r)>180?r+(r>0?360:-360):r}else v=n,d=e;Na.point(n,e),t(n,e)}function u(){Na.lineStart()}function o(){i(v,d),Na.lineEnd(),xo(m)>Uo&&(f=-(h=180)),x[0]=f,x[1]=h,y=null}function a(n,t){return(t-=n)<0?t+360:t}function l(n,t){return n[0]-t[0]}function c(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nka?(f=-(h=180),s=-(p=90)):m>Uo?p=90:-Uo>m&&(s=-90),x[0]=f,x[1]=h}};return function(n){p=h=-(f=s=1/0),M=[],ao.geo.stream(n,b);var t=M.length;if(t){M.sort(l);for(var e,r=1,i=M[0],u=[i];t>r;++r)e=M[r],c(e[0],i)||c(e[1],i)?(a(i[0],e[1])>a(i[0],i[1])&&(i[1]=e[1]),a(e[0],i[1])>a(i[0],i[1])&&(i[0]=e[0])):u.push(i=e);for(var o,e,g=-(1/0),t=u.length-1,r=0,i=u[t];t>=r;i=e,++r)e=u[r],(o=a(i[1],e[0]))>g&&(g=o,f=e[0],h=i[1])}return M=x=null,f===1/0||s===1/0?[[NaN,NaN],[NaN,NaN]]:[[f,s],[h,p]]}}(),ao.geo.centroid=function(n){Ea=Aa=Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,ja);var t=Da,e=Pa,r=Ua,i=t*t+e*e+r*r;return jo>i&&(t=qa,e=Ta,r=Ra,Uo>Aa&&(t=Ca,e=za,r=La),i=t*t+e*e+r*r,jo>i)?[NaN,NaN]:[Math.atan2(e,t)*Zo,tn(r/Math.sqrt(i))*Zo]};var Ea,Aa,Ca,za,La,qa,Ta,Ra,Da,Pa,Ua,ja={sphere:b,point:St,lineStart:Nt,lineEnd:Et,polygonStart:function(){ja.lineStart=At},polygonEnd:function(){ja.lineStart=Nt}},Fa=Rt(zt,jt,Ht,[-Fo,-Fo/2]),Ha=1e9;ao.geo.clipExtent=function(){var n,t,e,r,i,u,o={stream:function(n){return i&&(i.valid=!1),i=u(n),i.valid=!0,i},extent:function(a){return arguments.length?(u=Zt(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),i&&(i.valid=!1,i=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(ao.geo.conicEqualArea=function(){return Vt(Xt)}).raw=Xt,ao.geo.albers=function(){return ao.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},ao.geo.albersUsa=function(){function n(n){var u=n[0],o=n[1];return t=null,e(u,o),t||(r(u,o),t)||i(u,o),t}var t,e,r,i,u=ao.geo.albers(),o=ao.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ao.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=u.scale(),e=u.translate(),r=(n[0]-e[0])/t,i=(n[1]-e[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?o:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:u).invert(n)},n.stream=function(n){var t=u.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,i){t.point(n,i),e.point(n,i),r.point(n,i)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(u.precision(t),o.precision(t),a.precision(t),n):u.precision()},n.scale=function(t){return arguments.length?(u.scale(t),o.scale(.35*t),a.scale(t),n.translate(u.translate())):u.scale()},n.translate=function(t){if(!arguments.length)return u.translate();var c=u.scale(),f=+t[0],s=+t[1];return e=u.translate(t).clipExtent([[f-.455*c,s-.238*c],[f+.455*c,s+.238*c]]).stream(l).point,r=o.translate([f-.307*c,s+.201*c]).clipExtent([[f-.425*c+Uo,s+.12*c+Uo],[f-.214*c-Uo,s+.234*c-Uo]]).stream(l).point,i=a.translate([f-.205*c,s+.212*c]).clipExtent([[f-.214*c+Uo,s+.166*c+Uo],[f-.115*c-Uo,s+.234*c-Uo]]).stream(l).point,n},n.scale(1070)};var Oa,Ia,Ya,Za,Va,Xa,$a={point:b,lineStart:b,lineEnd:b,polygonStart:function(){Ia=0,$a.lineStart=$t},polygonEnd:function(){$a.lineStart=$a.lineEnd=$a.point=b,Oa+=xo(Ia/2)}},Ba={point:Bt,lineStart:b,lineEnd:b,polygonStart:b,polygonEnd:b},Wa={point:Gt,lineStart:Kt,lineEnd:Qt,polygonStart:function(){Wa.lineStart=ne},polygonEnd:function(){Wa.point=Gt,Wa.lineStart=Kt,Wa.lineEnd=Qt}};ao.geo.path=function(){function n(n){return n&&("function"==typeof a&&u.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=i(u)),ao.geo.stream(n,o)),u.result()}function t(){return o=null,n}var e,r,i,u,o,a=4.5;return n.area=function(n){return Oa=0,ao.geo.stream(n,i($a)),Oa},n.centroid=function(n){return Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,i(Wa)),Ua?[Da/Ua,Pa/Ua]:Ra?[qa/Ra,Ta/Ra]:La?[Ca/La,za/La]:[NaN,NaN]},n.bounds=function(n){return Va=Xa=-(Ya=Za=1/0),ao.geo.stream(n,i(Ba)),[[Ya,Za],[Va,Xa]]},n.projection=function(n){return arguments.length?(i=(e=n)?n.stream||re(n):m,t()):e},n.context=function(n){return arguments.length?(u=null==(r=n)?new Wt:new te(n),"function"!=typeof a&&u.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(u.pointRadius(+t),+t),n):a},n.projection(ao.geo.albersUsa()).context(null)},ao.geo.transform=function(n){return{stream:function(t){var e=new ie(t);for(var r in n)e[r]=n[r];return e}}},ie.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},ao.geo.projection=oe,ao.geo.projectionMutator=ae,(ao.geo.equirectangular=function(){return oe(ce)}).raw=ce.invert=ce,ao.geo.rotation=function(n){function t(t){return t=n(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t}return n=se(n[0]%360*Yo,n[1]*Yo,n.length>2?n[2]*Yo:0),t.invert=function(t){return t=n.invert(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t},t},fe.invert=ce,ao.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=se(-n[0]*Yo,-n[1]*Yo,0).invert,i=[];return e(null,null,1,{point:function(n,e){i.push(n=t(n,e)),n[0]*=Zo,n[1]*=Zo}}),{type:"Polygon",coordinates:[i]}}var t,e,r=[0,0],i=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=ve((t=+r)*Yo,i*Yo),n):t},n.precision=function(r){return arguments.length?(e=ve(t*Yo,(i=+r)*Yo),n):i},n.angle(90)},ao.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Yo,i=n[1]*Yo,u=t[1]*Yo,o=Math.sin(r),a=Math.cos(r),l=Math.sin(i),c=Math.cos(i),f=Math.sin(u),s=Math.cos(u);return Math.atan2(Math.sqrt((e=s*o)*e+(e=c*f-l*s*a)*e),l*f+c*s*a)},ao.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return ao.range(Math.ceil(u/d)*d,i,d).map(h).concat(ao.range(Math.ceil(c/y)*y,l,y).map(p)).concat(ao.range(Math.ceil(r/g)*g,e,g).filter(function(n){return xo(n%d)>Uo}).map(f)).concat(ao.range(Math.ceil(a/v)*v,o,v).filter(function(n){return xo(n%y)>Uo}).map(s))}var e,r,i,u,o,a,l,c,f,s,h,p,g=10,v=g,d=90,y=360,m=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(u).concat(p(l).slice(1),h(i).reverse().slice(1),p(c).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(u=+t[0][0],i=+t[1][0],c=+t[0][1],l=+t[1][1],u>i&&(t=u,u=i,i=t),c>l&&(t=c,c=l,l=t),n.precision(m)):[[u,c],[i,l]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(m)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],y=+t[1],n):[d,y]},n.minorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],n):[g,v]},n.precision=function(t){return arguments.length?(m=+t,f=ye(a,o,90),s=me(r,e,m),h=ye(c,l,90),p=me(u,i,m),n):m},n.majorExtent([[-180,-90+Uo],[180,90-Uo]]).minorExtent([[-180,-80-Uo],[180,80+Uo]])},ao.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||i.apply(this,arguments)]}}var t,e,r=Me,i=xe;return n.distance=function(){return ao.geo.distance(t||r.apply(this,arguments),e||i.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(i=t,e="function"==typeof t?null:t,n):i},n.precision=function(){return arguments.length?n:0},n},ao.geo.interpolate=function(n,t){return be(n[0]*Yo,n[1]*Yo,t[0]*Yo,t[1]*Yo)},ao.geo.length=function(n){return Ja=0,ao.geo.stream(n,Ga),Ja};var Ja,Ga={sphere:b,point:b,lineStart:_e,lineEnd:b,polygonStart:b,polygonEnd:b},Ka=we(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(ao.geo.azimuthalEqualArea=function(){return oe(Ka)}).raw=Ka;var Qa=we(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},m);(ao.geo.azimuthalEquidistant=function(){return oe(Qa)}).raw=Qa,(ao.geo.conicConformal=function(){return Vt(Se)}).raw=Se,(ao.geo.conicEquidistant=function(){return Vt(ke)}).raw=ke;var nl=we(function(n){return 1/n},Math.atan);(ao.geo.gnomonic=function(){return oe(nl)}).raw=nl,Ne.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Io]},(ao.geo.mercator=function(){return Ee(Ne)}).raw=Ne;var tl=we(function(){return 1},Math.asin);(ao.geo.orthographic=function(){return oe(tl)}).raw=tl;var el=we(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(ao.geo.stereographic=function(){return oe(el)}).raw=el,Ae.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Io]},(ao.geo.transverseMercator=function(){var n=Ee(Ae),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=Ae,ao.geom={},ao.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,i=En(e),u=En(r),o=n.length,a=[],l=[];for(t=0;o>t;t++)a.push([+i.call(this,n[t],t),+u.call(this,n[t],t),t]);for(a.sort(qe),t=0;o>t;t++)l.push([a[t][0],-a[t][1]]);var c=Le(a),f=Le(l),s=f[0]===c[0],h=f[f.length-1]===c[c.length-1],p=[];for(t=c.length-1;t>=0;--t)p.push(n[a[c[t]][2]]);for(t=+s;t=r&&c.x<=u&&c.y>=i&&c.y<=o?[[r,o],[u,o],[u,i],[r,i]]:[];f.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(u(n,t)/Uo)*Uo,y:Math.round(o(n,t)/Uo)*Uo,i:t}})}var r=Ce,i=ze,u=r,o=i,a=sl;return n?t(n):(t.links=function(n){return ar(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return ar(e(n)).cells.forEach(function(e,r){for(var i,u,o=e.site,a=e.edges.sort(Ve),l=-1,c=a.length,f=a[c-1].edge,s=f.l===o?f.r:f.l;++l=c,h=r>=f,p=h<<1|s;n.leaf=!1,n=n.nodes[p]||(n.nodes[p]=hr()),s?i=c:a=c,h?o=f:l=f,u(n,t,e,r,i,o,a,l)}var f,s,h,p,g,v,d,y,m,M=En(a),x=En(l);if(null!=t)v=t,d=e,y=r,m=i;else if(y=m=-(v=d=1/0),s=[],h=[],g=n.length,o)for(p=0;g>p;++p)f=n[p],f.xy&&(y=f.x),f.y>m&&(m=f.y),s.push(f.x),h.push(f.y);else for(p=0;g>p;++p){var b=+M(f=n[p],p),_=+x(f,p);v>b&&(v=b),d>_&&(d=_),b>y&&(y=b),_>m&&(m=_),s.push(b),h.push(_)}var w=y-v,S=m-d;w>S?m=d+w:y=v+S;var k=hr();if(k.add=function(n){u(k,n,+M(n,++p),+x(n,p),v,d,y,m)},k.visit=function(n){pr(n,k,v,d,y,m)},k.find=function(n){return gr(k,n[0],n[1],v,d,y,m)},p=-1,null==t){for(;++p=0?n.slice(0,t):n,r=t>=0?n.slice(t+1):"in";return e=vl.get(e)||gl,r=dl.get(r)||m,br(r(e.apply(null,lo.call(arguments,1))))},ao.interpolateHcl=Rr,ao.interpolateHsl=Dr,ao.interpolateLab=Pr,ao.interpolateRound=Ur,ao.transform=function(n){var t=fo.createElementNS(ao.ns.prefix.svg,"g");return(ao.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new jr(e?e.matrix:yl)})(n)},jr.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var yl={a:1,b:0,c:0,d:1,e:0,f:0};ao.interpolateTransform=$r,ao.layout={},ao.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++ea*a/y){if(v>l){var c=t.charge/l;n.px-=u*c,n.py-=o*c}return!0}if(t.point&&l&&v>l){var c=t.pointCharge/l;n.px-=u*c,n.py-=o*c}}return!t.charge}}function t(n){n.px=ao.event.x,n.py=ao.event.y,l.resume()}var e,r,i,u,o,a,l={},c=ao.dispatch("start","tick","end"),f=[1,1],s=.9,h=ml,p=Ml,g=-30,v=xl,d=.1,y=.64,M=[],x=[];return l.tick=function(){if((i*=.99)<.005)return e=null,c.end({type:"end",alpha:i=0}),!0;var t,r,l,h,p,v,y,m,b,_=M.length,w=x.length;for(r=0;w>r;++r)l=x[r],h=l.source,p=l.target,m=p.x-h.x,b=p.y-h.y,(v=m*m+b*b)&&(v=i*o[r]*((v=Math.sqrt(v))-u[r])/v,m*=v,b*=v,p.x-=m*(y=h.weight+p.weight?h.weight/(h.weight+p.weight):.5),p.y-=b*y,h.x+=m*(y=1-y),h.y+=b*y);if((y=i*d)&&(m=f[0]/2,b=f[1]/2,r=-1,y))for(;++r<_;)l=M[r],l.x+=(m-l.x)*y,l.y+=(b-l.y)*y;if(g)for(ri(t=ao.geom.quadtree(M),i,a),r=-1;++r<_;)(l=M[r]).fixed||t.visit(n(l));for(r=-1;++r<_;)l=M[r],l.fixed?(l.x=l.px,l.y=l.py):(l.x-=(l.px-(l.px=l.x))*s,l.y-=(l.py-(l.py=l.y))*s);c.tick({type:"tick",alpha:i})},l.nodes=function(n){return arguments.length?(M=n,l):M},l.links=function(n){return arguments.length?(x=n,l):x},l.size=function(n){return arguments.length?(f=n,l):f},l.linkDistance=function(n){return arguments.length?(h="function"==typeof n?n:+n,l):h},l.distance=l.linkDistance,l.linkStrength=function(n){return arguments.length?(p="function"==typeof n?n:+n,l):p},l.friction=function(n){return arguments.length?(s=+n,l):s},l.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,l):g},l.chargeDistance=function(n){return arguments.length?(v=n*n,l):Math.sqrt(v)},l.gravity=function(n){return arguments.length?(d=+n,l):d},l.theta=function(n){return arguments.length?(y=n*n,l):Math.sqrt(y)},l.alpha=function(n){return arguments.length?(n=+n,i?n>0?i=n:(e.c=null,e.t=NaN,e=null,c.end({type:"end",alpha:i=0})):n>0&&(c.start({type:"start",alpha:i=n}),e=qn(l.tick)),l):i},l.start=function(){function n(n,r){if(!e){for(e=new Array(i),l=0;i>l;++l)e[l]=[];for(l=0;c>l;++l){var u=x[l];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var o,a=e[t],l=-1,f=a.length;++lt;++t)(r=M[t]).index=t,r.weight=0;for(t=0;c>t;++t)r=x[t],"number"==typeof r.source&&(r.source=M[r.source]),"number"==typeof r.target&&(r.target=M[r.target]),++r.source.weight,++r.target.weight;for(t=0;i>t;++t)r=M[t],isNaN(r.x)&&(r.x=n("x",s)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof h)for(t=0;c>t;++t)u[t]=+h.call(this,x[t],t);else for(t=0;c>t;++t)u[t]=h;if(o=[],"function"==typeof p)for(t=0;c>t;++t)o[t]=+p.call(this,x[t],t);else for(t=0;c>t;++t)o[t]=p;if(a=[],"function"==typeof g)for(t=0;i>t;++t)a[t]=+g.call(this,M[t],t);else for(t=0;i>t;++t)a[t]=g;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return r||(r=ao.behavior.drag().origin(m).on("dragstart.force",Qr).on("drag.force",t).on("dragend.force",ni)),arguments.length?void this.on("mouseover.force",ti).on("mouseout.force",ei).call(r):r},ao.rebind(l,c,"on")};var ml=20,Ml=1,xl=1/0;ao.layout.hierarchy=function(){function n(i){var u,o=[i],a=[];for(i.depth=0;null!=(u=o.pop());)if(a.push(u),(c=e.call(n,u,u.depth))&&(l=c.length)){for(var l,c,f;--l>=0;)o.push(f=c[l]),f.parent=u,f.depth=u.depth+1;r&&(u.value=0),u.children=c}else r&&(u.value=+r.call(n,u,u.depth)||0),delete u.children;return oi(i,function(n){var e,i;t&&(e=n.children)&&e.sort(t),r&&(i=n.parent)&&(i.value+=n.value)}),a}var t=ci,e=ai,r=li;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(ui(t,function(n){n.children&&(n.value=0)}),oi(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},ao.layout.partition=function(){function n(t,e,r,i){var u=t.children;if(t.x=e,t.y=t.depth*i,t.dx=r,t.dy=i,u&&(o=u.length)){var o,a,l,c=-1;for(r=t.value?r/t.value:0;++cs?-1:1),g=ao.sum(c),v=g?(s-l*p)/g:0,d=ao.range(l),y=[];return null!=e&&d.sort(e===bl?function(n,t){return c[t]-c[n]}:function(n,t){return e(o[n],o[t])}),d.forEach(function(n){y[n]={data:o[n],value:a=c[n],startAngle:f,endAngle:f+=a*v+p,padAngle:h}}),y}var t=Number,e=bl,r=0,i=Ho,u=0;return n.value=function(e){return arguments.length?(t=e,n):t},n.sort=function(t){return arguments.length?(e=t,n):e},n.startAngle=function(t){return arguments.length?(r=t,n):r},n.endAngle=function(t){return arguments.length?(i=t,n):i},n.padAngle=function(t){return arguments.length?(u=t,n):u},n};var bl={};ao.layout.stack=function(){function n(a,l){if(!(h=a.length))return a;var c=a.map(function(e,r){return t.call(n,e,r)}),f=c.map(function(t){return t.map(function(t,e){return[u.call(n,t,e),o.call(n,t,e)]})}),s=e.call(n,f,l);c=ao.permute(c,s),f=ao.permute(f,s);var h,p,g,v,d=r.call(n,f,l),y=c[0].length;for(g=0;y>g;++g)for(i.call(n,c[0][g],v=d[g],f[0][g][1]),p=1;h>p;++p)i.call(n,c[p][g],v+=f[p-1][g][1],f[p][g][1]);return a}var t=m,e=gi,r=vi,i=pi,u=si,o=hi;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:_l.get(t)||gi,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:wl.get(t)||vi,n):r},n.x=function(t){return arguments.length?(u=t,n):u},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(i=t,n):i},n};var _l=ao.map({"inside-out":function(n){var t,e,r=n.length,i=n.map(di),u=n.map(yi),o=ao.range(r).sort(function(n,t){return i[n]-i[t]}),a=0,l=0,c=[],f=[];for(t=0;r>t;++t)e=o[t],l>a?(a+=u[e],c.push(e)):(l+=u[e],f.push(e));return f.reverse().concat(c)},reverse:function(n){return ao.range(n.length).reverse()},"default":gi}),wl=ao.map({silhouette:function(n){var t,e,r,i=n.length,u=n[0].length,o=[],a=0,l=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;u>e;++e)l[e]=(a-o[e])/2;return l},wiggle:function(n){var t,e,r,i,u,o,a,l,c,f=n.length,s=n[0],h=s.length,p=[];for(p[0]=l=c=0,e=1;h>e;++e){for(t=0,i=0;f>t;++t)i+=n[t][e][1];for(t=0,u=0,a=s[e][0]-s[e-1][0];f>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;u+=o*n[t][e][1]}p[e]=l-=i?u/i*a:0,c>l&&(c=l)}for(e=0;h>e;++e)p[e]-=c;return p},expand:function(n){var t,e,r,i=n.length,u=n[0].length,o=1/i,a=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];if(r)for(t=0;i>t;t++)n[t][e][1]/=r;else for(t=0;i>t;t++)n[t][e][1]=o}for(e=0;u>e;++e)a[e]=0;return a},zero:vi});ao.layout.histogram=function(){function n(n,u){for(var o,a,l=[],c=n.map(e,this),f=r.call(this,c,u),s=i.call(this,f,c,u),u=-1,h=c.length,p=s.length-1,g=t?1:1/h;++u0)for(u=-1;++u=f[0]&&a<=f[1]&&(o=l[ao.bisect(s,a,1,p)-1],o.y+=g,o.push(n[u]));return l}var t=!0,e=Number,r=bi,i=Mi;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=En(t),n):r},n.bins=function(t){return arguments.length?(i="number"==typeof t?function(n){return xi(n,t)}:En(t),n):i},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},ao.layout.pack=function(){function n(n,u){var o=e.call(this,n,u),a=o[0],l=i[0],c=i[1],f=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,oi(a,function(n){n.r=+f(n.value)}),oi(a,Ni),r){var s=r*(t?1:Math.max(2*a.r/l,2*a.r/c))/2;oi(a,function(n){n.r+=s}),oi(a,Ni),oi(a,function(n){n.r-=s})}return Ci(a,l/2,c/2,t?1:1/Math.max(2*a.r/l,2*a.r/c)),o}var t,e=ao.layout.hierarchy().sort(_i),r=0,i=[1,1];return n.size=function(t){return arguments.length?(i=t,n):i},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},ii(n,e)},ao.layout.tree=function(){function n(n,i){var f=o.call(this,n,i),s=f[0],h=t(s);if(oi(h,e),h.parent.m=-h.z,ui(h,r),c)ui(s,u);else{var p=s,g=s,v=s;ui(s,function(n){n.xg.x&&(g=n),n.depth>v.depth&&(v=n)});var d=a(p,g)/2-p.x,y=l[0]/(g.x+a(g,p)/2+d),m=l[1]/(v.depth||1);ui(s,function(n){n.x=(n.x+d)*y,n.y=n.depth*m})}return f}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var i,u=t.children,o=0,a=u.length;a>o;++o)r.push((u[o]=i={_:u[o],parent:t,children:(i=u[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){Di(n);var u=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-u):n.z=u}else r&&(n.z=r.z+a(n._,r._));n.parent.A=i(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function i(n,t,e){if(t){for(var r,i=n,u=n,o=t,l=i.parent.children[0],c=i.m,f=u.m,s=o.m,h=l.m;o=Ti(o),i=qi(i),o&&i;)l=qi(l),u=Ti(u),u.a=n,r=o.z+s-i.z-c+a(o._,i._),r>0&&(Ri(Pi(o,n,e),n,r),c+=r,f+=r),s+=o.m,c+=i.m,h+=l.m,f+=u.m;o&&!Ti(u)&&(u.t=o,u.m+=s-f),i&&!qi(l)&&(l.t=i,l.m+=c-h,e=n)}return e}function u(n){n.x*=l[0],n.y=n.depth*l[1]}var o=ao.layout.hierarchy().sort(null).value(null),a=Li,l=[1,1],c=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(c=null==(l=t)?u:null,n):c?null:l},n.nodeSize=function(t){return arguments.length?(c=null==(l=t)?null:u,n):c?l:null},ii(n,o)},ao.layout.cluster=function(){function n(n,u){var o,a=t.call(this,n,u),l=a[0],c=0;oi(l,function(n){var t=n.children;t&&t.length?(n.x=ji(t),n.y=Ui(t)):(n.x=o?c+=e(n,o):0,n.y=0,o=n)});var f=Fi(l),s=Hi(l),h=f.x-e(f,s)/2,p=s.x+e(s,f)/2;return oi(l,i?function(n){n.x=(n.x-l.x)*r[0],n.y=(l.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(p-h)*r[0],n.y=(1-(l.y?n.y/l.y:1))*r[1]}),a}var t=ao.layout.hierarchy().sort(null).value(null),e=Li,r=[1,1],i=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(i=null==(r=t),n):i?null:r},n.nodeSize=function(t){return arguments.length?(i=null!=(r=t),n):i?r:null},ii(n,t)},ao.layout.treemap=function(){function n(n,t){for(var e,r,i=-1,u=n.length;++it?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var u=e.children;if(u&&u.length){var o,a,l,c=s(e),f=[],h=u.slice(),g=1/0,v="slice"===p?c.dx:"dice"===p?c.dy:"slice-dice"===p?1&e.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(n(h,c.dx*c.dy/e.value),f.area=0;(l=h.length)>0;)f.push(o=h[l-1]),f.area+=o.area,"squarify"!==p||(a=r(f,v))<=g?(h.pop(),g=a):(f.area-=f.pop().area,i(f,v,c,!1),v=Math.min(c.dx,c.dy),f.length=f.area=0,g=1/0);f.length&&(i(f,v,c,!0),f.length=f.area=0),u.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var u,o=s(t),a=r.slice(),l=[];for(n(a,o.dx*o.dy/t.value),l.area=0;u=a.pop();)l.push(u),l.area+=u.area,null!=u.z&&(i(l,u.z?o.dx:o.dy,o,!a.length),l.length=l.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,i=0,u=1/0,o=-1,a=n.length;++oe&&(u=e),e>i&&(i=e));return r*=r,t*=t,r?Math.max(t*i*g/r,r/(t*u*g)):1/0}function i(n,t,e,r){var i,u=-1,o=n.length,a=e.x,c=e.y,f=t?l(n.area/t):0; -if(t==e.dx){for((r||f>e.dy)&&(f=e.dy);++ue.dx)&&(f=e.dx);++ue&&(t=1),1>e&&(n=0),function(){var e,r,i;do e=2*Math.random()-1,r=2*Math.random()-1,i=e*e+r*r;while(!i||i>1);return n+t*e*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var n=ao.random.normal.apply(ao,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=ao.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},ao.scale={};var Sl={floor:m,ceil:m};ao.scale.linear=function(){return Wi([0,1],[0,1],Mr,!1)};var kl={s:1,g:1,p:1,r:1,e:1};ao.scale.log=function(){return ru(ao.scale.linear().domain([0,1]),10,!0,[1,10])};var Nl=ao.format(".0e"),El={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};ao.scale.pow=function(){return iu(ao.scale.linear(),1,[0,1])},ao.scale.sqrt=function(){return ao.scale.pow().exponent(.5)},ao.scale.ordinal=function(){return ou([],{t:"range",a:[[]]})},ao.scale.category10=function(){return ao.scale.ordinal().range(Al)},ao.scale.category20=function(){return ao.scale.ordinal().range(Cl)},ao.scale.category20b=function(){return ao.scale.ordinal().range(zl)},ao.scale.category20c=function(){return ao.scale.ordinal().range(Ll)};var Al=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xn),Cl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xn),zl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xn),Ll=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xn);ao.scale.quantile=function(){return au([],[])},ao.scale.quantize=function(){return lu(0,1,[0,1])},ao.scale.threshold=function(){return cu([.5],[0,1])},ao.scale.identity=function(){return fu([0,1])},ao.svg={},ao.svg.arc=function(){function n(){var n=Math.max(0,+e.apply(this,arguments)),c=Math.max(0,+r.apply(this,arguments)),f=o.apply(this,arguments)-Io,s=a.apply(this,arguments)-Io,h=Math.abs(s-f),p=f>s?0:1;if(n>c&&(g=c,c=n,n=g),h>=Oo)return t(c,p)+(n?t(n,1-p):"")+"Z";var g,v,d,y,m,M,x,b,_,w,S,k,N=0,E=0,A=[];if((y=(+l.apply(this,arguments)||0)/2)&&(d=u===ql?Math.sqrt(n*n+c*c):+u.apply(this,arguments),p||(E*=-1),c&&(E=tn(d/c*Math.sin(y))),n&&(N=tn(d/n*Math.sin(y)))),c){m=c*Math.cos(f+E),M=c*Math.sin(f+E),x=c*Math.cos(s-E),b=c*Math.sin(s-E);var C=Math.abs(s-f-2*E)<=Fo?0:1;if(E&&yu(m,M,x,b)===p^C){var z=(f+s)/2;m=c*Math.cos(z),M=c*Math.sin(z),x=b=null}}else m=M=0;if(n){_=n*Math.cos(s-N),w=n*Math.sin(s-N),S=n*Math.cos(f+N),k=n*Math.sin(f+N);var L=Math.abs(f-s+2*N)<=Fo?0:1;if(N&&yu(_,w,S,k)===1-p^L){var q=(f+s)/2;_=n*Math.cos(q),w=n*Math.sin(q),S=k=null}}else _=w=0;if(h>Uo&&(g=Math.min(Math.abs(c-n)/2,+i.apply(this,arguments)))>.001){v=c>n^p?0:1;var T=g,R=g;if(Fo>h){var D=null==S?[_,w]:null==x?[m,M]:Re([m,M],[S,k],[x,b],[_,w]),P=m-D[0],U=M-D[1],j=x-D[0],F=b-D[1],H=1/Math.sin(Math.acos((P*j+U*F)/(Math.sqrt(P*P+U*U)*Math.sqrt(j*j+F*F)))/2),O=Math.sqrt(D[0]*D[0]+D[1]*D[1]);R=Math.min(g,(n-O)/(H-1)),T=Math.min(g,(c-O)/(H+1))}if(null!=x){var I=mu(null==S?[_,w]:[S,k],[m,M],c,T,p),Y=mu([x,b],[_,w],c,T,p);g===T?A.push("M",I[0],"A",T,",",T," 0 0,",v," ",I[1],"A",c,",",c," 0 ",1-p^yu(I[1][0],I[1][1],Y[1][0],Y[1][1]),",",p," ",Y[1],"A",T,",",T," 0 0,",v," ",Y[0]):A.push("M",I[0],"A",T,",",T," 0 1,",v," ",Y[0])}else A.push("M",m,",",M);if(null!=S){var Z=mu([m,M],[S,k],n,-R,p),V=mu([_,w],null==x?[m,M]:[x,b],n,-R,p);g===R?A.push("L",V[0],"A",R,",",R," 0 0,",v," ",V[1],"A",n,",",n," 0 ",p^yu(V[1][0],V[1][1],Z[1][0],Z[1][1]),",",1-p," ",Z[1],"A",R,",",R," 0 0,",v," ",Z[0]):A.push("L",V[0],"A",R,",",R," 0 0,",v," ",Z[0])}else A.push("L",_,",",w)}else A.push("M",m,",",M),null!=x&&A.push("A",c,",",c," 0 ",C,",",p," ",x,",",b),A.push("L",_,",",w),null!=S&&A.push("A",n,",",n," 0 ",L,",",1-p," ",S,",",k);return A.push("Z"),A.join("")}function t(n,t){return"M0,"+n+"A"+n+","+n+" 0 1,"+t+" 0,"+-n+"A"+n+","+n+" 0 1,"+t+" 0,"+n}var e=hu,r=pu,i=su,u=ql,o=gu,a=vu,l=du;return n.innerRadius=function(t){return arguments.length?(e=En(t),n):e},n.outerRadius=function(t){return arguments.length?(r=En(t),n):r},n.cornerRadius=function(t){return arguments.length?(i=En(t),n):i},n.padRadius=function(t){return arguments.length?(u=t==ql?ql:En(t),n):u},n.startAngle=function(t){return arguments.length?(o=En(t),n):o},n.endAngle=function(t){return arguments.length?(a=En(t),n):a},n.padAngle=function(t){return arguments.length?(l=En(t),n):l},n.centroid=function(){var n=(+e.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+o.apply(this,arguments)+ +a.apply(this,arguments))/2-Io;return[Math.cos(t)*n,Math.sin(t)*n]},n};var ql="auto";ao.svg.line=function(){return Mu(m)};var Tl=ao.map({linear:xu,"linear-closed":bu,step:_u,"step-before":wu,"step-after":Su,basis:zu,"basis-open":Lu,"basis-closed":qu,bundle:Tu,cardinal:Eu,"cardinal-open":ku,"cardinal-closed":Nu,monotone:Fu});Tl.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Rl=[0,2/3,1/3,0],Dl=[0,1/3,2/3,0],Pl=[0,1/6,2/3,1/6];ao.svg.line.radial=function(){var n=Mu(Hu);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},wu.reverse=Su,Su.reverse=wu,ao.svg.area=function(){return Ou(m)},ao.svg.area.radial=function(){var n=Ou(Hu);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},ao.svg.chord=function(){function n(n,a){var l=t(this,u,n,a),c=t(this,o,n,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(e(l,c)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,c.r,c.p0)+r(c.r,c.p1,c.a1-c.a0)+i(c.r,c.p1,l.r,l.p0))+"Z"}function t(n,t,e,r){var i=t.call(n,e,r),u=a.call(n,i,r),o=l.call(n,i,r)-Io,f=c.call(n,i,r)-Io;return{r:u,a0:o,a1:f,p0:[u*Math.cos(o),u*Math.sin(o)],p1:[u*Math.cos(f),u*Math.sin(f)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>Fo)+",1 "+t}function i(n,t,e,r){return"Q 0,0 "+r}var u=Me,o=xe,a=Iu,l=gu,c=vu;return n.radius=function(t){return arguments.length?(a=En(t),n):a},n.source=function(t){return arguments.length?(u=En(t),n):u},n.target=function(t){return arguments.length?(o=En(t),n):o},n.startAngle=function(t){return arguments.length?(l=En(t),n):l},n.endAngle=function(t){return arguments.length?(c=En(t),n):c},n},ao.svg.diagonal=function(){function n(n,i){var u=t.call(this,n,i),o=e.call(this,n,i),a=(u.y+o.y)/2,l=[u,{x:u.x,y:a},{x:o.x,y:a},o];return l=l.map(r),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=Me,e=xe,r=Yu;return n.source=function(e){return arguments.length?(t=En(e),n):t},n.target=function(t){return arguments.length?(e=En(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},ao.svg.diagonal.radial=function(){var n=ao.svg.diagonal(),t=Yu,e=n.projection;return n.projection=function(n){return arguments.length?e(Zu(t=n)):t},n},ao.svg.symbol=function(){function n(n,r){return(Ul.get(t.call(this,n,r))||$u)(e.call(this,n,r))}var t=Xu,e=Vu;return n.type=function(e){return arguments.length?(t=En(e),n):t},n.size=function(t){return arguments.length?(e=En(t),n):e},n};var Ul=ao.map({circle:$u,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Fl)),e=t*Fl;return"M0,"+-t+"L"+e+",0 0,"+t+" "+-e+",0Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});ao.svg.symbolTypes=Ul.keys();var jl=Math.sqrt(3),Fl=Math.tan(30*Yo);Co.transition=function(n){for(var t,e,r=Hl||++Zl,i=Ku(n),u=[],o=Ol||{time:Date.now(),ease:Nr,delay:0,duration:250},a=-1,l=this.length;++au;u++){i.push(t=[]);for(var e=this[u],a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return Wu(i,this.namespace,this.id)},Yl.tween=function(n,t){var e=this.id,r=this.namespace;return arguments.length<2?this.node()[r][e].tween.get(n):Y(this,null==t?function(t){t[r][e].tween.remove(n)}:function(i){i[r][e].tween.set(n,t)})},Yl.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function u(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?$r:Mr,a=ao.ns.qualify(n);return Ju(this,"attr."+n,t,a.local?u:i)},Yl.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(i));return r&&function(n){this.setAttribute(i,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(i.space,i.local));return r&&function(n){this.setAttributeNS(i.space,i.local,r(n))}}var i=ao.ns.qualify(n);return this.tween("attr."+n,i.local?r:e)},Yl.style=function(n,e,r){function i(){this.style.removeProperty(n)}function u(e){return null==e?i:(e+="",function(){var i,u=t(this).getComputedStyle(this,null).getPropertyValue(n);return u!==e&&(i=Mr(u,e),function(t){this.style.setProperty(n,i(t),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof n){2>o&&(e="");for(r in n)this.style(r,n[r],e);return this}r=""}return Ju(this,"style."+n,e,u)},Yl.styleTween=function(n,e,r){function i(i,u){var o=e.call(this,i,u,t(this).getComputedStyle(this,null).getPropertyValue(n));return o&&function(t){this.style.setProperty(n,o(t),r)}}return arguments.length<3&&(r=""),this.tween("style."+n,i)},Yl.text=function(n){return Ju(this,"text",n,Gu)},Yl.remove=function(){var n=this.namespace;return this.each("end.transition",function(){var t;this[n].count<2&&(t=this.parentNode)&&t.removeChild(this)})},Yl.ease=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].ease:("function"!=typeof n&&(n=ao.ease.apply(ao,arguments)),Y(this,function(r){r[e][t].ease=n}))},Yl.delay=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].delay:Y(this,"function"==typeof n?function(r,i,u){r[e][t].delay=+n.call(r,r.__data__,i,u)}:(n=+n,function(r){r[e][t].delay=n}))},Yl.duration=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].duration:Y(this,"function"==typeof n?function(r,i,u){r[e][t].duration=Math.max(1,n.call(r,r.__data__,i,u))}:(n=Math.max(1,n),function(r){r[e][t].duration=n}))},Yl.each=function(n,t){var e=this.id,r=this.namespace;if(arguments.length<2){var i=Ol,u=Hl;try{Hl=e,Y(this,function(t,i,u){Ol=t[r][e],n.call(t,t.__data__,i,u)})}finally{Ol=i,Hl=u}}else Y(this,function(i){var u=i[r][e];(u.event||(u.event=ao.dispatch("start","end","interrupt"))).on(n,t)});return this},Yl.transition=function(){for(var n,t,e,r,i=this.id,u=++Zl,o=this.namespace,a=[],l=0,c=this.length;c>l;l++){a.push(n=[]);for(var t=this[l],f=0,s=t.length;s>f;f++)(e=t[f])&&(r=e[o][i],Qu(e,f,o,u,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})),n.push(e)}return Wu(a,o,u)},ao.svg.axis=function(){function n(n){n.each(function(){var n,c=ao.select(this),f=this.__chart__||e,s=this.__chart__=e.copy(),h=null==l?s.ticks?s.ticks.apply(s,a):s.domain():l,p=null==t?s.tickFormat?s.tickFormat.apply(s,a):m:t,g=c.selectAll(".tick").data(h,s),v=g.enter().insert("g",".domain").attr("class","tick").style("opacity",Uo),d=ao.transition(g.exit()).style("opacity",Uo).remove(),y=ao.transition(g.order()).style("opacity",1),M=Math.max(i,0)+o,x=Zi(s),b=c.selectAll(".domain").data([0]),_=(b.enter().append("path").attr("class","domain"),ao.transition(b));v.append("line"),v.append("text");var w,S,k,N,E=v.select("line"),A=y.select("line"),C=g.select("text").text(p),z=v.select("text"),L=y.select("text"),q="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r?(n=no,w="x",k="y",S="x2",N="y2",C.attr("dy",0>q?"0em":".71em").style("text-anchor","middle"),_.attr("d","M"+x[0]+","+q*u+"V0H"+x[1]+"V"+q*u)):(n=to,w="y",k="x",S="y2",N="x2",C.attr("dy",".32em").style("text-anchor",0>q?"end":"start"),_.attr("d","M"+q*u+","+x[0]+"H0V"+x[1]+"H"+q*u)),E.attr(N,q*i),z.attr(k,q*M),A.attr(S,0).attr(N,q*i),L.attr(w,0).attr(k,q*M),s.rangeBand){var T=s,R=T.rangeBand()/2;f=s=function(n){return T(n)+R}}else f.rangeBand?f=s:d.call(n,s,f);v.call(n,f,s),y.call(n,s,s)})}var t,e=ao.scale.linear(),r=Vl,i=6,u=6,o=3,a=[10],l=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Xl?t+"":Vl,n):r},n.ticks=function(){return arguments.length?(a=co(arguments),n):a},n.tickValues=function(t){return arguments.length?(l=t,n):l},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(i=+t,u=+arguments[e-1],n):i},n.innerTickSize=function(t){return arguments.length?(i=+t,n):i},n.outerTickSize=function(t){return arguments.length?(u=+t,n):u},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var Vl="bottom",Xl={top:1,right:1,bottom:1,left:1};ao.svg.brush=function(){function n(t){t.each(function(){var t=ao.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=t.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),t.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=t.selectAll(".resize").data(v,m);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return $l[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,s=ao.transition(t),h=ao.transition(o);c&&(l=Zi(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(s)),f&&(l=Zi(f),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(s)),e(s)})}function e(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+s[+/e$/.test(n)]+","+h[+/^s/.test(n)]+")"})}function r(n){n.select(".extent").attr("x",s[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1]-s[0])}function i(n){n.select(".extent").attr("y",h[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function u(){function u(){32==ao.event.keyCode&&(C||(M=null,L[0]-=s[1],L[1]-=h[1],C=2),S())}function v(){32==ao.event.keyCode&&2==C&&(L[0]+=s[1],L[1]+=h[1],C=0,S())}function d(){var n=ao.mouse(b),t=!1;x&&(n[0]+=x[0],n[1]+=x[1]),C||(ao.event.altKey?(M||(M=[(s[0]+s[1])/2,(h[0]+h[1])/2]),L[0]=s[+(n[0]f?(i=r,r=f):i=f),v[0]!=r||v[1]!=i?(e?a=null:o=null,v[0]=r,v[1]=i,!0):void 0}function m(){d(),k.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),ao.select("body").style("cursor",null),q.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),z(),w({type:"brushend"})}var M,x,b=this,_=ao.select(ao.event.target),w=l.of(b,arguments),k=ao.select(b),N=_.datum(),E=!/^(n|s)$/.test(N)&&c,A=!/^(e|w)$/.test(N)&&f,C=_.classed("extent"),z=W(b),L=ao.mouse(b),q=ao.select(t(b)).on("keydown.brush",u).on("keyup.brush",v);if(ao.event.changedTouches?q.on("touchmove.brush",d).on("touchend.brush",m):q.on("mousemove.brush",d).on("mouseup.brush",m),k.interrupt().selectAll("*").interrupt(),C)L[0]=s[0]-L[0],L[1]=h[0]-L[1];else if(N){var T=+/w$/.test(N),R=+/^n/.test(N);x=[s[1-T]-L[0],h[1-R]-L[1]],L[0]=s[T],L[1]=h[R]}else ao.event.altKey&&(M=L.slice());k.style("pointer-events","none").selectAll(".resize").style("display",null),ao.select("body").style("cursor",_.style("cursor")),w({type:"brushstart"}),d()}var o,a,l=N(n,"brushstart","brush","brushend"),c=null,f=null,s=[0,0],h=[0,0],p=!0,g=!0,v=Bl[0];return n.event=function(n){n.each(function(){var n=l.of(this,arguments),t={x:s,y:h,i:o,j:a},e=this.__chart__||t;this.__chart__=t,Hl?ao.select(this).transition().each("start.brush",function(){o=e.i,a=e.j,s=e.x,h=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=xr(s,t.x),r=xr(h,t.y);return o=a=null,function(i){s=t.x=e(i),h=t.y=r(i),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i,a=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,v=Bl[!c<<1|!f],n):c},n.y=function(t){return arguments.length?(f=t,v=Bl[!c<<1|!f],n):f},n.clamp=function(t){return arguments.length?(c&&f?(p=!!t[0],g=!!t[1]):c?p=!!t:f&&(g=!!t),n):c&&f?[p,g]:c?p:f?g:null},n.extent=function(t){var e,r,i,u,l;return arguments.length?(c&&(e=t[0],r=t[1],f&&(e=e[0],r=r[0]),o=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(l=e,e=r,r=l),e==s[0]&&r==s[1]||(s=[e,r])),f&&(i=t[0],u=t[1],c&&(i=i[1],u=u[1]),a=[i,u],f.invert&&(i=f(i),u=f(u)),i>u&&(l=i,i=u,u=l),i==h[0]&&u==h[1]||(h=[i,u])),n):(c&&(o?(e=o[0],r=o[1]):(e=s[0],r=s[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(l=e,e=r,r=l))),f&&(a?(i=a[0],u=a[1]):(i=h[0],u=h[1],f.invert&&(i=f.invert(i),u=f.invert(u)),i>u&&(l=i,i=u,u=l))),c&&f?[[e,i],[r,u]]:c?[e,r]:f&&[i,u])},n.clear=function(){return n.empty()||(s=[0,0],h=[0,0],o=a=null),n},n.empty=function(){return!!c&&s[0]==s[1]||!!f&&h[0]==h[1]},ao.rebind(n,l,"on")};var $l={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Bl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Wl=ga.format=xa.timeFormat,Jl=Wl.utc,Gl=Jl("%Y-%m-%dT%H:%M:%S.%LZ");Wl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?eo:Gl,eo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},eo.toString=Gl.toString,ga.second=On(function(n){return new va(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),ga.seconds=ga.second.range,ga.seconds.utc=ga.second.utc.range,ga.minute=On(function(n){return new va(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),ga.minutes=ga.minute.range,ga.minutes.utc=ga.minute.utc.range,ga.hour=On(function(n){var t=n.getTimezoneOffset()/60;return new va(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),ga.hours=ga.hour.range,ga.hours.utc=ga.hour.utc.range,ga.month=On(function(n){return n=ga.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),ga.months=ga.month.range,ga.months.utc=ga.month.utc.range;var Kl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ql=[[ga.second,1],[ga.second,5],[ga.second,15],[ga.second,30],[ga.minute,1],[ga.minute,5],[ga.minute,15],[ga.minute,30],[ga.hour,1],[ga.hour,3],[ga.hour,6],[ga.hour,12],[ga.day,1],[ga.day,2],[ga.week,1],[ga.month,1],[ga.month,3],[ga.year,1]],nc=Wl.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",zt]]),tc={range:function(n,t,e){return ao.range(Math.ceil(n/e)*e,+t,e).map(io)},floor:m,ceil:m};Ql.year=ga.year,ga.scale=function(){return ro(ao.scale.linear(),Ql,nc)};var ec=Ql.map(function(n){return[n[0].utc,n[1]]}),rc=Jl.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",zt]]);ec.year=ga.year.utc,ga.scale.utc=function(){return ro(ao.scale.linear(),ec,rc)},ao.text=An(function(n){return n.responseText}),ao.json=function(n,t){return Cn(n,"application/json",uo,t)},ao.html=function(n,t){return Cn(n,"text/html",oo,t)},ao.xml=An(function(n){return n.responseXML}),"function"==typeof define&&define.amd?(this.d3=ao,define(ao)):"object"==typeof module&&module.exports?module.exports=ao:this.d3=ao}(); \ No newline at end of file diff --git a/tmp_overview_docs/js/dagre-d3.js b/tmp_overview_docs/js/dagre-d3.js deleted file mode 100644 index aed4090..0000000 --- a/tmp_overview_docs/js/dagre-d3.js +++ /dev/null @@ -1,17572 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.dagreD3 = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0; -} - -},{}],14:[function(require,module,exports){ -module.exports = intersectNode; - -function intersectNode(node, point) { - return node.intersect(point); -} - -},{}],15:[function(require,module,exports){ -var intersectLine = require("./intersect-line"); - -module.exports = intersectPolygon; - -/* - * Returns the point ({x, y}) at which the point argument intersects with the - * node argument assuming that it has the shape specified by polygon. - */ -function intersectPolygon(node, polyPoints, point) { - var x1 = node.x; - var y1 = node.y; - - var intersections = []; - - var minX = Number.POSITIVE_INFINITY, - minY = Number.POSITIVE_INFINITY; - polyPoints.forEach(function(entry) { - minX = Math.min(minX, entry.x); - minY = Math.min(minY, entry.y); - }); - - var left = x1 - node.width / 2 - minX; - var top = y1 - node.height / 2 - minY; - - for (var i = 0; i < polyPoints.length; i++) { - var p1 = polyPoints[i]; - var p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0]; - var intersect = intersectLine(node, point, - {x: left + p1.x, y: top + p1.y}, {x: left + p2.x, y: top + p2.y}); - if (intersect) { - intersections.push(intersect); - } - } - - if (!intersections.length) { - console.log("NO INTERSECTION FOUND, RETURN NODE CENTER", node); - return node; - } - - if (intersections.length > 1) { - // More intersections, find the one nearest to edge end point - intersections.sort(function(p, q) { - var pdx = p.x - point.x, - pdy = p.y - point.y, - distp = Math.sqrt(pdx * pdx + pdy * pdy), - - qdx = q.x - point.x, - qdy = q.y - point.y, - distq = Math.sqrt(qdx * qdx + qdy * qdy); - - return (distp < distq) ? -1 : (distp === distq ? 0 : 1); - }); - } - return intersections[0]; -} - -},{"./intersect-line":13}],16:[function(require,module,exports){ -module.exports = intersectRect; - -function intersectRect(node, point) { - var x = node.x; - var y = node.y; - - // Rectangle intersection algorithm from: - // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes - var dx = point.x - x; - var dy = point.y - y; - var w = node.width / 2; - var h = node.height / 2; - - var sx, sy; - if (Math.abs(dy) * w > Math.abs(dx) * h) { - // Intersection is top or bottom of rect. - if (dy < 0) { - h = -h; - } - sx = dy === 0 ? 0 : h * dx / dy; - sy = h; - } else { - // Intersection is left or right of rect. - if (dx < 0) { - w = -w; - } - sx = w; - sy = dx === 0 ? 0 : w * dy / dx; - } - - return {x: x + sx, y: y + sy}; -} - -},{}],17:[function(require,module,exports){ -var util = require("../util"); - -module.exports = addHtmlLabel; - -function addHtmlLabel(root, node) { - var fo = root - .append("foreignObject") - .attr("width", "100000"); - - var div = fo - .append("xhtml:div"); - div.attr("xmlns", "http://www.w3.org/1999/xhtml"); - - var label = node.label; - switch(typeof label) { - case "function": - div.insert(label); - break; - case "object": - // Currently we assume this is a DOM object. - div.insert(function() { return label; }); - break; - default: div.html(label); - } - - util.applyStyle(div, node.labelStyle); - div.style("display", "inline-block"); - // Fix for firefox - div.style("white-space", "nowrap"); - - var client = div[0][0].getBoundingClientRect(); - fo - .attr("width", client.width) - .attr("height", client.height); - - return fo; -} - -},{"../util":27}],18:[function(require,module,exports){ -var addTextLabel = require("./add-text-label"), - addHtmlLabel = require("./add-html-label"), - addSVGLabel = require("./add-svg-label"); - -module.exports = addLabel; - -function addLabel(root, node, location) { - var label = node.label; - var labelSvg = root.append("g"); - - // Allow the label to be a string, a function that returns a DOM element, or - // a DOM element itself. - if (node.labelType === "svg") { - addSVGLabel(labelSvg, node); - } else if (typeof label !== "string" || node.labelType === "html") { - addHtmlLabel(labelSvg, node); - } else { - addTextLabel(labelSvg, node); - } - - var labelBBox = labelSvg.node().getBBox(); - var y; - switch(location) { - case "top": - y = (-node.height / 2); - break; - case "bottom": - y = (node.height / 2) - labelBBox.height; - break; - default: - y = (-labelBBox.height / 2); - } - labelSvg.attr("transform", - "translate(" + (-labelBBox.width / 2) + "," + y + ")"); - - return labelSvg; -} - -},{"./add-html-label":17,"./add-svg-label":19,"./add-text-label":20}],19:[function(require,module,exports){ -var util = require("../util"); - -module.exports = addSVGLabel; - -function addSVGLabel(root, node) { - var domNode = root; - - domNode.node().appendChild(node.label); - - util.applyStyle(domNode, node.labelStyle); - - return domNode; -} - -},{"../util":27}],20:[function(require,module,exports){ -var util = require("../util"); - -module.exports = addTextLabel; - -/* - * Attaches a text label to the specified root. Handles escape sequences. - */ -function addTextLabel(root, node) { - var domNode = root.append("text"); - - var lines = processEscapeSequences(node.label).split("\n"); - for (var i = 0; i < lines.length; i++) { - domNode - .append("tspan") - .attr("xml:space", "preserve") - .attr("dy", "1em") - .attr("x", "1") - .text(lines[i]); - } - - util.applyStyle(domNode, node.labelStyle); - - return domNode; -} - -function processEscapeSequences(text) { - var newText = "", - escaped = false, - ch; - for (var i = 0; i < text.length; ++i) { - ch = text[i]; - if (escaped) { - switch(ch) { - case "n": newText += "\n"; break; - default: newText += ch; - } - escaped = false; - } else if (ch === "\\") { - escaped = true; - } else { - newText += ch; - } - } - return newText; -} - -},{"../util":27}],21:[function(require,module,exports){ -/* global window */ - -var lodash; - -if (require) { - try { - lodash = require("lodash"); - } catch (e) {} -} - -if (!lodash) { - lodash = window._; -} - -module.exports = lodash; - -},{"lodash":79}],22:[function(require,module,exports){ -"use strict"; - -var util = require("./util"), - d3 = require("./d3"); - -module.exports = positionClusters; - -function positionClusters(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(v) { - var node = g.node(v); - return "translate(" + node.x + "," + node.y + ")"; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); - - util.applyTransition(created.selectAll("rect"), g) - .attr("width", function(v) { return g.node(v).width; }) - .attr("height", function(v) { return g.node(v).height; }) - .attr("x", function(v) { - var node = g.node(v); - return -node.width / 2; - }) - .attr("y", function(v) { - var node = g.node(v); - return -node.height / 2; - }); - -} - -},{"./d3":7,"./util":27}],23:[function(require,module,exports){ -"use strict"; - -var util = require("./util"), - d3 = require("./d3"), - _ = require("./lodash"); - -module.exports = positionEdgeLabels; - -function positionEdgeLabels(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(e) { - var edge = g.edge(e); - return _.has(edge, "x") ? "translate(" + edge.x + "," + edge.y + ")" : ""; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); -} - -},{"./d3":7,"./lodash":21,"./util":27}],24:[function(require,module,exports){ -"use strict"; - -var util = require("./util"), - d3 = require("./d3"); - -module.exports = positionNodes; - -function positionNodes(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(v) { - var node = g.node(v); - return "translate(" + node.x + "," + node.y + ")"; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); -} - -},{"./d3":7,"./util":27}],25:[function(require,module,exports){ -var _ = require("./lodash"), - layout = require("./dagre").layout; - -module.exports = render; - -// This design is based on http://bost.ocks.org/mike/chart/. -function render() { - var createNodes = require("./create-nodes"), - createClusters = require("./create-clusters"), - createEdgeLabels = require("./create-edge-labels"), - createEdgePaths = require("./create-edge-paths"), - positionNodes = require("./position-nodes"), - positionEdgeLabels = require("./position-edge-labels"), - positionClusters = require("./position-clusters"), - shapes = require("./shapes"), - arrows = require("./arrows"); - - var fn = function(svg, g) { - preProcessGraph(g); - - var outputGroup = createOrSelectGroup(svg, "output"), - clustersGroup = createOrSelectGroup(outputGroup, "clusters"), - edgePathsGroup = createOrSelectGroup(outputGroup, "edgePaths"), - edgeLabels = createEdgeLabels(createOrSelectGroup(outputGroup, "edgeLabels"), g), - nodes = createNodes(createOrSelectGroup(outputGroup, "nodes"), g, shapes); - - layout(g); - - positionNodes(nodes, g); - positionEdgeLabels(edgeLabels, g); - createEdgePaths(edgePathsGroup, g, arrows); - - var clusters = createClusters(clustersGroup, g); - positionClusters(clusters, g); - - postProcessGraph(g); - }; - - fn.createNodes = function(value) { - if (!arguments.length) return createNodes; - createNodes = value; - return fn; - }; - - fn.createClusters = function(value) { - if (!arguments.length) return createClusters; - createClusters = value; - return fn; - }; - - fn.createEdgeLabels = function(value) { - if (!arguments.length) return createEdgeLabels; - createEdgeLabels = value; - return fn; - }; - - fn.createEdgePaths = function(value) { - if (!arguments.length) return createEdgePaths; - createEdgePaths = value; - return fn; - }; - - fn.shapes = function(value) { - if (!arguments.length) return shapes; - shapes = value; - return fn; - }; - - fn.arrows = function(value) { - if (!arguments.length) return arrows; - arrows = value; - return fn; - }; - - return fn; -} - -var NODE_DEFAULT_ATTRS = { - paddingLeft: 10, - paddingRight: 10, - paddingTop: 10, - paddingBottom: 10, - rx: 0, - ry: 0, - shape: "rect" -}; - -var EDGE_DEFAULT_ATTRS = { - arrowhead: "normal", - lineInterpolate: "linear" -}; - -function preProcessGraph(g) { - g.nodes().forEach(function(v) { - var node = g.node(v); - if (!_.has(node, "label") && !g.children(v).length) { node.label = v; } - - if (_.has(node, "paddingX")) { - _.defaults(node, { - paddingLeft: node.paddingX, - paddingRight: node.paddingX - }); - } - - if (_.has(node, "paddingY")) { - _.defaults(node, { - paddingTop: node.paddingY, - paddingBottom: node.paddingY - }); - } - - if (_.has(node, "padding")) { - _.defaults(node, { - paddingLeft: node.padding, - paddingRight: node.padding, - paddingTop: node.padding, - paddingBottom: node.padding - }); - } - - _.defaults(node, NODE_DEFAULT_ATTRS); - - _.each(["paddingLeft", "paddingRight", "paddingTop", "paddingBottom"], function(k) { - node[k] = Number(node[k]); - }); - - // Save dimensions for restore during post-processing - if (_.has(node, "width")) { node._prevWidth = node.width; } - if (_.has(node, "height")) { node._prevHeight = node.height; } - }); - - g.edges().forEach(function(e) { - var edge = g.edge(e); - if (!_.has(edge, "label")) { edge.label = ""; } - _.defaults(edge, EDGE_DEFAULT_ATTRS); - }); -} - -function postProcessGraph(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - - // Restore original dimensions - if (_.has(node, "_prevWidth")) { - node.width = node._prevWidth; - } else { - delete node.width; - } - - if (_.has(node, "_prevHeight")) { - node.height = node._prevHeight; - } else { - delete node.height; - } - - delete node._prevWidth; - delete node._prevHeight; - }); -} - -function createOrSelectGroup(root, name) { - var selection = root.select("g." + name); - if (selection.empty()) { - selection = root.append("g").attr("class", name); - } - return selection; -} - -},{"./arrows":2,"./create-clusters":3,"./create-edge-labels":4,"./create-edge-paths":5,"./create-nodes":6,"./dagre":8,"./lodash":21,"./position-clusters":22,"./position-edge-labels":23,"./position-nodes":24,"./shapes":26}],26:[function(require,module,exports){ -"use strict"; - -var intersectRect = require("./intersect/intersect-rect"), - intersectEllipse = require("./intersect/intersect-ellipse"), - intersectCircle = require("./intersect/intersect-circle"), - intersectPolygon = require("./intersect/intersect-polygon"); - -module.exports = { - rect: rect, - ellipse: ellipse, - circle: circle, - diamond: diamond -}; - -function rect(parent, bbox, node) { - var shapeSvg = parent.insert("rect", ":first-child") - .attr("rx", node.rx) - .attr("ry", node.ry) - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("width", bbox.width) - .attr("height", bbox.height); - - node.intersect = function(point) { - return intersectRect(node, point); - }; - - return shapeSvg; -} - -function ellipse(parent, bbox, node) { - var rx = bbox.width / 2, - ry = bbox.height / 2, - shapeSvg = parent.insert("ellipse", ":first-child") - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("rx", rx) - .attr("ry", ry); - - node.intersect = function(point) { - return intersectEllipse(node, rx, ry, point); - }; - - return shapeSvg; -} - -function circle(parent, bbox, node) { - var r = Math.max(bbox.width, bbox.height) / 2, - shapeSvg = parent.insert("circle", ":first-child") - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("r", r); - - node.intersect = function(point) { - return intersectCircle(node, r, point); - }; - - return shapeSvg; -} - -// Circumscribe an ellipse for the bounding box with a diamond shape. I derived -// the function to calculate the diamond shape from: -// http://mathforum.org/kb/message.jspa?messageID=3750236 -function diamond(parent, bbox, node) { - var w = (bbox.width * Math.SQRT2) / 2, - h = (bbox.height * Math.SQRT2) / 2, - points = [ - { x: 0, y: -h }, - { x: -w, y: 0 }, - { x: 0, y: h }, - { x: w, y: 0 } - ], - shapeSvg = parent.insert("polygon", ":first-child") - .attr("points", points.map(function(p) { return p.x + "," + p.y; }).join(" ")); - - node.intersect = function(p) { - return intersectPolygon(node, points, p); - }; - - return shapeSvg; -} - -},{"./intersect/intersect-circle":11,"./intersect/intersect-ellipse":12,"./intersect/intersect-polygon":15,"./intersect/intersect-rect":16}],27:[function(require,module,exports){ -var _ = require("./lodash"); - -// Public utility functions -module.exports = { - isSubgraph: isSubgraph, - edgeToId: edgeToId, - applyStyle: applyStyle, - applyClass: applyClass, - applyTransition: applyTransition -}; - -/* - * Returns true if the specified node in the graph is a subgraph node. A - * subgraph node is one that contains other nodes. - */ -function isSubgraph(g, v) { - return !!g.children(v).length; -} - -function edgeToId(e) { - return escapeId(e.v) + ":" + escapeId(e.w) + ":" + escapeId(e.name); -} - -var ID_DELIM = /:/g; -function escapeId(str) { - return str ? String(str).replace(ID_DELIM, "\\:") : ""; -} - -function applyStyle(dom, styleFn) { - if (styleFn) { - dom.attr("style", styleFn); - } -} - -function applyClass(dom, classFn, otherClasses) { - if (classFn) { - dom - .attr("class", classFn) - .attr("class", otherClasses + " " + dom.attr("class")); - } -} - -function applyTransition(selection, g) { - var graph = g.graph(); - - if (_.isPlainObject(graph)) { - var transition = graph.transition; - if (_.isFunction(transition)) { - return transition(selection); - } - } - - return selection; -} - -},{"./lodash":21}],28:[function(require,module,exports){ -module.exports = "0.4.17"; - -},{}],29:[function(require,module,exports){ -/* -Copyright (c) 2012-2014 Chris Pettitt - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -module.exports = { - graphlib: require("./lib/graphlib"), - - layout: require("./lib/layout"), - debug: require("./lib/debug"), - util: { - time: require("./lib/util").time, - notime: require("./lib/util").notime - }, - version: require("./lib/version") -}; - -},{"./lib/debug":34,"./lib/graphlib":35,"./lib/layout":37,"./lib/util":57,"./lib/version":58}],30:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - greedyFAS = require("./greedy-fas"); - -module.exports = { - run: run, - undo: undo -}; - -function run(g) { - var fas = (g.graph().acyclicer === "greedy" - ? greedyFAS(g, weightFn(g)) - : dfsFAS(g)); - _.each(fas, function(e) { - var label = g.edge(e); - g.removeEdge(e); - label.forwardName = e.name; - label.reversed = true; - g.setEdge(e.w, e.v, label, _.uniqueId("rev")); - }); - - function weightFn(g) { - return function(e) { - return g.edge(e).weight; - }; - } -} - -function dfsFAS(g) { - var fas = [], - stack = {}, - visited = {}; - - function dfs(v) { - if (_.has(visited, v)) { - return; - } - visited[v] = true; - stack[v] = true; - _.each(g.outEdges(v), function(e) { - if (_.has(stack, e.w)) { - fas.push(e); - } else { - dfs(e.w); - } - }); - delete stack[v]; - } - - _.each(g.nodes(), dfs); - return fas; -} - -function undo(g) { - _.each(g.edges(), function(e) { - var label = g.edge(e); - if (label.reversed) { - g.removeEdge(e); - - var forwardName = label.forwardName; - delete label.reversed; - delete label.forwardName; - g.setEdge(e.w, e.v, label, forwardName); - } - }); -} - -},{"./greedy-fas":36,"./lodash":38}],31:[function(require,module,exports){ -var _ = require("./lodash"), - util = require("./util"); - -module.exports = addBorderSegments; - -function addBorderSegments(g) { - function dfs(v) { - var children = g.children(v), - node = g.node(v); - if (children.length) { - _.each(children, dfs); - } - - if (_.has(node, "minRank")) { - node.borderLeft = []; - node.borderRight = []; - for (var rank = node.minRank, maxRank = node.maxRank + 1; - rank < maxRank; - ++rank) { - addBorderNode(g, "borderLeft", "_bl", v, node, rank); - addBorderNode(g, "borderRight", "_br", v, node, rank); - } - } - } - - _.each(g.children(), dfs); -} - -function addBorderNode(g, prop, prefix, sg, sgNode, rank) { - var label = { width: 0, height: 0, rank: rank, borderType: prop }, - prev = sgNode[prop][rank - 1], - curr = util.addDummyNode(g, "border", label, prefix); - sgNode[prop][rank] = curr; - g.setParent(curr, sg); - if (prev) { - g.setEdge(prev, curr, { weight: 1 }); - } -} - -},{"./lodash":38,"./util":57}],32:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"); - -module.exports = { - adjust: adjust, - undo: undo -}; - -function adjust(g) { - var rankDir = g.graph().rankdir.toLowerCase(); - if (rankDir === "lr" || rankDir === "rl") { - swapWidthHeight(g); - } -} - -function undo(g) { - var rankDir = g.graph().rankdir.toLowerCase(); - if (rankDir === "bt" || rankDir === "rl") { - reverseY(g); - } - - if (rankDir === "lr" || rankDir === "rl") { - swapXY(g); - swapWidthHeight(g); - } -} - -function swapWidthHeight(g) { - _.each(g.nodes(), function(v) { swapWidthHeightOne(g.node(v)); }); - _.each(g.edges(), function(e) { swapWidthHeightOne(g.edge(e)); }); -} - -function swapWidthHeightOne(attrs) { - var w = attrs.width; - attrs.width = attrs.height; - attrs.height = w; -} - -function reverseY(g) { - _.each(g.nodes(), function(v) { reverseYOne(g.node(v)); }); - - _.each(g.edges(), function(e) { - var edge = g.edge(e); - _.each(edge.points, reverseYOne); - if (_.has(edge, "y")) { - reverseYOne(edge); - } - }); -} - -function reverseYOne(attrs) { - attrs.y = -attrs.y; -} - -function swapXY(g) { - _.each(g.nodes(), function(v) { swapXYOne(g.node(v)); }); - - _.each(g.edges(), function(e) { - var edge = g.edge(e); - _.each(edge.points, swapXYOne); - if (_.has(edge, "x")) { - swapXYOne(edge); - } - }); -} - -function swapXYOne(attrs) { - var x = attrs.x; - attrs.x = attrs.y; - attrs.y = x; -} - -},{"./lodash":38}],33:[function(require,module,exports){ -/* - * Simple doubly linked list implementation derived from Cormen, et al., - * "Introduction to Algorithms". - */ - -module.exports = List; - -function List() { - var sentinel = {}; - sentinel._next = sentinel._prev = sentinel; - this._sentinel = sentinel; -} - -List.prototype.dequeue = function() { - var sentinel = this._sentinel, - entry = sentinel._prev; - if (entry !== sentinel) { - unlink(entry); - return entry; - } -}; - -List.prototype.enqueue = function(entry) { - var sentinel = this._sentinel; - if (entry._prev && entry._next) { - unlink(entry); - } - entry._next = sentinel._next; - sentinel._next._prev = entry; - sentinel._next = entry; - entry._prev = sentinel; -}; - -List.prototype.toString = function() { - var strs = [], - sentinel = this._sentinel, - curr = sentinel._prev; - while (curr !== sentinel) { - strs.push(JSON.stringify(curr, filterOutLinks)); - curr = curr._prev; - } - return "[" + strs.join(", ") + "]"; -}; - -function unlink(entry) { - entry._prev._next = entry._next; - entry._next._prev = entry._prev; - delete entry._next; - delete entry._prev; -} - -function filterOutLinks(k, v) { - if (k !== "_next" && k !== "_prev") { - return v; - } -} - -},{}],34:[function(require,module,exports){ -var _ = require("./lodash"), - util = require("./util"), - Graph = require("./graphlib").Graph; - -module.exports = { - debugOrdering: debugOrdering -}; - -/* istanbul ignore next */ -function debugOrdering(g) { - var layerMatrix = util.buildLayerMatrix(g); - - var h = new Graph({ compound: true, multigraph: true }).setGraph({}); - - _.each(g.nodes(), function(v) { - h.setNode(v, { label: v }); - h.setParent(v, "layer" + g.node(v).rank); - }); - - _.each(g.edges(), function(e) { - h.setEdge(e.v, e.w, {}, e.name); - }); - - _.each(layerMatrix, function(layer, i) { - var layerV = "layer" + i; - h.setNode(layerV, { rank: "same" }); - _.reduce(layer, function(u, v) { - h.setEdge(u, v, { style: "invis" }); - return v; - }); - }); - - return h; -} - -},{"./graphlib":35,"./lodash":38,"./util":57}],35:[function(require,module,exports){ -arguments[4][9][0].apply(exports,arguments) -},{"dup":9,"graphlib":59}],36:[function(require,module,exports){ -var _ = require("./lodash"), - Graph = require("./graphlib").Graph, - List = require("./data/list"); - -/* - * A greedy heuristic for finding a feedback arc set for a graph. A feedback - * arc set is a set of edges that can be removed to make a graph acyclic. - * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and - * effective heuristic for the feedback arc set problem." This implementation - * adjusts that from the paper to allow for weighted edges. - */ -module.exports = greedyFAS; - -var DEFAULT_WEIGHT_FN = _.constant(1); - -function greedyFAS(g, weightFn) { - if (g.nodeCount() <= 1) { - return []; - } - var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN); - var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx); - - // Expand multi-edges - return _.flatten(_.map(results, function(e) { - return g.outEdges(e.v, e.w); - }), true); -} - -function doGreedyFAS(g, buckets, zeroIdx) { - var results = [], - sources = buckets[buckets.length - 1], - sinks = buckets[0]; - - var entry; - while (g.nodeCount()) { - while ((entry = sinks.dequeue())) { removeNode(g, buckets, zeroIdx, entry); } - while ((entry = sources.dequeue())) { removeNode(g, buckets, zeroIdx, entry); } - if (g.nodeCount()) { - for (var i = buckets.length - 2; i > 0; --i) { - entry = buckets[i].dequeue(); - if (entry) { - results = results.concat(removeNode(g, buckets, zeroIdx, entry, true)); - break; - } - } - } - } - - return results; -} - -function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) { - var results = collectPredecessors ? [] : undefined; - - _.each(g.inEdges(entry.v), function(edge) { - var weight = g.edge(edge), - uEntry = g.node(edge.v); - - if (collectPredecessors) { - results.push({ v: edge.v, w: edge.w }); - } - - uEntry.out -= weight; - assignBucket(buckets, zeroIdx, uEntry); - }); - - _.each(g.outEdges(entry.v), function(edge) { - var weight = g.edge(edge), - w = edge.w, - wEntry = g.node(w); - wEntry["in"] -= weight; - assignBucket(buckets, zeroIdx, wEntry); - }); - - g.removeNode(entry.v); - - return results; -} - -function buildState(g, weightFn) { - var fasGraph = new Graph(), - maxIn = 0, - maxOut = 0; - - _.each(g.nodes(), function(v) { - fasGraph.setNode(v, { v: v, "in": 0, out: 0 }); - }); - - // Aggregate weights on nodes, but also sum the weights across multi-edges - // into a single edge for the fasGraph. - _.each(g.edges(), function(e) { - var prevWeight = fasGraph.edge(e.v, e.w) || 0, - weight = weightFn(e), - edgeWeight = prevWeight + weight; - fasGraph.setEdge(e.v, e.w, edgeWeight); - maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight); - maxIn = Math.max(maxIn, fasGraph.node(e.w)["in"] += weight); - }); - - var buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); }); - var zeroIdx = maxIn + 1; - - _.each(fasGraph.nodes(), function(v) { - assignBucket(buckets, zeroIdx, fasGraph.node(v)); - }); - - return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx }; -} - -function assignBucket(buckets, zeroIdx, entry) { - if (!entry.out) { - buckets[0].enqueue(entry); - } else if (!entry["in"]) { - buckets[buckets.length - 1].enqueue(entry); - } else { - buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry); - } -} - -},{"./data/list":33,"./graphlib":35,"./lodash":38}],37:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - acyclic = require("./acyclic"), - normalize = require("./normalize"), - rank = require("./rank"), - normalizeRanks = require("./util").normalizeRanks, - parentDummyChains = require("./parent-dummy-chains"), - removeEmptyRanks = require("./util").removeEmptyRanks, - nestingGraph = require("./nesting-graph"), - addBorderSegments = require("./add-border-segments"), - coordinateSystem = require("./coordinate-system"), - order = require("./order"), - position = require("./position"), - util = require("./util"), - Graph = require("./graphlib").Graph; - -module.exports = layout; - -function layout(g, opts) { - var time = opts && opts.debugTiming ? util.time : util.notime; - time("layout", function() { - var layoutGraph = time(" buildLayoutGraph", - function() { return buildLayoutGraph(g); }); - time(" runLayout", function() { runLayout(layoutGraph, time); }); - time(" updateInputGraph", function() { updateInputGraph(g, layoutGraph); }); - }); -} - -function runLayout(g, time) { - time(" makeSpaceForEdgeLabels", function() { makeSpaceForEdgeLabels(g); }); - time(" removeSelfEdges", function() { removeSelfEdges(g); }); - time(" acyclic", function() { acyclic.run(g); }); - time(" nestingGraph.run", function() { nestingGraph.run(g); }); - time(" rank", function() { rank(util.asNonCompoundGraph(g)); }); - time(" injectEdgeLabelProxies", function() { injectEdgeLabelProxies(g); }); - time(" removeEmptyRanks", function() { removeEmptyRanks(g); }); - time(" nestingGraph.cleanup", function() { nestingGraph.cleanup(g); }); - time(" normalizeRanks", function() { normalizeRanks(g); }); - time(" assignRankMinMax", function() { assignRankMinMax(g); }); - time(" removeEdgeLabelProxies", function() { removeEdgeLabelProxies(g); }); - time(" normalize.run", function() { normalize.run(g); }); - time(" parentDummyChains", function() { parentDummyChains(g); }); - time(" addBorderSegments", function() { addBorderSegments(g); }); - time(" order", function() { order(g); }); - time(" insertSelfEdges", function() { insertSelfEdges(g); }); - time(" adjustCoordinateSystem", function() { coordinateSystem.adjust(g); }); - time(" position", function() { position(g); }); - time(" positionSelfEdges", function() { positionSelfEdges(g); }); - time(" removeBorderNodes", function() { removeBorderNodes(g); }); - time(" normalize.undo", function() { normalize.undo(g); }); - time(" fixupEdgeLabelCoords", function() { fixupEdgeLabelCoords(g); }); - time(" undoCoordinateSystem", function() { coordinateSystem.undo(g); }); - time(" translateGraph", function() { translateGraph(g); }); - time(" assignNodeIntersects", function() { assignNodeIntersects(g); }); - time(" reversePoints", function() { reversePointsForReversedEdges(g); }); - time(" acyclic.undo", function() { acyclic.undo(g); }); -} - -/* - * Copies final layout information from the layout graph back to the input - * graph. This process only copies whitelisted attributes from the layout graph - * to the input graph, so it serves as a good place to determine what - * attributes can influence layout. - */ -function updateInputGraph(inputGraph, layoutGraph) { - _.each(inputGraph.nodes(), function(v) { - var inputLabel = inputGraph.node(v), - layoutLabel = layoutGraph.node(v); - - if (inputLabel) { - inputLabel.x = layoutLabel.x; - inputLabel.y = layoutLabel.y; - - if (layoutGraph.children(v).length) { - inputLabel.width = layoutLabel.width; - inputLabel.height = layoutLabel.height; - } - } - }); - - _.each(inputGraph.edges(), function(e) { - var inputLabel = inputGraph.edge(e), - layoutLabel = layoutGraph.edge(e); - - inputLabel.points = layoutLabel.points; - if (_.has(layoutLabel, "x")) { - inputLabel.x = layoutLabel.x; - inputLabel.y = layoutLabel.y; - } - }); - - inputGraph.graph().width = layoutGraph.graph().width; - inputGraph.graph().height = layoutGraph.graph().height; -} - -var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"], - graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" }, - graphAttrs = ["acyclicer", "ranker", "rankdir", "align"], - nodeNumAttrs = ["width", "height"], - nodeDefaults = { width: 0, height: 0 }, - edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"], - edgeDefaults = { - minlen: 1, weight: 1, width: 0, height: 0, - labeloffset: 10, labelpos: "r" - }, - edgeAttrs = ["labelpos"]; - -/* - * Constructs a new graph from the input graph, which can be used for layout. - * This process copies only whitelisted attributes from the input graph to the - * layout graph. Thus this function serves as a good place to determine what - * attributes can influence layout. - */ -function buildLayoutGraph(inputGraph) { - var g = new Graph({ multigraph: true, compound: true }), - graph = canonicalize(inputGraph.graph()); - - g.setGraph(_.merge({}, - graphDefaults, - selectNumberAttrs(graph, graphNumAttrs), - _.pick(graph, graphAttrs))); - - _.each(inputGraph.nodes(), function(v) { - var node = canonicalize(inputGraph.node(v)); - g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults)); - g.setParent(v, inputGraph.parent(v)); - }); - - _.each(inputGraph.edges(), function(e) { - var edge = canonicalize(inputGraph.edge(e)); - g.setEdge(e, _.merge({}, - edgeDefaults, - selectNumberAttrs(edge, edgeNumAttrs), - _.pick(edge, edgeAttrs))); - }); - - return g; -} - -/* - * This idea comes from the Gansner paper: to account for edge labels in our - * layout we split each rank in half by doubling minlen and halving ranksep. - * Then we can place labels at these mid-points between nodes. - * - * We also add some minimal padding to the width to push the label for the edge - * away from the edge itself a bit. - */ -function makeSpaceForEdgeLabels(g) { - var graph = g.graph(); - graph.ranksep /= 2; - _.each(g.edges(), function(e) { - var edge = g.edge(e); - edge.minlen *= 2; - if (edge.labelpos.toLowerCase() !== "c") { - if (graph.rankdir === "TB" || graph.rankdir === "BT") { - edge.width += edge.labeloffset; - } else { - edge.height += edge.labeloffset; - } - } - }); -} - -/* - * Creates temporary dummy nodes that capture the rank in which each edge's - * label is going to, if it has one of non-zero width and height. We do this - * so that we can safely remove empty ranks while preserving balance for the - * label's position. - */ -function injectEdgeLabelProxies(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.width && edge.height) { - var v = g.node(e.v), - w = g.node(e.w), - label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e }; - util.addDummyNode(g, "edge-proxy", label, "_ep"); - } - }); -} - -function assignRankMinMax(g) { - var maxRank = 0; - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.borderTop) { - node.minRank = g.node(node.borderTop).rank; - node.maxRank = g.node(node.borderBottom).rank; - maxRank = _.max(maxRank, node.maxRank); - } - }); - g.graph().maxRank = maxRank; -} - -function removeEdgeLabelProxies(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.dummy === "edge-proxy") { - g.edge(node.e).labelRank = node.rank; - g.removeNode(v); - } - }); -} - -function translateGraph(g) { - var minX = Number.POSITIVE_INFINITY, - maxX = 0, - minY = Number.POSITIVE_INFINITY, - maxY = 0, - graphLabel = g.graph(), - marginX = graphLabel.marginx || 0, - marginY = graphLabel.marginy || 0; - - function getExtremes(attrs) { - var x = attrs.x, - y = attrs.y, - w = attrs.width, - h = attrs.height; - minX = Math.min(minX, x - w / 2); - maxX = Math.max(maxX, x + w / 2); - minY = Math.min(minY, y - h / 2); - maxY = Math.max(maxY, y + h / 2); - } - - _.each(g.nodes(), function(v) { getExtremes(g.node(v)); }); - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (_.has(edge, "x")) { - getExtremes(edge); - } - }); - - minX -= marginX; - minY -= marginY; - - _.each(g.nodes(), function(v) { - var node = g.node(v); - node.x -= minX; - node.y -= minY; - }); - - _.each(g.edges(), function(e) { - var edge = g.edge(e); - _.each(edge.points, function(p) { - p.x -= minX; - p.y -= minY; - }); - if (_.has(edge, "x")) { edge.x -= minX; } - if (_.has(edge, "y")) { edge.y -= minY; } - }); - - graphLabel.width = maxX - minX + marginX; - graphLabel.height = maxY - minY + marginY; -} - -function assignNodeIntersects(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e), - nodeV = g.node(e.v), - nodeW = g.node(e.w), - p1, p2; - if (!edge.points) { - edge.points = []; - p1 = nodeW; - p2 = nodeV; - } else { - p1 = edge.points[0]; - p2 = edge.points[edge.points.length - 1]; - } - edge.points.unshift(util.intersectRect(nodeV, p1)); - edge.points.push(util.intersectRect(nodeW, p2)); - }); -} - -function fixupEdgeLabelCoords(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (_.has(edge, "x")) { - if (edge.labelpos === "l" || edge.labelpos === "r") { - edge.width -= edge.labeloffset; - } - switch (edge.labelpos) { - case "l": edge.x -= edge.width / 2 + edge.labeloffset; break; - case "r": edge.x += edge.width / 2 + edge.labeloffset; break; - } - } - }); -} - -function reversePointsForReversedEdges(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.reversed) { - edge.points.reverse(); - } - }); -} - -function removeBorderNodes(g) { - _.each(g.nodes(), function(v) { - if (g.children(v).length) { - var node = g.node(v), - t = g.node(node.borderTop), - b = g.node(node.borderBottom), - l = g.node(_.last(node.borderLeft)), - r = g.node(_.last(node.borderRight)); - - node.width = Math.abs(r.x - l.x); - node.height = Math.abs(b.y - t.y); - node.x = l.x + node.width / 2; - node.y = t.y + node.height / 2; - } - }); - - _.each(g.nodes(), function(v) { - if (g.node(v).dummy === "border") { - g.removeNode(v); - } - }); -} - -function removeSelfEdges(g) { - _.each(g.edges(), function(e) { - if (e.v === e.w) { - var node = g.node(e.v); - if (!node.selfEdges) { - node.selfEdges = []; - } - node.selfEdges.push({ e: e, label: g.edge(e) }); - g.removeEdge(e); - } - }); -} - -function insertSelfEdges(g) { - var layers = util.buildLayerMatrix(g); - _.each(layers, function(layer) { - var orderShift = 0; - _.each(layer, function(v, i) { - var node = g.node(v); - node.order = i + orderShift; - _.each(node.selfEdges, function(selfEdge) { - util.addDummyNode(g, "selfedge", { - width: selfEdge.label.width, - height: selfEdge.label.height, - rank: node.rank, - order: i + (++orderShift), - e: selfEdge.e, - label: selfEdge.label - }, "_se"); - }); - delete node.selfEdges; - }); - }); -} - -function positionSelfEdges(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.dummy === "selfedge") { - var selfNode = g.node(node.e.v), - x = selfNode.x + selfNode.width / 2, - y = selfNode.y, - dx = node.x - x, - dy = selfNode.height / 2; - g.setEdge(node.e, node.label); - g.removeNode(v); - node.label.points = [ - { x: x + 2 * dx / 3, y: y - dy }, - { x: x + 5 * dx / 6, y: y - dy }, - { x: x + dx , y: y }, - { x: x + 5 * dx / 6, y: y + dy }, - { x: x + 2 * dx / 3, y: y + dy }, - ]; - node.label.x = node.x; - node.label.y = node.y; - } - }); -} - -function selectNumberAttrs(obj, attrs) { - return _.mapValues(_.pick(obj, attrs), Number); -} - -function canonicalize(attrs) { - var newAttrs = {}; - _.each(attrs, function(v, k) { - newAttrs[k.toLowerCase()] = v; - }); - return newAttrs; -} - -},{"./acyclic":30,"./add-border-segments":31,"./coordinate-system":32,"./graphlib":35,"./lodash":38,"./nesting-graph":39,"./normalize":40,"./order":45,"./parent-dummy-chains":50,"./position":52,"./rank":54,"./util":57}],38:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21,"lodash":79}],39:[function(require,module,exports){ -var _ = require("./lodash"), - util = require("./util"); - -module.exports = { - run: run, - cleanup: cleanup -}; - -/* - * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs, - * adds appropriate edges to ensure that all cluster nodes are placed between - * these boundries, and ensures that the graph is connected. - * - * In addition we ensure, through the use of the minlen property, that nodes - * and subgraph border nodes to not end up on the same rank. - * - * Preconditions: - * - * 1. Input graph is a DAG - * 2. Nodes in the input graph has a minlen attribute - * - * Postconditions: - * - * 1. Input graph is connected. - * 2. Dummy nodes are added for the tops and bottoms of subgraphs. - * 3. The minlen attribute for nodes is adjusted to ensure nodes do not - * get placed on the same rank as subgraph border nodes. - * - * The nesting graph idea comes from Sander, "Layout of Compound Directed - * Graphs." - */ -function run(g) { - var root = util.addDummyNode(g, "root", {}, "_root"), - depths = treeDepths(g), - height = _.max(depths) - 1, - nodeSep = 2 * height + 1; - - g.graph().nestingRoot = root; - - // Multiply minlen by nodeSep to align nodes on non-border ranks. - _.each(g.edges(), function(e) { g.edge(e).minlen *= nodeSep; }); - - // Calculate a weight that is sufficient to keep subgraphs vertically compact - var weight = sumWeights(g) + 1; - - // Create border nodes and link them up - _.each(g.children(), function(child) { - dfs(g, root, nodeSep, weight, height, depths, child); - }); - - // Save the multiplier for node layers for later removal of empty border - // layers. - g.graph().nodeRankFactor = nodeSep; -} - -function dfs(g, root, nodeSep, weight, height, depths, v) { - var children = g.children(v); - if (!children.length) { - if (v !== root) { - g.setEdge(root, v, { weight: 0, minlen: nodeSep }); - } - return; - } - - var top = util.addBorderNode(g, "_bt"), - bottom = util.addBorderNode(g, "_bb"), - label = g.node(v); - - g.setParent(top, v); - label.borderTop = top; - g.setParent(bottom, v); - label.borderBottom = bottom; - - _.each(children, function(child) { - dfs(g, root, nodeSep, weight, height, depths, child); - - var childNode = g.node(child), - childTop = childNode.borderTop ? childNode.borderTop : child, - childBottom = childNode.borderBottom ? childNode.borderBottom : child, - thisWeight = childNode.borderTop ? weight : 2 * weight, - minlen = childTop !== childBottom ? 1 : height - depths[v] + 1; - - g.setEdge(top, childTop, { - weight: thisWeight, - minlen: minlen, - nestingEdge: true - }); - - g.setEdge(childBottom, bottom, { - weight: thisWeight, - minlen: minlen, - nestingEdge: true - }); - }); - - if (!g.parent(v)) { - g.setEdge(root, top, { weight: 0, minlen: height + depths[v] }); - } -} - -function treeDepths(g) { - var depths = {}; - function dfs(v, depth) { - var children = g.children(v); - if (children && children.length) { - _.each(children, function(child) { - dfs(child, depth + 1); - }); - } - depths[v] = depth; - } - _.each(g.children(), function(v) { dfs(v, 1); }); - return depths; -} - -function sumWeights(g) { - return _.reduce(g.edges(), function(acc, e) { - return acc + g.edge(e).weight; - }, 0); -} - -function cleanup(g) { - var graphLabel = g.graph(); - g.removeNode(graphLabel.nestingRoot); - delete graphLabel.nestingRoot; - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.nestingEdge) { - g.removeEdge(e); - } - }); -} - -},{"./lodash":38,"./util":57}],40:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - util = require("./util"); - -module.exports = { - run: run, - undo: undo -}; - -/* - * Breaks any long edges in the graph into short segments that span 1 layer - * each. This operation is undoable with the denormalize function. - * - * Pre-conditions: - * - * 1. The input graph is a DAG. - * 2. Each node in the graph has a "rank" property. - * - * Post-condition: - * - * 1. All edges in the graph have a length of 1. - * 2. Dummy nodes are added where edges have been split into segments. - * 3. The graph is augmented with a "dummyChains" attribute which contains - * the first dummy in each chain of dummy nodes produced. - */ -function run(g) { - g.graph().dummyChains = []; - _.each(g.edges(), function(edge) { normalizeEdge(g, edge); }); -} - -function normalizeEdge(g, e) { - var v = e.v, - vRank = g.node(v).rank, - w = e.w, - wRank = g.node(w).rank, - name = e.name, - edgeLabel = g.edge(e), - labelRank = edgeLabel.labelRank; - - if (wRank === vRank + 1) return; - - g.removeEdge(e); - - var dummy, attrs, i; - for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) { - edgeLabel.points = []; - attrs = { - width: 0, height: 0, - edgeLabel: edgeLabel, edgeObj: e, - rank: vRank - }; - dummy = util.addDummyNode(g, "edge", attrs, "_d"); - if (vRank === labelRank) { - attrs.width = edgeLabel.width; - attrs.height = edgeLabel.height; - attrs.dummy = "edge-label"; - attrs.labelpos = edgeLabel.labelpos; - } - g.setEdge(v, dummy, { weight: edgeLabel.weight }, name); - if (i === 0) { - g.graph().dummyChains.push(dummy); - } - v = dummy; - } - - g.setEdge(v, w, { weight: edgeLabel.weight }, name); -} - -function undo(g) { - _.each(g.graph().dummyChains, function(v) { - var node = g.node(v), - origLabel = node.edgeLabel, - w; - g.setEdge(node.edgeObj, origLabel); - while (node.dummy) { - w = g.successors(v)[0]; - g.removeNode(v); - origLabel.points.push({ x: node.x, y: node.y }); - if (node.dummy === "edge-label") { - origLabel.x = node.x; - origLabel.y = node.y; - origLabel.width = node.width; - origLabel.height = node.height; - } - v = w; - node = g.node(v); - } - }); -} - -},{"./lodash":38,"./util":57}],41:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = addSubgraphConstraints; - -function addSubgraphConstraints(g, cg, vs) { - var prev = {}, - rootPrev; - - _.each(vs, function(v) { - var child = g.parent(v), - parent, - prevChild; - while (child) { - parent = g.parent(child); - if (parent) { - prevChild = prev[parent]; - prev[parent] = child; - } else { - prevChild = rootPrev; - rootPrev = child; - } - if (prevChild && prevChild !== child) { - cg.setEdge(prevChild, child); - return; - } - child = parent; - } - }); - - /* - function dfs(v) { - var children = v ? g.children(v) : g.children(); - if (children.length) { - var min = Number.POSITIVE_INFINITY, - subgraphs = []; - _.each(children, function(child) { - var childMin = dfs(child); - if (g.children(child).length) { - subgraphs.push({ v: child, order: childMin }); - } - min = Math.min(min, childMin); - }); - _.reduce(_.sortBy(subgraphs, "order"), function(prev, curr) { - cg.setEdge(prev.v, curr.v); - return curr; - }); - return min; - } - return g.node(v).order; - } - dfs(undefined); - */ -} - -},{"../lodash":38}],42:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = barycenter; - -function barycenter(g, movable) { - return _.map(movable, function(v) { - var inV = g.inEdges(v); - if (!inV.length) { - return { v: v }; - } else { - var result = _.reduce(inV, function(acc, e) { - var edge = g.edge(e), - nodeU = g.node(e.v); - return { - sum: acc.sum + (edge.weight * nodeU.order), - weight: acc.weight + edge.weight - }; - }, { sum: 0, weight: 0 }); - - return { - v: v, - barycenter: result.sum / result.weight, - weight: result.weight - }; - } - }); -} - - -},{"../lodash":38}],43:[function(require,module,exports){ -var _ = require("../lodash"), - Graph = require("../graphlib").Graph; - -module.exports = buildLayerGraph; - -/* - * Constructs a graph that can be used to sort a layer of nodes. The graph will - * contain all base and subgraph nodes from the request layer in their original - * hierarchy and any edges that are incident on these nodes and are of the type - * requested by the "relationship" parameter. - * - * Nodes from the requested rank that do not have parents are assigned a root - * node in the output graph, which is set in the root graph attribute. This - * makes it easy to walk the hierarchy of movable nodes during ordering. - * - * Pre-conditions: - * - * 1. Input graph is a DAG - * 2. Base nodes in the input graph have a rank attribute - * 3. Subgraph nodes in the input graph has minRank and maxRank attributes - * 4. Edges have an assigned weight - * - * Post-conditions: - * - * 1. Output graph has all nodes in the movable rank with preserved - * hierarchy. - * 2. Root nodes in the movable layer are made children of the node - * indicated by the root attribute of the graph. - * 3. Non-movable nodes incident on movable nodes, selected by the - * relationship parameter, are included in the graph (without hierarchy). - * 4. Edges incident on movable nodes, selected by the relationship - * parameter, are added to the output graph. - * 5. The weights for copied edges are aggregated as need, since the output - * graph is not a multi-graph. - */ -function buildLayerGraph(g, rank, relationship) { - var root = createRootNode(g), - result = new Graph({ compound: true }).setGraph({ root: root }) - .setDefaultNodeLabel(function(v) { return g.node(v); }); - - _.each(g.nodes(), function(v) { - var node = g.node(v), - parent = g.parent(v); - - if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) { - result.setNode(v); - result.setParent(v, parent || root); - - // This assumes we have only short edges! - _.each(g[relationship](v), function(e) { - var u = e.v === v ? e.w : e.v, - edge = result.edge(u, v), - weight = !_.isUndefined(edge) ? edge.weight : 0; - result.setEdge(u, v, { weight: g.edge(e).weight + weight }); - }); - - if (_.has(node, "minRank")) { - result.setNode(v, { - borderLeft: node.borderLeft[rank], - borderRight: node.borderRight[rank] - }); - } - } - }); - - return result; -} - -function createRootNode(g) { - var v; - while (g.hasNode((v = _.uniqueId("_root")))); - return v; -} - -},{"../graphlib":35,"../lodash":38}],44:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = crossCount; - -/* - * A function that takes a layering (an array of layers, each with an array of - * ordererd nodes) and a graph and returns a weighted crossing count. - * - * Pre-conditions: - * - * 1. Input graph must be simple (not a multigraph), directed, and include - * only simple edges. - * 2. Edges in the input graph must have assigned weights. - * - * Post-conditions: - * - * 1. The graph and layering matrix are left unchanged. - * - * This algorithm is derived from Barth, et al., "Bilayer Cross Counting." - */ -function crossCount(g, layering) { - var cc = 0; - for (var i = 1; i < layering.length; ++i) { - cc += twoLayerCrossCount(g, layering[i-1], layering[i]); - } - return cc; -} - -function twoLayerCrossCount(g, northLayer, southLayer) { - // Sort all of the edges between the north and south layers by their position - // in the north layer and then the south. Map these edges to the position of - // their head in the south layer. - var southPos = _.zipObject(southLayer, - _.map(southLayer, function (v, i) { return i; })); - var southEntries = _.flatten(_.map(northLayer, function(v) { - return _.chain(g.outEdges(v)) - .map(function(e) { - return { pos: southPos[e.w], weight: g.edge(e).weight }; - }) - .sortBy("pos") - .value(); - }), true); - - // Build the accumulator tree - var firstIndex = 1; - while (firstIndex < southLayer.length) firstIndex <<= 1; - var treeSize = 2 * firstIndex - 1; - firstIndex -= 1; - var tree = _.map(new Array(treeSize), function() { return 0; }); - - // Calculate the weighted crossings - var cc = 0; - _.each(southEntries.forEach(function(entry) { - var index = entry.pos + firstIndex; - tree[index] += entry.weight; - var weightSum = 0; - while (index > 0) { - if (index % 2) { - weightSum += tree[index + 1]; - } - index = (index - 1) >> 1; - tree[index] += entry.weight; - } - cc += entry.weight * weightSum; - })); - - return cc; -} - -},{"../lodash":38}],45:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - initOrder = require("./init-order"), - crossCount = require("./cross-count"), - sortSubgraph = require("./sort-subgraph"), - buildLayerGraph = require("./build-layer-graph"), - addSubgraphConstraints = require("./add-subgraph-constraints"), - Graph = require("../graphlib").Graph, - util = require("../util"); - -module.exports = order; - -/* - * Applies heuristics to minimize edge crossings in the graph and sets the best - * order solution as an order attribute on each node. - * - * Pre-conditions: - * - * 1. Graph must be DAG - * 2. Graph nodes must be objects with a "rank" attribute - * 3. Graph edges must have the "weight" attribute - * - * Post-conditions: - * - * 1. Graph nodes will have an "order" attribute based on the results of the - * algorithm. - */ -function order(g) { - var maxRank = util.maxRank(g), - downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), "inEdges"), - upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), "outEdges"); - - var layering = initOrder(g); - assignOrder(g, layering); - - var bestCC = Number.POSITIVE_INFINITY, - best; - - for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) { - sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2); - - layering = util.buildLayerMatrix(g); - var cc = crossCount(g, layering); - if (cc < bestCC) { - lastBest = 0; - best = _.cloneDeep(layering); - bestCC = cc; - } - } - - assignOrder(g, best); -} - -function buildLayerGraphs(g, ranks, relationship) { - return _.map(ranks, function(rank) { - return buildLayerGraph(g, rank, relationship); - }); -} - -function sweepLayerGraphs(layerGraphs, biasRight) { - var cg = new Graph(); - _.each(layerGraphs, function(lg) { - var root = lg.graph().root; - var sorted = sortSubgraph(lg, root, cg, biasRight); - _.each(sorted.vs, function(v, i) { - lg.node(v).order = i; - }); - addSubgraphConstraints(lg, cg, sorted.vs); - }); -} - -function assignOrder(g, layering) { - _.each(layering, function(layer) { - _.each(layer, function(v, i) { - g.node(v).order = i; - }); - }); -} - -},{"../graphlib":35,"../lodash":38,"../util":57,"./add-subgraph-constraints":41,"./build-layer-graph":43,"./cross-count":44,"./init-order":46,"./sort-subgraph":48}],46:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = initOrder; - -/* - * Assigns an initial order value for each node by performing a DFS search - * starting from nodes in the first rank. Nodes are assigned an order in their - * rank as they are first visited. - * - * This approach comes from Gansner, et al., "A Technique for Drawing Directed - * Graphs." - * - * Returns a layering matrix with an array per layer and each layer sorted by - * the order of its nodes. - */ -function initOrder(g) { - var visited = {}, - simpleNodes = _.filter(g.nodes(), function(v) { - return !g.children(v).length; - }), - maxRank = _.max(_.map(simpleNodes, function(v) { return g.node(v).rank; })), - layers = _.map(_.range(maxRank + 1), function() { return []; }); - - function dfs(v) { - if (_.has(visited, v)) return; - visited[v] = true; - var node = g.node(v); - layers[node.rank].push(v); - _.each(g.successors(v), dfs); - } - - var orderedVs = _.sortBy(simpleNodes, function(v) { return g.node(v).rank; }); - _.each(orderedVs, dfs); - - return layers; -} - -},{"../lodash":38}],47:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = resolveConflicts; - -/* - * Given a list of entries of the form {v, barycenter, weight} and a - * constraint graph this function will resolve any conflicts between the - * constraint graph and the barycenters for the entries. If the barycenters for - * an entry would violate a constraint in the constraint graph then we coalesce - * the nodes in the conflict into a new node that respects the contraint and - * aggregates barycenter and weight information. - * - * This implementation is based on the description in Forster, "A Fast and - * Simple Hueristic for Constrained Two-Level Crossing Reduction," thought it - * differs in some specific details. - * - * Pre-conditions: - * - * 1. Each entry has the form {v, barycenter, weight}, or if the node has - * no barycenter, then {v}. - * - * Returns: - * - * A new list of entries of the form {vs, i, barycenter, weight}. The list - * `vs` may either be a singleton or it may be an aggregation of nodes - * ordered such that they do not violate constraints from the constraint - * graph. The property `i` is the lowest original index of any of the - * elements in `vs`. - */ -function resolveConflicts(entries, cg) { - var mappedEntries = {}; - _.each(entries, function(entry, i) { - var tmp = mappedEntries[entry.v] = { - indegree: 0, - "in": [], - out: [], - vs: [entry.v], - i: i - }; - if (!_.isUndefined(entry.barycenter)) { - tmp.barycenter = entry.barycenter; - tmp.weight = entry.weight; - } - }); - - _.each(cg.edges(), function(e) { - var entryV = mappedEntries[e.v], - entryW = mappedEntries[e.w]; - if (!_.isUndefined(entryV) && !_.isUndefined(entryW)) { - entryW.indegree++; - entryV.out.push(mappedEntries[e.w]); - } - }); - - var sourceSet = _.filter(mappedEntries, function(entry) { - return !entry.indegree; - }); - - return doResolveConflicts(sourceSet); -} - -function doResolveConflicts(sourceSet) { - var entries = []; - - function handleIn(vEntry) { - return function(uEntry) { - if (uEntry.merged) { - return; - } - if (_.isUndefined(uEntry.barycenter) || - _.isUndefined(vEntry.barycenter) || - uEntry.barycenter >= vEntry.barycenter) { - mergeEntries(vEntry, uEntry); - } - }; - } - - function handleOut(vEntry) { - return function(wEntry) { - wEntry["in"].push(vEntry); - if (--wEntry.indegree === 0) { - sourceSet.push(wEntry); - } - }; - } - - while (sourceSet.length) { - var entry = sourceSet.pop(); - entries.push(entry); - _.each(entry["in"].reverse(), handleIn(entry)); - _.each(entry.out, handleOut(entry)); - } - - return _.chain(entries) - .filter(function(entry) { return !entry.merged; }) - .map(function(entry) { - return _.pick(entry, ["vs", "i", "barycenter", "weight"]); - }) - .value(); -} - -function mergeEntries(target, source) { - var sum = 0, - weight = 0; - - if (target.weight) { - sum += target.barycenter * target.weight; - weight += target.weight; - } - - if (source.weight) { - sum += source.barycenter * source.weight; - weight += source.weight; - } - - target.vs = source.vs.concat(target.vs); - target.barycenter = sum / weight; - target.weight = weight; - target.i = Math.min(source.i, target.i); - source.merged = true; -} - -},{"../lodash":38}],48:[function(require,module,exports){ -var _ = require("../lodash"), - barycenter = require("./barycenter"), - resolveConflicts = require("./resolve-conflicts"), - sort = require("./sort"); - -module.exports = sortSubgraph; - -function sortSubgraph(g, v, cg, biasRight) { - var movable = g.children(v), - node = g.node(v), - bl = node ? node.borderLeft : undefined, - br = node ? node.borderRight: undefined, - subgraphs = {}; - - if (bl) { - movable = _.filter(movable, function(w) { - return w !== bl && w !== br; - }); - } - - var barycenters = barycenter(g, movable); - _.each(barycenters, function(entry) { - if (g.children(entry.v).length) { - var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight); - subgraphs[entry.v] = subgraphResult; - if (_.has(subgraphResult, "barycenter")) { - mergeBarycenters(entry, subgraphResult); - } - } - }); - - var entries = resolveConflicts(barycenters, cg); - expandSubgraphs(entries, subgraphs); - - var result = sort(entries, biasRight); - - if (bl) { - result.vs = _.flatten([bl, result.vs, br], true); - if (g.predecessors(bl).length) { - var blPred = g.node(g.predecessors(bl)[0]), - brPred = g.node(g.predecessors(br)[0]); - if (!_.has(result, "barycenter")) { - result.barycenter = 0; - result.weight = 0; - } - result.barycenter = (result.barycenter * result.weight + - blPred.order + brPred.order) / (result.weight + 2); - result.weight += 2; - } - } - - return result; -} - -function expandSubgraphs(entries, subgraphs) { - _.each(entries, function(entry) { - entry.vs = _.flatten(entry.vs.map(function(v) { - if (subgraphs[v]) { - return subgraphs[v].vs; - } - return v; - }), true); - }); -} - -function mergeBarycenters(target, other) { - if (!_.isUndefined(target.barycenter)) { - target.barycenter = (target.barycenter * target.weight + - other.barycenter * other.weight) / - (target.weight + other.weight); - target.weight += other.weight; - } else { - target.barycenter = other.barycenter; - target.weight = other.weight; - } -} - -},{"../lodash":38,"./barycenter":42,"./resolve-conflicts":47,"./sort":49}],49:[function(require,module,exports){ -var _ = require("../lodash"), - util = require("../util"); - -module.exports = sort; - -function sort(entries, biasRight) { - var parts = util.partition(entries, function(entry) { - return _.has(entry, "barycenter"); - }); - var sortable = parts.lhs, - unsortable = _.sortBy(parts.rhs, function(entry) { return -entry.i; }), - vs = [], - sum = 0, - weight = 0, - vsIndex = 0; - - sortable.sort(compareWithBias(!!biasRight)); - - vsIndex = consumeUnsortable(vs, unsortable, vsIndex); - - _.each(sortable, function (entry) { - vsIndex += entry.vs.length; - vs.push(entry.vs); - sum += entry.barycenter * entry.weight; - weight += entry.weight; - vsIndex = consumeUnsortable(vs, unsortable, vsIndex); - }); - - var result = { vs: _.flatten(vs, true) }; - if (weight) { - result.barycenter = sum / weight; - result.weight = weight; - } - return result; -} - -function consumeUnsortable(vs, unsortable, index) { - var last; - while (unsortable.length && (last = _.last(unsortable)).i <= index) { - unsortable.pop(); - vs.push(last.vs); - index++; - } - return index; -} - -function compareWithBias(bias) { - return function(entryV, entryW) { - if (entryV.barycenter < entryW.barycenter) { - return -1; - } else if (entryV.barycenter > entryW.barycenter) { - return 1; - } - - return !bias ? entryV.i - entryW.i : entryW.i - entryV.i; - }; -} - -},{"../lodash":38,"../util":57}],50:[function(require,module,exports){ -var _ = require("./lodash"); - -module.exports = parentDummyChains; - -function parentDummyChains(g) { - var postorderNums = postorder(g); - - _.each(g.graph().dummyChains, function(v) { - var node = g.node(v), - edgeObj = node.edgeObj, - pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w), - path = pathData.path, - lca = pathData.lca, - pathIdx = 0, - pathV = path[pathIdx], - ascending = true; - - while (v !== edgeObj.w) { - node = g.node(v); - - if (ascending) { - while ((pathV = path[pathIdx]) !== lca && - g.node(pathV).maxRank < node.rank) { - pathIdx++; - } - - if (pathV === lca) { - ascending = false; - } - } - - if (!ascending) { - while (pathIdx < path.length - 1 && - g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) { - pathIdx++; - } - pathV = path[pathIdx]; - } - - g.setParent(v, pathV); - v = g.successors(v)[0]; - } - }); -} - -// Find a path from v to w through the lowest common ancestor (LCA). Return the -// full path and the LCA. -function findPath(g, postorderNums, v, w) { - var vPath = [], - wPath = [], - low = Math.min(postorderNums[v].low, postorderNums[w].low), - lim = Math.max(postorderNums[v].lim, postorderNums[w].lim), - parent, - lca; - - // Traverse up from v to find the LCA - parent = v; - do { - parent = g.parent(parent); - vPath.push(parent); - } while (parent && - (postorderNums[parent].low > low || lim > postorderNums[parent].lim)); - lca = parent; - - // Traverse from w to LCA - parent = w; - while ((parent = g.parent(parent)) !== lca) { - wPath.push(parent); - } - - return { path: vPath.concat(wPath.reverse()), lca: lca }; -} - -function postorder(g) { - var result = {}, - lim = 0; - - function dfs(v) { - var low = lim; - _.each(g.children(v), dfs); - result[v] = { low: low, lim: lim++ }; - } - _.each(g.children(), dfs); - - return result; -} - -},{"./lodash":38}],51:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - Graph = require("../graphlib").Graph, - util = require("../util"); - -/* - * This module provides coordinate assignment based on Brandes and Köpf, "Fast - * and Simple Horizontal Coordinate Assignment." - */ - -module.exports = { - positionX: positionX, - findType1Conflicts: findType1Conflicts, - findType2Conflicts: findType2Conflicts, - addConflict: addConflict, - hasConflict: hasConflict, - verticalAlignment: verticalAlignment, - horizontalCompaction: horizontalCompaction, - alignCoordinates: alignCoordinates, - findSmallestWidthAlignment: findSmallestWidthAlignment, - balance: balance -}; - -/* - * Marks all edges in the graph with a type-1 conflict with the "type1Conflict" - * property. A type-1 conflict is one where a non-inner segment crosses an - * inner segment. An inner segment is an edge with both incident nodes marked - * with the "dummy" property. - * - * This algorithm scans layer by layer, starting with the second, for type-1 - * conflicts between the current layer and the previous layer. For each layer - * it scans the nodes from left to right until it reaches one that is incident - * on an inner segment. It then scans predecessors to determine if they have - * edges that cross that inner segment. At the end a final scan is done for all - * nodes on the current rank to see if they cross the last visited inner - * segment. - * - * This algorithm (safely) assumes that a dummy node will only be incident on a - * single node in the layers being scanned. - */ -function findType1Conflicts(g, layering) { - var conflicts = {}; - - function visitLayer(prevLayer, layer) { - var - // last visited node in the previous layer that is incident on an inner - // segment. - k0 = 0, - // Tracks the last node in this layer scanned for crossings with a type-1 - // segment. - scanPos = 0, - prevLayerLength = prevLayer.length, - lastNode = _.last(layer); - - _.each(layer, function(v, i) { - var w = findOtherInnerSegmentNode(g, v), - k1 = w ? g.node(w).order : prevLayerLength; - - if (w || v === lastNode) { - _.each(layer.slice(scanPos, i +1), function(scanNode) { - _.each(g.predecessors(scanNode), function(u) { - var uLabel = g.node(u), - uPos = uLabel.order; - if ((uPos < k0 || k1 < uPos) && - !(uLabel.dummy && g.node(scanNode).dummy)) { - addConflict(conflicts, u, scanNode); - } - }); - }); - scanPos = i + 1; - k0 = k1; - } - }); - - return layer; - } - - _.reduce(layering, visitLayer); - return conflicts; -} - -function findType2Conflicts(g, layering) { - var conflicts = {}; - - function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) { - var v; - _.each(_.range(southPos, southEnd), function(i) { - v = south[i]; - if (g.node(v).dummy) { - _.each(g.predecessors(v), function(u) { - var uNode = g.node(u); - if (uNode.dummy && - (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) { - addConflict(conflicts, u, v); - } - }); - } - }); - } - - - function visitLayer(north, south) { - var prevNorthPos = -1, - nextNorthPos, - southPos = 0; - - _.each(south, function(v, southLookahead) { - if (g.node(v).dummy === "border") { - var predecessors = g.predecessors(v); - if (predecessors.length) { - nextNorthPos = g.node(predecessors[0]).order; - scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos); - southPos = southLookahead; - prevNorthPos = nextNorthPos; - } - } - scan(south, southPos, south.length, nextNorthPos, north.length); - }); - - return south; - } - - _.reduce(layering, visitLayer); - return conflicts; -} - -function findOtherInnerSegmentNode(g, v) { - if (g.node(v).dummy) { - return _.find(g.predecessors(v), function(u) { - return g.node(u).dummy; - }); - } -} - -function addConflict(conflicts, v, w) { - if (v > w) { - var tmp = v; - v = w; - w = tmp; - } - - var conflictsV = conflicts[v]; - if (!conflictsV) { - conflicts[v] = conflictsV = {}; - } - conflictsV[w] = true; -} - -function hasConflict(conflicts, v, w) { - if (v > w) { - var tmp = v; - v = w; - w = tmp; - } - return _.has(conflicts[v], w); -} - -/* - * Try to align nodes into vertical "blocks" where possible. This algorithm - * attempts to align a node with one of its median neighbors. If the edge - * connecting a neighbor is a type-1 conflict then we ignore that possibility. - * If a previous node has already formed a block with a node after the node - * we're trying to form a block with, we also ignore that possibility - our - * blocks would be split in that scenario. - */ -function verticalAlignment(g, layering, conflicts, neighborFn) { - var root = {}, - align = {}, - pos = {}; - - // We cache the position here based on the layering because the graph and - // layering may be out of sync. The layering matrix is manipulated to - // generate different extreme alignments. - _.each(layering, function(layer) { - _.each(layer, function(v, order) { - root[v] = v; - align[v] = v; - pos[v] = order; - }); - }); - - _.each(layering, function(layer) { - var prevIdx = -1; - _.each(layer, function(v) { - var ws = neighborFn(v); - if (ws.length) { - ws = _.sortBy(ws, function(w) { return pos[w]; }); - var mp = (ws.length - 1) / 2; - for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) { - var w = ws[i]; - if (align[v] === v && - prevIdx < pos[w] && - !hasConflict(conflicts, v, w)) { - align[w] = v; - align[v] = root[v] = root[w]; - prevIdx = pos[w]; - } - } - } - }); - }); - - return { root: root, align: align }; -} - -function horizontalCompaction(g, layering, root, align, reverseSep) { - // This portion of the algorithm differs from BK due to a number of problems. - // Instead of their algorithm we construct a new block graph and do two - // sweeps. The first sweep places blocks with the smallest possible - // coordinates. The second sweep removes unused space by moving blocks to the - // greatest coordinates without violating separation. - var xs = {}, - blockG = buildBlockGraph(g, layering, root, reverseSep); - - // First pass, assign smallest coordinates via DFS - var visited = {}; - function pass1(v) { - if (!_.has(visited, v)) { - visited[v] = true; - xs[v] = _.reduce(blockG.inEdges(v), function(max, e) { - pass1(e.v); - return Math.max(max, xs[e.v] + blockG.edge(e)); - }, 0); - } - } - _.each(blockG.nodes(), pass1); - - var borderType = reverseSep ? "borderLeft" : "borderRight"; - function pass2(v) { - if (visited[v] !== 2) { - visited[v]++; - var node = g.node(v); - var min = _.reduce(blockG.outEdges(v), function(min, e) { - pass2(e.w); - return Math.min(min, xs[e.w] - blockG.edge(e)); - }, Number.POSITIVE_INFINITY); - if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) { - xs[v] = Math.max(xs[v], min); - } - } - } - _.each(blockG.nodes(), pass2); - - // Assign x coordinates to all nodes - _.each(align, function(v) { - xs[v] = xs[root[v]]; - }); - - return xs; -} - - -function buildBlockGraph(g, layering, root, reverseSep) { - var blockGraph = new Graph(), - graphLabel = g.graph(), - sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep); - - _.each(layering, function(layer) { - var u; - _.each(layer, function(v) { - var vRoot = root[v]; - blockGraph.setNode(vRoot); - if (u) { - var uRoot = root[u], - prevMax = blockGraph.edge(uRoot, vRoot); - blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0)); - } - u = v; - }); - }); - - return blockGraph; -} - -/* - * Returns the alignment that has the smallest width of the given alignments. - */ -function findSmallestWidthAlignment(g, xss) { - return _.min(xss, function(xs) { - var min = _.min(xs, function(x, v) { return x - width(g, v) / 2; }), - max = _.max(xs, function(x, v) { return x + width(g, v) / 2; }); - return max - min; - }); -} - -/* - * Align the coordinates of each of the layout alignments such that - * left-biased alignments have their minimum coordinate at the same point as - * the minimum coordinate of the smallest width alignment and right-biased - * alignments have their maximum coordinate at the same point as the maximum - * coordinate of the smallest width alignment. - */ -function alignCoordinates(xss, alignTo) { - var alignToMin = _.min(alignTo), - alignToMax = _.max(alignTo); - - _.each(["u", "d"], function(vert) { - _.each(["l", "r"], function(horiz) { - var alignment = vert + horiz, - xs = xss[alignment], - delta; - if (xs === alignTo) return; - - delta = horiz === "l" ? alignToMin - _.min(xs) : alignToMax - _.max(xs); - - if (delta) { - xss[alignment] = _.mapValues(xs, function(x) { return x + delta; }); - } - }); - }); -} - -function balance(xss, align) { - return _.mapValues(xss.ul, function(ignore, v) { - if (align) { - return xss[align.toLowerCase()][v]; - } else { - var xs = _.sortBy(_.pluck(xss, v)); - return (xs[1] + xs[2]) / 2; - } - }); -} - -function positionX(g) { - var layering = util.buildLayerMatrix(g), - conflicts = _.merge(findType1Conflicts(g, layering), - findType2Conflicts(g, layering)); - - var xss = {}, - adjustedLayering; - _.each(["u", "d"], function(vert) { - adjustedLayering = vert === "u" ? layering : _.values(layering).reverse(); - _.each(["l", "r"], function(horiz) { - if (horiz === "r") { - adjustedLayering = _.map(adjustedLayering, function(inner) { - return _.values(inner).reverse(); - }); - } - - var neighborFn = _.bind(vert === "u" ? g.predecessors : g.successors, g); - var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn); - var xs = horizontalCompaction(g, adjustedLayering, - align.root, align.align, - horiz === "r"); - if (horiz === "r") { - xs = _.mapValues(xs, function(x) { return -x; }); - } - xss[vert + horiz] = xs; - }); - }); - - var smallestWidth = findSmallestWidthAlignment(g, xss); - alignCoordinates(xss, smallestWidth); - return balance(xss, g.graph().align); -} - -function sep(nodeSep, edgeSep, reverseSep) { - return function(g, v, w) { - var vLabel = g.node(v), - wLabel = g.node(w), - sum = 0, - delta; - - sum += vLabel.width / 2; - if (_.has(vLabel, "labelpos")) { - switch (vLabel.labelpos.toLowerCase()) { - case "l": delta = -vLabel.width / 2; break; - case "r": delta = vLabel.width / 2; break; - } - } - if (delta) { - sum += reverseSep ? delta : -delta; - } - delta = 0; - - sum += (vLabel.dummy ? edgeSep : nodeSep) / 2; - sum += (wLabel.dummy ? edgeSep : nodeSep) / 2; - - sum += wLabel.width / 2; - if (_.has(wLabel, "labelpos")) { - switch (wLabel.labelpos.toLowerCase()) { - case "l": delta = wLabel.width / 2; break; - case "r": delta = -wLabel.width / 2; break; - } - } - if (delta) { - sum += reverseSep ? delta : -delta; - } - delta = 0; - - return sum; - }; -} - -function width(g, v) { - return g.node(v).width; -} - -},{"../graphlib":35,"../lodash":38,"../util":57}],52:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - util = require("../util"), - positionX = require("./bk").positionX; - -module.exports = position; - -function position(g) { - g = util.asNonCompoundGraph(g); - - positionY(g); - _.each(positionX(g), function(x, v) { - g.node(v).x = x; - }); -} - -function positionY(g) { - var layering = util.buildLayerMatrix(g), - rankSep = g.graph().ranksep, - prevY = 0; - _.each(layering, function(layer) { - var maxHeight = _.max(_.map(layer, function(v) { return g.node(v).height; })); - _.each(layer, function(v) { - g.node(v).y = prevY + maxHeight / 2; - }); - prevY += maxHeight + rankSep; - }); -} - - -},{"../lodash":38,"../util":57,"./bk":51}],53:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - Graph = require("../graphlib").Graph, - slack = require("./util").slack; - -module.exports = feasibleTree; - -/* - * Constructs a spanning tree with tight edges and adjusted the input node's - * ranks to achieve this. A tight edge is one that is has a length that matches - * its "minlen" attribute. - * - * The basic structure for this function is derived from Gansner, et al., "A - * Technique for Drawing Directed Graphs." - * - * Pre-conditions: - * - * 1. Graph must be a DAG. - * 2. Graph must be connected. - * 3. Graph must have at least one node. - * 5. Graph nodes must have been previously assigned a "rank" property that - * respects the "minlen" property of incident edges. - * 6. Graph edges must have a "minlen" property. - * - * Post-conditions: - * - * - Graph nodes will have their rank adjusted to ensure that all edges are - * tight. - * - * Returns a tree (undirected graph) that is constructed using only "tight" - * edges. - */ -function feasibleTree(g) { - var t = new Graph({ directed: false }); - - // Choose arbitrary node from which to start our tree - var start = g.nodes()[0], - size = g.nodeCount(); - t.setNode(start, {}); - - var edge, delta; - while (tightTree(t, g) < size) { - edge = findMinSlackEdge(t, g); - delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge); - shiftRanks(t, g, delta); - } - - return t; -} - -/* - * Finds a maximal tree of tight edges and returns the number of nodes in the - * tree. - */ -function tightTree(t, g) { - function dfs(v) { - _.each(g.nodeEdges(v), function(e) { - var edgeV = e.v, - w = (v === edgeV) ? e.w : edgeV; - if (!t.hasNode(w) && !slack(g, e)) { - t.setNode(w, {}); - t.setEdge(v, w, {}); - dfs(w); - } - }); - } - - _.each(t.nodes(), dfs); - return t.nodeCount(); -} - -/* - * Finds the edge with the smallest slack that is incident on tree and returns - * it. - */ -function findMinSlackEdge(t, g) { - return _.min(g.edges(), function(e) { - if (t.hasNode(e.v) !== t.hasNode(e.w)) { - return slack(g, e); - } - }); -} - -function shiftRanks(t, g, delta) { - _.each(t.nodes(), function(v) { - g.node(v).rank += delta; - }); -} - -},{"../graphlib":35,"../lodash":38,"./util":56}],54:[function(require,module,exports){ -"use strict"; - -var rankUtil = require("./util"), - longestPath = rankUtil.longestPath, - feasibleTree = require("./feasible-tree"), - networkSimplex = require("./network-simplex"); - -module.exports = rank; - -/* - * Assigns a rank to each node in the input graph that respects the "minlen" - * constraint specified on edges between nodes. - * - * This basic structure is derived from Gansner, et al., "A Technique for - * Drawing Directed Graphs." - * - * Pre-conditions: - * - * 1. Graph must be a connected DAG - * 2. Graph nodes must be objects - * 3. Graph edges must have "weight" and "minlen" attributes - * - * Post-conditions: - * - * 1. Graph nodes will have a "rank" attribute based on the results of the - * algorithm. Ranks can start at any index (including negative), we'll - * fix them up later. - */ -function rank(g) { - switch(g.graph().ranker) { - case "network-simplex": networkSimplexRanker(g); break; - case "tight-tree": tightTreeRanker(g); break; - case "longest-path": longestPathRanker(g); break; - default: networkSimplexRanker(g); - } -} - -// A fast and simple ranker, but results are far from optimal. -var longestPathRanker = longestPath; - -function tightTreeRanker(g) { - longestPath(g); - feasibleTree(g); -} - -function networkSimplexRanker(g) { - networkSimplex(g); -} - -},{"./feasible-tree":53,"./network-simplex":55,"./util":56}],55:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - feasibleTree = require("./feasible-tree"), - slack = require("./util").slack, - initRank = require("./util").longestPath, - preorder = require("../graphlib").alg.preorder, - postorder = require("../graphlib").alg.postorder, - simplify = require("../util").simplify; - -module.exports = networkSimplex; - -// Expose some internals for testing purposes -networkSimplex.initLowLimValues = initLowLimValues; -networkSimplex.initCutValues = initCutValues; -networkSimplex.calcCutValue = calcCutValue; -networkSimplex.leaveEdge = leaveEdge; -networkSimplex.enterEdge = enterEdge; -networkSimplex.exchangeEdges = exchangeEdges; - -/* - * The network simplex algorithm assigns ranks to each node in the input graph - * and iteratively improves the ranking to reduce the length of edges. - * - * Preconditions: - * - * 1. The input graph must be a DAG. - * 2. All nodes in the graph must have an object value. - * 3. All edges in the graph must have "minlen" and "weight" attributes. - * - * Postconditions: - * - * 1. All nodes in the graph will have an assigned "rank" attribute that has - * been optimized by the network simplex algorithm. Ranks start at 0. - * - * - * A rough sketch of the algorithm is as follows: - * - * 1. Assign initial ranks to each node. We use the longest path algorithm, - * which assigns ranks to the lowest position possible. In general this - * leads to very wide bottom ranks and unnecessarily long edges. - * 2. Construct a feasible tight tree. A tight tree is one such that all - * edges in the tree have no slack (difference between length of edge - * and minlen for the edge). This by itself greatly improves the assigned - * rankings by shorting edges. - * 3. Iteratively find edges that have negative cut values. Generally a - * negative cut value indicates that the edge could be removed and a new - * tree edge could be added to produce a more compact graph. - * - * Much of the algorithms here are derived from Gansner, et al., "A Technique - * for Drawing Directed Graphs." The structure of the file roughly follows the - * structure of the overall algorithm. - */ -function networkSimplex(g) { - g = simplify(g); - initRank(g); - var t = feasibleTree(g); - initLowLimValues(t); - initCutValues(t, g); - - var e, f; - while ((e = leaveEdge(t))) { - f = enterEdge(t, g, e); - exchangeEdges(t, g, e, f); - } -} - -/* - * Initializes cut values for all edges in the tree. - */ -function initCutValues(t, g) { - var vs = postorder(t, t.nodes()); - vs = vs.slice(0, vs.length - 1); - _.each(vs, function(v) { - assignCutValue(t, g, v); - }); -} - -function assignCutValue(t, g, child) { - var childLab = t.node(child), - parent = childLab.parent; - t.edge(child, parent).cutvalue = calcCutValue(t, g, child); -} - -/* - * Given the tight tree, its graph, and a child in the graph calculate and - * return the cut value for the edge between the child and its parent. - */ -function calcCutValue(t, g, child) { - var childLab = t.node(child), - parent = childLab.parent, - // True if the child is on the tail end of the edge in the directed graph - childIsTail = true, - // The graph's view of the tree edge we're inspecting - graphEdge = g.edge(child, parent), - // The accumulated cut value for the edge between this node and its parent - cutValue = 0; - - if (!graphEdge) { - childIsTail = false; - graphEdge = g.edge(parent, child); - } - - cutValue = graphEdge.weight; - - _.each(g.nodeEdges(child), function(e) { - var isOutEdge = e.v === child, - other = isOutEdge ? e.w : e.v; - - if (other !== parent) { - var pointsToHead = isOutEdge === childIsTail, - otherWeight = g.edge(e).weight; - - cutValue += pointsToHead ? otherWeight : -otherWeight; - if (isTreeEdge(t, child, other)) { - var otherCutValue = t.edge(child, other).cutvalue; - cutValue += pointsToHead ? -otherCutValue : otherCutValue; - } - } - }); - - return cutValue; -} - -function initLowLimValues(tree, root) { - if (arguments.length < 2) { - root = tree.nodes()[0]; - } - dfsAssignLowLim(tree, {}, 1, root); -} - -function dfsAssignLowLim(tree, visited, nextLim, v, parent) { - var low = nextLim, - label = tree.node(v); - - visited[v] = true; - _.each(tree.neighbors(v), function(w) { - if (!_.has(visited, w)) { - nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v); - } - }); - - label.low = low; - label.lim = nextLim++; - if (parent) { - label.parent = parent; - } else { - // TODO should be able to remove this when we incrementally update low lim - delete label.parent; - } - - return nextLim; -} - -function leaveEdge(tree) { - return _.find(tree.edges(), function(e) { - return tree.edge(e).cutvalue < 0; - }); -} - -function enterEdge(t, g, edge) { - var v = edge.v, - w = edge.w; - - // For the rest of this function we assume that v is the tail and w is the - // head, so if we don't have this edge in the graph we should flip it to - // match the correct orientation. - if (!g.hasEdge(v, w)) { - v = edge.w; - w = edge.v; - } - - var vLabel = t.node(v), - wLabel = t.node(w), - tailLabel = vLabel, - flip = false; - - // If the root is in the tail of the edge then we need to flip the logic that - // checks for the head and tail nodes in the candidates function below. - if (vLabel.lim > wLabel.lim) { - tailLabel = wLabel; - flip = true; - } - - var candidates = _.filter(g.edges(), function(edge) { - return flip === isDescendant(t, t.node(edge.v), tailLabel) && - flip !== isDescendant(t, t.node(edge.w), tailLabel); - }); - - return _.min(candidates, function(edge) { return slack(g, edge); }); -} - -function exchangeEdges(t, g, e, f) { - var v = e.v, - w = e.w; - t.removeEdge(v, w); - t.setEdge(f.v, f.w, {}); - initLowLimValues(t); - initCutValues(t, g); - updateRanks(t, g); -} - -function updateRanks(t, g) { - var root = _.find(t.nodes(), function(v) { return !g.node(v).parent; }), - vs = preorder(t, root); - vs = vs.slice(1); - _.each(vs, function(v) { - var parent = t.node(v).parent, - edge = g.edge(v, parent), - flipped = false; - - if (!edge) { - edge = g.edge(parent, v); - flipped = true; - } - - g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen); - }); -} - -/* - * Returns true if the edge is in the tree. - */ -function isTreeEdge(tree, u, v) { - return tree.hasEdge(u, v); -} - -/* - * Returns true if the specified node is descendant of the root node per the - * assigned low and lim attributes in the tree. - */ -function isDescendant(tree, vLabel, rootLabel) { - return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim; -} - -},{"../graphlib":35,"../lodash":38,"../util":57,"./feasible-tree":53,"./util":56}],56:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = { - longestPath: longestPath, - slack: slack -}; - -/* - * Initializes ranks for the input graph using the longest path algorithm. This - * algorithm scales well and is fast in practice, it yields rather poor - * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom - * ranks wide and leaving edges longer than necessary. However, due to its - * speed, this algorithm is good for getting an initial ranking that can be fed - * into other algorithms. - * - * This algorithm does not normalize layers because it will be used by other - * algorithms in most cases. If using this algorithm directly, be sure to - * run normalize at the end. - * - * Pre-conditions: - * - * 1. Input graph is a DAG. - * 2. Input graph node labels can be assigned properties. - * - * Post-conditions: - * - * 1. Each node will be assign an (unnormalized) "rank" property. - */ -function longestPath(g) { - var visited = {}; - - function dfs(v) { - var label = g.node(v); - if (_.has(visited, v)) { - return label.rank; - } - visited[v] = true; - - var rank = _.min(_.map(g.outEdges(v), function(e) { - return dfs(e.w) - g.edge(e).minlen; - })); - - if (rank === Number.POSITIVE_INFINITY) { - rank = 0; - } - - return (label.rank = rank); - } - - _.each(g.sources(), dfs); -} - -/* - * Returns the amount of slack for the given edge. The slack is defined as the - * difference between the length of the edge and its minimum length. - */ -function slack(g, e) { - return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen; -} - -},{"../lodash":38}],57:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - Graph = require("./graphlib").Graph; - -module.exports = { - addDummyNode: addDummyNode, - simplify: simplify, - asNonCompoundGraph: asNonCompoundGraph, - successorWeights: successorWeights, - predecessorWeights: predecessorWeights, - intersectRect: intersectRect, - buildLayerMatrix: buildLayerMatrix, - normalizeRanks: normalizeRanks, - removeEmptyRanks: removeEmptyRanks, - addBorderNode: addBorderNode, - maxRank: maxRank, - partition: partition, - time: time, - notime: notime -}; - -/* - * Adds a dummy node to the graph and return v. - */ -function addDummyNode(g, type, attrs, name) { - var v; - do { - v = _.uniqueId(name); - } while (g.hasNode(v)); - - attrs.dummy = type; - g.setNode(v, attrs); - return v; -} - -/* - * Returns a new graph with only simple edges. Handles aggregation of data - * associated with multi-edges. - */ -function simplify(g) { - var simplified = new Graph().setGraph(g.graph()); - _.each(g.nodes(), function(v) { simplified.setNode(v, g.node(v)); }); - _.each(g.edges(), function(e) { - var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 }, - label = g.edge(e); - simplified.setEdge(e.v, e.w, { - weight: simpleLabel.weight + label.weight, - minlen: Math.max(simpleLabel.minlen, label.minlen) - }); - }); - return simplified; -} - -function asNonCompoundGraph(g) { - var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph()); - _.each(g.nodes(), function(v) { - if (!g.children(v).length) { - simplified.setNode(v, g.node(v)); - } - }); - _.each(g.edges(), function(e) { - simplified.setEdge(e, g.edge(e)); - }); - return simplified; -} - -function successorWeights(g) { - var weightMap = _.map(g.nodes(), function(v) { - var sucs = {}; - _.each(g.outEdges(v), function(e) { - sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight; - }); - return sucs; - }); - return _.zipObject(g.nodes(), weightMap); -} - -function predecessorWeights(g) { - var weightMap = _.map(g.nodes(), function(v) { - var preds = {}; - _.each(g.inEdges(v), function(e) { - preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight; - }); - return preds; - }); - return _.zipObject(g.nodes(), weightMap); -} - -/* - * Finds where a line starting at point ({x, y}) would intersect a rectangle - * ({x, y, width, height}) if it were pointing at the rectangle's center. - */ -function intersectRect(rect, point) { - var x = rect.x; - var y = rect.y; - - // Rectangle intersection algorithm from: - // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes - var dx = point.x - x; - var dy = point.y - y; - var w = rect.width / 2; - var h = rect.height / 2; - - if (!dx && !dy) { - throw new Error("Not possible to find intersection inside of the rectangle"); - } - - var sx, sy; - if (Math.abs(dy) * w > Math.abs(dx) * h) { - // Intersection is top or bottom of rect. - if (dy < 0) { - h = -h; - } - sx = h * dx / dy; - sy = h; - } else { - // Intersection is left or right of rect. - if (dx < 0) { - w = -w; - } - sx = w; - sy = w * dy / dx; - } - - return { x: x + sx, y: y + sy }; -} - -/* - * Given a DAG with each node assigned "rank" and "order" properties, this - * function will produce a matrix with the ids of each node. - */ -function buildLayerMatrix(g) { - var layering = _.map(_.range(maxRank(g) + 1), function() { return []; }); - _.each(g.nodes(), function(v) { - var node = g.node(v), - rank = node.rank; - if (!_.isUndefined(rank)) { - layering[rank][node.order] = v; - } - }); - return layering; -} - -/* - * Adjusts the ranks for all nodes in the graph such that all nodes v have - * rank(v) >= 0 and at least one node w has rank(w) = 0. - */ -function normalizeRanks(g) { - var min = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; })); - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (_.has(node, "rank")) { - node.rank -= min; - } - }); -} - -function removeEmptyRanks(g) { - // Ranks may not start at 0, so we need to offset them - var offset = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; })); - - var layers = []; - _.each(g.nodes(), function(v) { - var rank = g.node(v).rank - offset; - if (!layers[rank]) { - layers[rank] = []; - } - layers[rank].push(v); - }); - - var delta = 0, - nodeRankFactor = g.graph().nodeRankFactor; - _.each(layers, function(vs, i) { - if (_.isUndefined(vs) && i % nodeRankFactor !== 0) { - --delta; - } else if (delta) { - _.each(vs, function(v) { g.node(v).rank += delta; }); - } - }); -} - -function addBorderNode(g, prefix, rank, order) { - var node = { - width: 0, - height: 0 - }; - if (arguments.length >= 4) { - node.rank = rank; - node.order = order; - } - return addDummyNode(g, "border", node, prefix); -} - -function maxRank(g) { - return _.max(_.map(g.nodes(), function(v) { - var rank = g.node(v).rank; - if (!_.isUndefined(rank)) { - return rank; - } - })); -} - -/* - * Partition a collection into two groups: `lhs` and `rhs`. If the supplied - * function returns true for an entry it goes into `lhs`. Otherwise it goes - * into `rhs. - */ -function partition(collection, fn) { - var result = { lhs: [], rhs: [] }; - _.each(collection, function(value) { - if (fn(value)) { - result.lhs.push(value); - } else { - result.rhs.push(value); - } - }); - return result; -} - -/* - * Returns a new function that wraps `fn` with a timer. The wrapper logs the - * time it takes to execute the function. - */ -function time(name, fn) { - var start = _.now(); - try { - return fn(); - } finally { - console.log(name + " time: " + (_.now() - start) + "ms"); - } -} - -function notime(name, fn) { - return fn(); -} - -},{"./graphlib":35,"./lodash":38}],58:[function(require,module,exports){ -module.exports = "0.7.3"; - -},{}],59:[function(require,module,exports){ -/** - * Copyright (c) 2014, Chris Pettitt - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -var lib = require("./lib"); - -module.exports = { - Graph: lib.Graph, - json: require("./lib/json"), - alg: require("./lib/alg"), - version: lib.version -}; - -},{"./lib":75,"./lib/alg":66,"./lib/json":76}],60:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = components; - -function components(g) { - var visited = {}, - cmpts = [], - cmpt; - - function dfs(v) { - if (_.has(visited, v)) return; - visited[v] = true; - cmpt.push(v); - _.each(g.successors(v), dfs); - _.each(g.predecessors(v), dfs); - } - - _.each(g.nodes(), function(v) { - cmpt = []; - dfs(v); - if (cmpt.length) { - cmpts.push(cmpt); - } - }); - - return cmpts; -} - -},{"../lodash":77}],61:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = dfs; - -/* - * A helper that preforms a pre- or post-order traversal on the input graph - * and returns the nodes in the order they were visited. This algorithm treats - * the input as undirected. - * - * Order must be one of "pre" or "post". - */ -function dfs(g, vs, order) { - if (!_.isArray(vs)) { - vs = [vs]; - } - - var acc = [], - visited = {}; - _.each(vs, function(v) { - if (!g.hasNode(v)) { - throw new Error("Graph does not have node: " + v); - } - - doDfs(g, v, order === "post", visited, acc); - }); - return acc; -} - -function doDfs(g, v, postorder, visited, acc) { - if (!_.has(visited, v)) { - visited[v] = true; - - if (!postorder) { acc.push(v); } - _.each(g.neighbors(v), function(w) { - doDfs(g, w, postorder, visited, acc); - }); - if (postorder) { acc.push(v); } - } -} - -},{"../lodash":77}],62:[function(require,module,exports){ -var dijkstra = require("./dijkstra"), - _ = require("../lodash"); - -module.exports = dijkstraAll; - -function dijkstraAll(g, weightFunc, edgeFunc) { - return _.transform(g.nodes(), function(acc, v) { - acc[v] = dijkstra(g, v, weightFunc, edgeFunc); - }, {}); -} - -},{"../lodash":77,"./dijkstra":63}],63:[function(require,module,exports){ -var _ = require("../lodash"), - PriorityQueue = require("../data/priority-queue"); - -module.exports = dijkstra; - -var DEFAULT_WEIGHT_FUNC = _.constant(1); - -function dijkstra(g, source, weightFn, edgeFn) { - return runDijkstra(g, String(source), - weightFn || DEFAULT_WEIGHT_FUNC, - edgeFn || function(v) { return g.outEdges(v); }); -} - -function runDijkstra(g, source, weightFn, edgeFn) { - var results = {}, - pq = new PriorityQueue(), - v, vEntry; - - var updateNeighbors = function(edge) { - var w = edge.v !== v ? edge.v : edge.w, - wEntry = results[w], - weight = weightFn(edge), - distance = vEntry.distance + weight; - - if (weight < 0) { - throw new Error("dijkstra does not allow negative edge weights. " + - "Bad edge: " + edge + " Weight: " + weight); - } - - if (distance < wEntry.distance) { - wEntry.distance = distance; - wEntry.predecessor = v; - pq.decrease(w, distance); - } - }; - - g.nodes().forEach(function(v) { - var distance = v === source ? 0 : Number.POSITIVE_INFINITY; - results[v] = { distance: distance }; - pq.add(v, distance); - }); - - while (pq.size() > 0) { - v = pq.removeMin(); - vEntry = results[v]; - if (vEntry.distance === Number.POSITIVE_INFINITY) { - break; - } - - edgeFn(v).forEach(updateNeighbors); - } - - return results; -} - -},{"../data/priority-queue":73,"../lodash":77}],64:[function(require,module,exports){ -var _ = require("../lodash"), - tarjan = require("./tarjan"); - -module.exports = findCycles; - -function findCycles(g) { - return _.filter(tarjan(g), function(cmpt) { - return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0])); - }); -} - -},{"../lodash":77,"./tarjan":71}],65:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = floydWarshall; - -var DEFAULT_WEIGHT_FUNC = _.constant(1); - -function floydWarshall(g, weightFn, edgeFn) { - return runFloydWarshall(g, - weightFn || DEFAULT_WEIGHT_FUNC, - edgeFn || function(v) { return g.outEdges(v); }); -} - -function runFloydWarshall(g, weightFn, edgeFn) { - var results = {}, - nodes = g.nodes(); - - nodes.forEach(function(v) { - results[v] = {}; - results[v][v] = { distance: 0 }; - nodes.forEach(function(w) { - if (v !== w) { - results[v][w] = { distance: Number.POSITIVE_INFINITY }; - } - }); - edgeFn(v).forEach(function(edge) { - var w = edge.v === v ? edge.w : edge.v, - d = weightFn(edge); - results[v][w] = { distance: d, predecessor: v }; - }); - }); - - nodes.forEach(function(k) { - var rowK = results[k]; - nodes.forEach(function(i) { - var rowI = results[i]; - nodes.forEach(function(j) { - var ik = rowI[k]; - var kj = rowK[j]; - var ij = rowI[j]; - var altDistance = ik.distance + kj.distance; - if (altDistance < ij.distance) { - ij.distance = altDistance; - ij.predecessor = kj.predecessor; - } - }); - }); - }); - - return results; -} - -},{"../lodash":77}],66:[function(require,module,exports){ -module.exports = { - components: require("./components"), - dijkstra: require("./dijkstra"), - dijkstraAll: require("./dijkstra-all"), - findCycles: require("./find-cycles"), - floydWarshall: require("./floyd-warshall"), - isAcyclic: require("./is-acyclic"), - postorder: require("./postorder"), - preorder: require("./preorder"), - prim: require("./prim"), - tarjan: require("./tarjan"), - topsort: require("./topsort") -}; - -},{"./components":60,"./dijkstra":63,"./dijkstra-all":62,"./find-cycles":64,"./floyd-warshall":65,"./is-acyclic":67,"./postorder":68,"./preorder":69,"./prim":70,"./tarjan":71,"./topsort":72}],67:[function(require,module,exports){ -var topsort = require("./topsort"); - -module.exports = isAcyclic; - -function isAcyclic(g) { - try { - topsort(g); - } catch (e) { - if (e instanceof topsort.CycleException) { - return false; - } - throw e; - } - return true; -} - -},{"./topsort":72}],68:[function(require,module,exports){ -var dfs = require("./dfs"); - -module.exports = postorder; - -function postorder(g, vs) { - return dfs(g, vs, "post"); -} - -},{"./dfs":61}],69:[function(require,module,exports){ -var dfs = require("./dfs"); - -module.exports = preorder; - -function preorder(g, vs) { - return dfs(g, vs, "pre"); -} - -},{"./dfs":61}],70:[function(require,module,exports){ -var _ = require("../lodash"), - Graph = require("../graph"), - PriorityQueue = require("../data/priority-queue"); - -module.exports = prim; - -function prim(g, weightFunc) { - var result = new Graph(), - parents = {}, - pq = new PriorityQueue(), - v; - - function updateNeighbors(edge) { - var w = edge.v === v ? edge.w : edge.v, - pri = pq.priority(w); - if (pri !== undefined) { - var edgeWeight = weightFunc(edge); - if (edgeWeight < pri) { - parents[w] = v; - pq.decrease(w, edgeWeight); - } - } - } - - if (g.nodeCount() === 0) { - return result; - } - - _.each(g.nodes(), function(v) { - pq.add(v, Number.POSITIVE_INFINITY); - result.setNode(v); - }); - - // Start from an arbitrary node - pq.decrease(g.nodes()[0], 0); - - var init = false; - while (pq.size() > 0) { - v = pq.removeMin(); - if (_.has(parents, v)) { - result.setEdge(v, parents[v]); - } else if (init) { - throw new Error("Input graph is not connected: " + g); - } else { - init = true; - } - - g.nodeEdges(v).forEach(updateNeighbors); - } - - return result; -} - -},{"../data/priority-queue":73,"../graph":74,"../lodash":77}],71:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = tarjan; - -function tarjan(g) { - var index = 0, - stack = [], - visited = {}, // node id -> { onStack, lowlink, index } - results = []; - - function dfs(v) { - var entry = visited[v] = { - onStack: true, - lowlink: index, - index: index++ - }; - stack.push(v); - - g.successors(v).forEach(function(w) { - if (!_.has(visited, w)) { - dfs(w); - entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink); - } else if (visited[w].onStack) { - entry.lowlink = Math.min(entry.lowlink, visited[w].index); - } - }); - - if (entry.lowlink === entry.index) { - var cmpt = [], - w; - do { - w = stack.pop(); - visited[w].onStack = false; - cmpt.push(w); - } while (v !== w); - results.push(cmpt); - } - } - - g.nodes().forEach(function(v) { - if (!_.has(visited, v)) { - dfs(v); - } - }); - - return results; -} - -},{"../lodash":77}],72:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = topsort; -topsort.CycleException = CycleException; - -function topsort(g) { - var visited = {}, - stack = {}, - results = []; - - function visit(node) { - if (_.has(stack, node)) { - throw new CycleException(); - } - - if (!_.has(visited, node)) { - stack[node] = true; - visited[node] = true; - _.each(g.predecessors(node), visit); - delete stack[node]; - results.push(node); - } - } - - _.each(g.sinks(), visit); - - if (_.size(visited) !== g.nodeCount()) { - throw new CycleException(); - } - - return results; -} - -function CycleException() {} - -},{"../lodash":77}],73:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = PriorityQueue; - -/** - * A min-priority queue data structure. This algorithm is derived from Cormen, - * et al., "Introduction to Algorithms". The basic idea of a min-priority - * queue is that you can efficiently (in O(1) time) get the smallest key in - * the queue. Adding and removing elements takes O(log n) time. A key can - * have its priority decreased in O(log n) time. - */ -function PriorityQueue() { - this._arr = []; - this._keyIndices = {}; -} - -/** - * Returns the number of elements in the queue. Takes `O(1)` time. - */ -PriorityQueue.prototype.size = function() { - return this._arr.length; -}; - -/** - * Returns the keys that are in the queue. Takes `O(n)` time. - */ -PriorityQueue.prototype.keys = function() { - return this._arr.map(function(x) { return x.key; }); -}; - -/** - * Returns `true` if **key** is in the queue and `false` if not. - */ -PriorityQueue.prototype.has = function(key) { - return _.has(this._keyIndices, key); -}; - -/** - * Returns the priority for **key**. If **key** is not present in the queue - * then this function returns `undefined`. Takes `O(1)` time. - * - * @param {Object} key - */ -PriorityQueue.prototype.priority = function(key) { - var index = this._keyIndices[key]; - if (index !== undefined) { - return this._arr[index].priority; - } -}; - -/** - * Returns the key for the minimum element in this queue. If the queue is - * empty this function throws an Error. Takes `O(1)` time. - */ -PriorityQueue.prototype.min = function() { - if (this.size() === 0) { - throw new Error("Queue underflow"); - } - return this._arr[0].key; -}; - -/** - * Inserts a new key into the priority queue. If the key already exists in - * the queue this function returns `false`; otherwise it will return `true`. - * Takes `O(n)` time. - * - * @param {Object} key the key to add - * @param {Number} priority the initial priority for the key - */ -PriorityQueue.prototype.add = function(key, priority) { - var keyIndices = this._keyIndices; - key = String(key); - if (!_.has(keyIndices, key)) { - var arr = this._arr; - var index = arr.length; - keyIndices[key] = index; - arr.push({key: key, priority: priority}); - this._decrease(index); - return true; - } - return false; -}; - -/** - * Removes and returns the smallest key in the queue. Takes `O(log n)` time. - */ -PriorityQueue.prototype.removeMin = function() { - this._swap(0, this._arr.length - 1); - var min = this._arr.pop(); - delete this._keyIndices[min.key]; - this._heapify(0); - return min.key; -}; - -/** - * Decreases the priority for **key** to **priority**. If the new priority is - * greater than the previous priority, this function will throw an Error. - * - * @param {Object} key the key for which to raise priority - * @param {Number} priority the new priority for the key - */ -PriorityQueue.prototype.decrease = function(key, priority) { - var index = this._keyIndices[key]; - if (priority > this._arr[index].priority) { - throw new Error("New priority is greater than current priority. " + - "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority); - } - this._arr[index].priority = priority; - this._decrease(index); -}; - -PriorityQueue.prototype._heapify = function(i) { - var arr = this._arr; - var l = 2 * i, - r = l + 1, - largest = i; - if (l < arr.length) { - largest = arr[l].priority < arr[largest].priority ? l : largest; - if (r < arr.length) { - largest = arr[r].priority < arr[largest].priority ? r : largest; - } - if (largest !== i) { - this._swap(i, largest); - this._heapify(largest); - } - } -}; - -PriorityQueue.prototype._decrease = function(index) { - var arr = this._arr; - var priority = arr[index].priority; - var parent; - while (index !== 0) { - parent = index >> 1; - if (arr[parent].priority < priority) { - break; - } - this._swap(index, parent); - index = parent; - } -}; - -PriorityQueue.prototype._swap = function(i, j) { - var arr = this._arr; - var keyIndices = this._keyIndices; - var origArrI = arr[i]; - var origArrJ = arr[j]; - arr[i] = origArrJ; - arr[j] = origArrI; - keyIndices[origArrJ.key] = i; - keyIndices[origArrI.key] = j; -}; - -},{"../lodash":77}],74:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"); - -module.exports = Graph; - -var DEFAULT_EDGE_NAME = "\x00", - GRAPH_NODE = "\x00", - EDGE_KEY_DELIM = "\x01"; - -// Implementation notes: -// -// * Node id query functions should return string ids for the nodes -// * Edge id query functions should return an "edgeObj", edge object, that is -// composed of enough information to uniquely identify an edge: {v, w, name}. -// * Internally we use an "edgeId", a stringified form of the edgeObj, to -// reference edges. This is because we need a performant way to look these -// edges up and, object properties, which have string keys, are the closest -// we're going to get to a performant hashtable in JavaScript. - -function Graph(opts) { - this._isDirected = _.has(opts, "directed") ? opts.directed : true; - this._isMultigraph = _.has(opts, "multigraph") ? opts.multigraph : false; - this._isCompound = _.has(opts, "compound") ? opts.compound : false; - - // Label for the graph itself - this._label = undefined; - - // Defaults to be set when creating a new node - this._defaultNodeLabelFn = _.constant(undefined); - - // Defaults to be set when creating a new edge - this._defaultEdgeLabelFn = _.constant(undefined); - - // v -> label - this._nodes = {}; - - if (this._isCompound) { - // v -> parent - this._parent = {}; - - // v -> children - this._children = {}; - this._children[GRAPH_NODE] = {}; - } - - // v -> edgeObj - this._in = {}; - - // u -> v -> Number - this._preds = {}; - - // v -> edgeObj - this._out = {}; - - // v -> w -> Number - this._sucs = {}; - - // e -> edgeObj - this._edgeObjs = {}; - - // e -> label - this._edgeLabels = {}; -} - -/* Number of nodes in the graph. Should only be changed by the implementation. */ -Graph.prototype._nodeCount = 0; - -/* Number of edges in the graph. Should only be changed by the implementation. */ -Graph.prototype._edgeCount = 0; - - -/* === Graph functions ========= */ - -Graph.prototype.isDirected = function() { - return this._isDirected; -}; - -Graph.prototype.isMultigraph = function() { - return this._isMultigraph; -}; - -Graph.prototype.isCompound = function() { - return this._isCompound; -}; - -Graph.prototype.setGraph = function(label) { - this._label = label; - return this; -}; - -Graph.prototype.graph = function() { - return this._label; -}; - - -/* === Node functions ========== */ - -Graph.prototype.setDefaultNodeLabel = function(newDefault) { - if (!_.isFunction(newDefault)) { - newDefault = _.constant(newDefault); - } - this._defaultNodeLabelFn = newDefault; - return this; -}; - -Graph.prototype.nodeCount = function() { - return this._nodeCount; -}; - -Graph.prototype.nodes = function() { - return _.keys(this._nodes); -}; - -Graph.prototype.sources = function() { - return _.filter(this.nodes(), function(v) { - return _.isEmpty(this._in[v]); - }, this); -}; - -Graph.prototype.sinks = function() { - return _.filter(this.nodes(), function(v) { - return _.isEmpty(this._out[v]); - }, this); -}; - -Graph.prototype.setNodes = function(vs, value) { - var args = arguments; - _.each(vs, function(v) { - if (args.length > 1) { - this.setNode(v, value); - } else { - this.setNode(v); - } - }, this); - return this; -}; - -Graph.prototype.setNode = function(v, value) { - if (_.has(this._nodes, v)) { - if (arguments.length > 1) { - this._nodes[v] = value; - } - return this; - } - - this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); - if (this._isCompound) { - this._parent[v] = GRAPH_NODE; - this._children[v] = {}; - this._children[GRAPH_NODE][v] = true; - } - this._in[v] = {}; - this._preds[v] = {}; - this._out[v] = {}; - this._sucs[v] = {}; - ++this._nodeCount; - return this; -}; - -Graph.prototype.node = function(v) { - return this._nodes[v]; -}; - -Graph.prototype.hasNode = function(v) { - return _.has(this._nodes, v); -}; - -Graph.prototype.removeNode = function(v) { - var self = this; - if (_.has(this._nodes, v)) { - var removeEdge = function(e) { self.removeEdge(self._edgeObjs[e]); }; - delete this._nodes[v]; - if (this._isCompound) { - this._removeFromParentsChildList(v); - delete this._parent[v]; - _.each(this.children(v), function(child) { - this.setParent(child); - }, this); - delete this._children[v]; - } - _.each(_.keys(this._in[v]), removeEdge); - delete this._in[v]; - delete this._preds[v]; - _.each(_.keys(this._out[v]), removeEdge); - delete this._out[v]; - delete this._sucs[v]; - --this._nodeCount; - } - return this; -}; - -Graph.prototype.setParent = function(v, parent) { - if (!this._isCompound) { - throw new Error("Cannot set parent in a non-compound graph"); - } - - if (_.isUndefined(parent)) { - parent = GRAPH_NODE; - } else { - // Coerce parent to string - parent += ""; - for (var ancestor = parent; - !_.isUndefined(ancestor); - ancestor = this.parent(ancestor)) { - if (ancestor === v) { - throw new Error("Setting " + parent+ " as parent of " + v + - " would create create a cycle"); - } - } - - this.setNode(parent); - } - - this.setNode(v); - this._removeFromParentsChildList(v); - this._parent[v] = parent; - this._children[parent][v] = true; - return this; -}; - -Graph.prototype._removeFromParentsChildList = function(v) { - delete this._children[this._parent[v]][v]; -}; - -Graph.prototype.parent = function(v) { - if (this._isCompound) { - var parent = this._parent[v]; - if (parent !== GRAPH_NODE) { - return parent; - } - } -}; - -Graph.prototype.children = function(v) { - if (_.isUndefined(v)) { - v = GRAPH_NODE; - } - - if (this._isCompound) { - var children = this._children[v]; - if (children) { - return _.keys(children); - } - } else if (v === GRAPH_NODE) { - return this.nodes(); - } else if (this.hasNode(v)) { - return []; - } -}; - -Graph.prototype.predecessors = function(v) { - var predsV = this._preds[v]; - if (predsV) { - return _.keys(predsV); - } -}; - -Graph.prototype.successors = function(v) { - var sucsV = this._sucs[v]; - if (sucsV) { - return _.keys(sucsV); - } -}; - -Graph.prototype.neighbors = function(v) { - var preds = this.predecessors(v); - if (preds) { - return _.union(preds, this.successors(v)); - } -}; - -/* === Edge functions ========== */ - -Graph.prototype.setDefaultEdgeLabel = function(newDefault) { - if (!_.isFunction(newDefault)) { - newDefault = _.constant(newDefault); - } - this._defaultEdgeLabelFn = newDefault; - return this; -}; - -Graph.prototype.edgeCount = function() { - return this._edgeCount; -}; - -Graph.prototype.edges = function() { - return _.values(this._edgeObjs); -}; - -Graph.prototype.setPath = function(vs, value) { - var self = this, - args = arguments; - _.reduce(vs, function(v, w) { - if (args.length > 1) { - self.setEdge(v, w, value); - } else { - self.setEdge(v, w); - } - return w; - }); - return this; -}; - -/* - * setEdge(v, w, [value, [name]]) - * setEdge({ v, w, [name] }, [value]) - */ -Graph.prototype.setEdge = function() { - var v, w, name, value, - valueSpecified = false; - - if (_.isPlainObject(arguments[0])) { - v = arguments[0].v; - w = arguments[0].w; - name = arguments[0].name; - if (arguments.length === 2) { - value = arguments[1]; - valueSpecified = true; - } - } else { - v = arguments[0]; - w = arguments[1]; - name = arguments[3]; - if (arguments.length > 2) { - value = arguments[2]; - valueSpecified = true; - } - } - - v = "" + v; - w = "" + w; - if (!_.isUndefined(name)) { - name = "" + name; - } - - var e = edgeArgsToId(this._isDirected, v, w, name); - if (_.has(this._edgeLabels, e)) { - if (valueSpecified) { - this._edgeLabels[e] = value; - } - return this; - } - - if (!_.isUndefined(name) && !this._isMultigraph) { - throw new Error("Cannot set a named edge when isMultigraph = false"); - } - - // It didn't exist, so we need to create it. - // First ensure the nodes exist. - this.setNode(v); - this.setNode(w); - - this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); - - var edgeObj = edgeArgsToObj(this._isDirected, v, w, name); - // Ensure we add undirected edges in a consistent way. - v = edgeObj.v; - w = edgeObj.w; - - Object.freeze(edgeObj); - this._edgeObjs[e] = edgeObj; - incrementOrInitEntry(this._preds[w], v); - incrementOrInitEntry(this._sucs[v], w); - this._in[w][e] = edgeObj; - this._out[v][e] = edgeObj; - this._edgeCount++; - return this; -}; - -Graph.prototype.edge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)); - return this._edgeLabels[e]; -}; - -Graph.prototype.hasEdge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)); - return _.has(this._edgeLabels, e); -}; - -Graph.prototype.removeEdge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)), - edge = this._edgeObjs[e]; - if (edge) { - v = edge.v; - w = edge.w; - delete this._edgeLabels[e]; - delete this._edgeObjs[e]; - decrementOrRemoveEntry(this._preds[w], v); - decrementOrRemoveEntry(this._sucs[v], w); - delete this._in[w][e]; - delete this._out[v][e]; - this._edgeCount--; - } - return this; -}; - -Graph.prototype.inEdges = function(v, u) { - var inV = this._in[v]; - if (inV) { - var edges = _.values(inV); - if (!u) { - return edges; - } - return _.filter(edges, function(edge) { return edge.v === u; }); - } -}; - -Graph.prototype.outEdges = function(v, w) { - var outV = this._out[v]; - if (outV) { - var edges = _.values(outV); - if (!w) { - return edges; - } - return _.filter(edges, function(edge) { return edge.w === w; }); - } -}; - -Graph.prototype.nodeEdges = function(v, w) { - var inEdges = this.inEdges(v, w); - if (inEdges) { - return inEdges.concat(this.outEdges(v, w)); - } -}; - -function incrementOrInitEntry(map, k) { - if (_.has(map, k)) { - map[k]++; - } else { - map[k] = 1; - } -} - -function decrementOrRemoveEntry(map, k) { - if (!--map[k]) { delete map[k]; } -} - -function edgeArgsToId(isDirected, v, w, name) { - if (!isDirected && v > w) { - var tmp = v; - v = w; - w = tmp; - } - return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + - (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name); -} - -function edgeArgsToObj(isDirected, v, w, name) { - if (!isDirected && v > w) { - var tmp = v; - v = w; - w = tmp; - } - var edgeObj = { v: v, w: w }; - if (name) { - edgeObj.name = name; - } - return edgeObj; -} - -function edgeObjToId(isDirected, edgeObj) { - return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); -} - -},{"./lodash":77}],75:[function(require,module,exports){ -// Includes only the "core" of graphlib -module.exports = { - Graph: require("./graph"), - version: require("./version") -}; - -},{"./graph":74,"./version":78}],76:[function(require,module,exports){ -var _ = require("./lodash"), - Graph = require("./graph"); - -module.exports = { - write: write, - read: read -}; - -function write(g) { - var json = { - options: { - directed: g.isDirected(), - multigraph: g.isMultigraph(), - compound: g.isCompound() - }, - nodes: writeNodes(g), - edges: writeEdges(g) - }; - if (!_.isUndefined(g.graph())) { - json.value = _.clone(g.graph()); - } - return json; -} - -function writeNodes(g) { - return _.map(g.nodes(), function(v) { - var nodeValue = g.node(v), - parent = g.parent(v), - node = { v: v }; - if (!_.isUndefined(nodeValue)) { - node.value = nodeValue; - } - if (!_.isUndefined(parent)) { - node.parent = parent; - } - return node; - }); -} - -function writeEdges(g) { - return _.map(g.edges(), function(e) { - var edgeValue = g.edge(e), - edge = { v: e.v, w: e.w }; - if (!_.isUndefined(e.name)) { - edge.name = e.name; - } - if (!_.isUndefined(edgeValue)) { - edge.value = edgeValue; - } - return edge; - }); -} - -function read(json) { - var g = new Graph(json.options).setGraph(json.value); - _.each(json.nodes, function(entry) { - g.setNode(entry.v, entry.value); - if (entry.parent) { - g.setParent(entry.v, entry.parent); - } - }); - _.each(json.edges, function(entry) { - g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value); - }); - return g; -} - -},{"./graph":74,"./lodash":77}],77:[function(require,module,exports){ -/* global window */ - -var lodash; - -if (typeof require === "function") { - try { - lodash = require("lodash"); - } catch (e) {} -} - -if (!lodash) { - lodash = window._; -} - -module.exports = lodash; - -},{"lodash":79}],78:[function(require,module,exports){ -module.exports = '1.0.5'; - -},{}],79:[function(require,module,exports){ -(function (global){ -/** - * @license - * lodash 3.10.0 (Custom Build) - * Build: `lodash modern -d -o ./index.js` - * Copyright 2012-2015 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '3.10.0'; - - /** Used to compose bitmasks for wrapper metadata. */ - var BIND_FLAG = 1, - BIND_KEY_FLAG = 2, - CURRY_BOUND_FLAG = 4, - CURRY_FLAG = 8, - CURRY_RIGHT_FLAG = 16, - PARTIAL_FLAG = 32, - PARTIAL_RIGHT_FLAG = 64, - ARY_FLAG = 128, - REARG_FLAG = 256; - - /** Used as default options for `_.trunc`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect when a function becomes hot. */ - var HOT_COUNT = 150, - HOT_SPAN = 16; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2; - - /** Used as the `TypeError` message for "Functions" methods. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, - reUnescapedHtml = /[&<>"'`]/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; - - /** - * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns) - * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern). - */ - var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g, - reHasRegExpChars = RegExp(reRegExpChars.source); - - /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ - var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect hexadecimal string values. */ - var reHasHexPrefix = /^0[xX]/; - - /** Used to detect host constructors (Safari > 5). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^\d+$/; - - /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ - var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to match words to create compound words. */ - var reWords = (function() { - var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', - lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; - - return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); - }()); - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', - 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite', - 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dateTag] = typedArrayTags[errorTag] = - typedArrayTags[funcTag] = typedArrayTags[mapTag] = - typedArrayTags[numberTag] = typedArrayTags[objectTag] = - typedArrayTags[regexpTag] = typedArrayTags[setTag] = - typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = - cloneableTags[dateTag] = cloneableTags[float32Tag] = - cloneableTags[float64Tag] = cloneableTags[int8Tag] = - cloneableTags[int16Tag] = cloneableTags[int32Tag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[stringTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[mapTag] = cloneableTags[setTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map latin-1 supplementary letters to basic latin letters. */ - var deburredLetters = { - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '`': '`' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'", - '`': '`' - }; - - /** Used to determine if values are of the language type `Object`. */ - var objectTypes = { - 'function': true, - 'object': true - }; - - /** Used to escape characters for inclusion in compiled regexes. */ - var regexpEscapes = { - '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34', - '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39', - 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46', - 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66', - 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78' - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Detect free variable `exports`. */ - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; - - /** Detect free variable `self`. */ - var freeSelf = objectTypes[typeof self] && self && self.Object && self; - - /** Detect free variable `window`. */ - var freeWindow = objectTypes[typeof window] && window && window.Object && window; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; - - /** - * Used as a reference to the global object. - * - * The `this` value is used if it's the global object to avoid Greasemonkey's - * restricted `window` object, otherwise the `window` object is used. - */ - var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; - - /*--------------------------------------------------------------------------*/ - - /** - * The base implementation of `compareAscending` which compares values and - * sorts them in ascending order without guaranteeing a stable sort. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function baseCompareAscending(value, other) { - if (value !== other) { - var valIsNull = value === null, - valIsUndef = value === undefined, - valIsReflexive = value === value; - - var othIsNull = other === null, - othIsUndef = other === undefined, - othIsReflexive = other === other; - - if ((value > other && !othIsNull) || !valIsReflexive || - (valIsNull && !othIsUndef && othIsReflexive) || - (valIsUndef && othIsReflexive)) { - return 1; - } - if ((value < other && !valIsNull) || !othIsReflexive || - (othIsNull && !valIsUndef && valIsReflexive) || - (othIsUndef && valIsReflexive)) { - return -1; - } - } - return 0; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to search. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without support for binary searches. - * - * @private - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return indexOfNaN(array, fromIndex); - } - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isFunction` without support for environments - * with incorrect `typeof` results. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - */ - function baseIsFunction(value) { - // Avoid a Chakra JIT bug in compatibility modes of IE 11. - // See https://github.com/jashkenas/underscore/issues/1621 for more details. - return typeof value == 'function' || false; - } - - /** - * Converts `value` to a string if it's not one. An empty string is returned - * for `null` or `undefined` values. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - return value == null ? '' : (value + ''); - } - - /** - * Used by `_.trim` and `_.trimLeft` to get the index of the first character - * of `string` that is not found in `chars`. - * - * @private - * @param {string} string The string to inspect. - * @param {string} chars The characters to find. - * @returns {number} Returns the index of the first character not found in `chars`. - */ - function charsLeftIndex(string, chars) { - var index = -1, - length = string.length; - - while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimRight` to get the index of the last character - * of `string` that is not found in `chars`. - * - * @private - * @param {string} string The string to inspect. - * @param {string} chars The characters to find. - * @returns {number} Returns the index of the last character not found in `chars`. - */ - function charsRightIndex(string, chars) { - var index = string.length; - - while (index-- && chars.indexOf(string.charAt(index)) > -1) {} - return index; - } - - /** - * Used by `_.sortBy` to compare transformed elements of a collection and stable - * sort them in ascending order. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareAscending(object, other) { - return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); - } - - /** - * Used by `_.sortByOrder` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise, - * a value is sorted in ascending order if its corresponding order is "asc", and - * descending if "desc". - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = baseCompareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * ((order === 'asc' || order === true) ? 1 : -1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://code.google.com/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - function deburrLetter(letter) { - return deburredLetters[letter]; - } - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeHtmlChar(chr) { - return htmlEscapes[chr]; - } - - /** - * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes. - * - * @private - * @param {string} chr The matched character to escape. - * @param {string} leadingChar The capture group for a leading character. - * @param {string} whitespaceChar The capture group for a whitespace character. - * @returns {string} Returns the escaped character. - */ - function escapeRegExpChar(chr, leadingChar, whitespaceChar) { - if (leadingChar) { - chr = regexpEscapes[chr]; - } else if (whitespaceChar) { - chr = stringEscapes[chr]; - } - return '\\' + chr; - } - - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** - * Gets the index at which the first occurrence of `NaN` is found in `array`. - * - * @private - * @param {Array} array The array to search. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched `NaN`, else `-1`. - */ - function indexOfNaN(array, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 0 : -1); - - while ((fromRight ? index-- : ++index < length)) { - var other = array[index]; - if (other !== other) { - return index; - } - } - return -1; - } - - /** - * Checks if `value` is object-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a - * character code is whitespace. - * - * @private - * @param {number} charCode The character code to inspect. - * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. - */ - function isSpace(charCode) { - return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || - (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); - } - - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = -1, - result = []; - - while (++index < length) { - if (array[index] === placeholder) { - array[index] = PLACEHOLDER; - result[++resIndex] = index; - } - } - return result; - } - - /** - * An implementation of `_.uniq` optimized for sorted arrays without support - * for callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The function invoked per iteration. - * @returns {Array} Returns the new duplicate-value-free array. - */ - function sortedUniq(array, iteratee) { - var seen, - index = -1, - length = array.length, - resIndex = -1, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value, index, array) : value; - - if (!index || seen !== computed) { - seen = computed; - result[++resIndex] = value; - } - } - return result; - } - - /** - * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the first non-whitespace character. - */ - function trimmedLeftIndex(string) { - var index = -1, - length = string.length; - - while (++index < length && isSpace(string.charCodeAt(index))) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedRightIndex(string) { - var index = string.length; - - while (index-- && isSpace(string.charCodeAt(index))) {} - return index; - } - - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - function unescapeHtmlChar(chr) { - return htmlUnescapes[chr]; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new pristine `lodash` function using the given `context` object. - * - * @static - * @memberOf _ - * @category Utility - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // using `context` to mock `Date#getTime` use in `_.now` - * var mock = _.runInContext({ - * 'Date': function() { - * return { 'getTime': getTimeMock }; - * } - * }); - * - * // or creating a suped-up `defer` in Node.js - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - function runInContext(context) { - // Avoid issues with some ES3 environments that attempt to use values, named - // after built-in constructors like `Object`, for the creation of literals. - // ES5 clears this up by stating that literals must use built-in constructors. - // See https://es5.github.io/#x11.1.5 for more details. - context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; - - /** Native constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Number = context.Number, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** Used for native method references. */ - var arrayProto = Array.prototype, - objectProto = Object.prototype, - stringProto = String.prototype; - - /** Used to resolve the decompiled source of functions. */ - var fnToString = Function.prototype.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Native method references. */ - var ArrayBuffer = context.ArrayBuffer, - clearTimeout = context.clearTimeout, - parseFloat = context.parseFloat, - pow = Math.pow, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - Set = getNative(context, 'Set'), - setTimeout = context.setTimeout, - splice = arrayProto.splice, - Uint8Array = context.Uint8Array, - WeakMap = getNative(context, 'WeakMap'); - - /* Native method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeCreate = getNative(Object, 'create'), - nativeFloor = Math.floor, - nativeIsArray = getNative(Array, 'isArray'), - nativeIsFinite = context.isFinite, - nativeKeys = getNative(Object, 'keys'), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = getNative(Date, 'now'), - nativeParseInt = context.parseInt, - nativeRandom = Math.random; - - /** Used as references for `-Infinity` and `Infinity`. */ - var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, - POSITIVE_INFINITY = Number.POSITIVE_INFINITY; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** - * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) - * of an array-like value. - */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - - /** Used to lookup unminified function names. */ - var realNames = {}; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit chaining. - * Methods that operate on and return arrays, collections, and functions can - * be chained together. Methods that retrieve a single value or may return a - * primitive value will automatically end the chain returning the unwrapped - * value. Explicit chaining may be enabled using `_.chain`. The execution of - * chained methods is lazy, that is, execution is deferred until `_#value` - * is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. Shortcut - * fusion is an optimization strategy which merge iteratee calls; this can help - * to avoid the creation of intermediate data structures and greatly reduce the - * number of iteratee executions. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, - * `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, - * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, - * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, - * and `where` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, - * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, - * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`, - * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`, - * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, - * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, - * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, - * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, - * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`, - * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, - * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, - * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`, - * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, - * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`, - * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, - * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`, - * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`, - * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, - * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, - * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, - * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, - * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`, - * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`, - * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`, - * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`, - * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`, - * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, - * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, - * `unescape`, `uniqueId`, `value`, and `words` - * - * The wrapper method `sample` will return a wrapped value when `n` is provided, - * otherwise an unwrapped value is returned. - * - * @name _ - * @constructor - * @category Chain - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var wrapped = _([1, 2, 3]); - * - * // returns an unwrapped value - * wrapped.reduce(function(total, n) { - * return total + n; - * }); - * // => 6 - * - * // returns a wrapped value - * var squares = wrapped.map(function(n) { - * return n * n; - * }); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The function whose prototype all chaining wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable chaining for all wrapper methods. - * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. - */ - function LodashWrapper(value, chainAll, actions) { - this.__wrapped__ = value; - this.__actions__ = actions || []; - this.__chain__ = !!chainAll; - } - - /** - * An object environment feature flags. - * - * @static - * @memberOf _ - * @type Object - */ - var support = lodash.support = {}; - - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB). Change the following template settings to use - * alternative delimiters. - * - * @static - * @memberOf _ - * @type Object - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'escape': reEscape, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'evaluate': reEvaluate, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type string - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type Object - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type Function - */ - '_': lodash - } - }; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = POSITIVE_INFINITY; - this.__views__ = []; - } - - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = arrayCopy(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = arrayCopy(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = arrayCopy(this.__views__); - return result; - } - - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); - - if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) { - return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__); - } - var result = []; - - outer: - while (length-- && resIndex < takeCount) { - index += dir; - - var iterIndex = -1, - value = array[index]; - - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a cache object to store key/value pairs. - * - * @private - * @static - * @name Cache - * @memberOf _.memoize - */ - function MapCache() { - this.__data__ = {}; - } - - /** - * Removes `key` and its value from the cache. - * - * @private - * @name delete - * @memberOf _.memoize.Cache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. - */ - function mapDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the cached value for `key`. - * - * @private - * @name get - * @memberOf _.memoize.Cache - * @param {string} key The key of the value to get. - * @returns {*} Returns the cached value. - */ - function mapGet(key) { - return key == '__proto__' ? undefined : this.__data__[key]; - } - - /** - * Checks if a cached value for `key` exists. - * - * @private - * @name has - * @memberOf _.memoize.Cache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapHas(key) { - return key != '__proto__' && hasOwnProperty.call(this.__data__, key); - } - - /** - * Sets `value` to `key` of the cache. - * - * @private - * @name set - * @memberOf _.memoize.Cache - * @param {string} key The key of the value to cache. - * @param {*} value The value to cache. - * @returns {Object} Returns the cache object. - */ - function mapSet(key, value) { - if (key != '__proto__') { - this.__data__[key] = value; - } - return this; - } - - /*------------------------------------------------------------------------*/ - - /** - * - * Creates a cache object to store unique values. - * - * @private - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var length = values ? values.length : 0; - - this.data = { 'hash': nativeCreate(null), 'set': new Set }; - while (length--) { - this.push(values[length]); - } - } - - /** - * Checks if `value` is in `cache` mimicking the return signature of - * `_.indexOf` by returning `0` if the value is found, else `-1`. - * - * @private - * @param {Object} cache The cache to search. - * @param {*} value The value to search for. - * @returns {number} Returns `0` if `value` is found, else `-1`. - */ - function cacheIndexOf(cache, value) { - var data = cache.data, - result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; - - return result ? 0 : -1; - } - - /** - * Adds `value` to the cache. - * - * @private - * @name push - * @memberOf SetCache - * @param {*} value The value to cache. - */ - function cachePush(value) { - var data = this.data; - if (typeof value == 'string' || isObject(value)) { - data.set.add(value); - } else { - data.hash[value] = true; - } - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a new array joining `array` with `other`. - * - * @private - * @param {Array} array The array to join. - * @param {Array} other The other array to join. - * @returns {Array} Returns the new concatenated array. - */ - function arrayConcat(array, other) { - var index = -1, - length = array.length, - othIndex = -1, - othLength = other.length, - result = Array(length + othLength); - - while (++index < length) { - result[index] = array[index]; - } - while (++othIndex < othLength) { - result[index++] = other[othIndex]; - } - return result; - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function arrayCopy(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * A specialized version of `_.forEach` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array.length; - - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.every` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - - /** - * A specialized version of `baseExtremum` for arrays which invokes `iteratee` - * with one argument: (value). - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} comparator The function used to compare values. - * @param {*} exValue The initial extremum value. - * @returns {*} Returns the extremum value. - */ - function arrayExtremum(array, iteratee, comparator, exValue) { - var index = -1, - length = array.length, - computed = exValue, - result = computed; - - while (++index < length) { - var value = array[index], - current = +iteratee(value); - - if (comparator(current, computed)) { - computed = current; - result = value; - } - } - return result; - } - - /** - * A specialized version of `_.filter` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array.length, - resIndex = -1, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[++resIndex] = value; - } - } - return result; - } - - /** - * A specialized version of `_.map` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initFromArray] Specify using the first element of `array` - * as the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initFromArray) { - var index = -1, - length = array.length; - - if (initFromArray && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * A specialized version of `_.reduceRight` for arrays without support for - * callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initFromArray] Specify using the last element of `array` - * as the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initFromArray) { - var length = array.length; - if (initFromArray && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - - /** - * A specialized version of `_.some` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * A specialized version of `_.sum` for arrays without support for callback - * shorthands and `this` binding.. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function arraySum(array, iteratee) { - var length = array.length, - result = 0; - - while (length--) { - result += +iteratee(array[length]) || 0; - } - return result; - } - - /** - * Used by `_.defaults` to customize its `_.assign` use. - * - * @private - * @param {*} objectValue The destination object property value. - * @param {*} sourceValue The source object property value. - * @returns {*} Returns the value to assign to the destination object. - */ - function assignDefaults(objectValue, sourceValue) { - return objectValue === undefined ? sourceValue : objectValue; - } - - /** - * Used by `_.template` to customize its `_.assign` use. - * - * **Note:** This function is like `assignDefaults` except that it ignores - * inherited property values when checking if a property is `undefined`. - * - * @private - * @param {*} objectValue The destination object property value. - * @param {*} sourceValue The source object property value. - * @param {string} key The key associated with the object and source values. - * @param {Object} object The destination object. - * @returns {*} Returns the value to assign to the destination object. - */ - function assignOwnDefaults(objectValue, sourceValue, key, object) { - return (objectValue === undefined || !hasOwnProperty.call(object, key)) - ? sourceValue - : objectValue; - } - - /** - * A specialized version of `_.assign` for customizing assigned values without - * support for argument juggling, multiple sources, and `this` binding `customizer` - * functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - */ - function assignWith(object, source, customizer) { - var index = -1, - props = keys(source), - length = props.length; - - while (++index < length) { - var key = props[index], - value = object[key], - result = customizer(value, source[key], key, object, source); - - if ((result === result ? (result !== value) : (value === value)) || - (value === undefined && !(key in object))) { - object[key] = result; - } - } - return object; - } - - /** - * The base implementation of `_.assign` without support for argument juggling, - * multiple sources, and `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return source == null - ? object - : baseCopy(source, keys(source), object); - } - - /** - * The base implementation of `_.at` without support for string collections - * and individual key arguments. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {number[]|string[]} props The property names or indexes of elements to pick. - * @returns {Array} Returns the new array of picked elements. - */ - function baseAt(collection, props) { - var index = -1, - isNil = collection == null, - isArr = !isNil && isArrayLike(collection), - length = isArr ? collection.length : 0, - propsLength = props.length, - result = Array(propsLength); - - while(++index < propsLength) { - var key = props[index]; - if (isArr) { - result[index] = isIndex(key, length) ? collection[key] : undefined; - } else { - result[index] = isNil ? undefined : collection[key]; - } - } - return result; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property names to copy. - * @param {Object} [object={}] The object to copy properties to. - * @returns {Object} Returns `object`. - */ - function baseCopy(source, props, object) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - object[key] = source[key]; - } - return object; - } - - /** - * The base implementation of `_.callback` which supports specifying the - * number of arguments to provide to `func`. - * - * @private - * @param {*} [func=_.identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ - function baseCallback(func, thisArg, argCount) { - var type = typeof func; - if (type == 'function') { - return thisArg === undefined - ? func - : bindCallback(func, thisArg, argCount); - } - if (func == null) { - return identity; - } - if (type == 'object') { - return baseMatches(func); - } - return thisArg === undefined - ? property(func) - : baseMatchesProperty(func, thisArg); - } - - /** - * The base implementation of `_.clone` without support for argument juggling - * and `this` binding `customizer` functions. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The object `value` belongs to. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { - var result; - if (customizer) { - result = object ? customizer(value, key, object) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return arrayCopy(value, result); - } - } else { - var tag = objToString.call(value), - isFunc = tag == funcTag; - - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return baseAssign(result, value); - } - } else { - return cloneableTags[tag] - ? initCloneByTag(value, tag, isDeep) - : (object ? value : {}); - } - } - // Check for circular references and return its corresponding clone. - stackA || (stackA = []); - stackB || (stackB = []); - - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - // Add the source value to the stack of traversed objects and associate it with its clone. - stackA.push(value); - stackB.push(result); - - // Recursively populate clone (susceptible to call stack limits). - (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { - result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(prototype) { - if (isObject(prototype)) { - object.prototype = prototype; - var result = new object; - object.prototype = undefined; - } - return result || {}; - }; - }()); - - /** - * The base implementation of `_.delay` and `_.defer` which accepts an index - * of where to slice the arguments to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Object} args The arguments provide to `func`. - * @returns {number} Returns the timer id. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of `_.difference` which accepts a single array - * of values to exclude. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values) { - var length = array ? array.length : 0, - result = []; - - if (!length) { - return result; - } - var index = -1, - indexOf = getIndexOf(), - isCommon = indexOf == baseIndexOf, - cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null, - valuesLength = values.length; - - if (cache) { - indexOf = cacheIndexOf; - isCommon = false; - values = cache; - } - outer: - while (++index < length) { - var value = array[index]; - - if (isCommon && value === value) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === value) { - continue outer; - } - } - result.push(value); - } - else if (indexOf(values, value, 0) < 0) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object|string} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object|string} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * Gets the extremum value of `collection` invoking `iteratee` for each value - * in `collection` to generate the criterion by which the value is ranked. - * The `iteratee` is invoked with three arguments: (value, index|key, collection). - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} comparator The function used to compare values. - * @param {*} exValue The initial extremum value. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(collection, iteratee, comparator, exValue) { - var computed = exValue, - result = computed; - - baseEach(collection, function(value, index, collection) { - var current = +iteratee(value, index, collection); - if (comparator(current, computed) || (current === exValue && current === result)) { - computed = current; - result = value; - } - }); - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = start == null ? 0 : (+start || 0); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : (+end || 0); - if (end < 0) { - end += length; - } - length = start > end ? 0 : (end >>> 0); - start >>>= 0; - - while (start < length) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, - * without support for callback shorthands and `this` binding, which iterates - * over `collection` using the provided `eachFunc`. - * - * @private - * @param {Array|Object|string} collection The collection to search. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @param {boolean} [retKey] Specify returning the key of the found element - * instead of the element itself. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFind(collection, predicate, eachFunc, retKey) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = retKey ? key : value; - return false; - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with added support for restricting - * flattening and specifying the start index. - * - * @private - * @param {Array} array The array to flatten. - * @param {boolean} [isDeep] Specify a deep flatten. - * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, isDeep, isStrict, result) { - result || (result = []); - - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index]; - if (isObjectLike(value) && isArrayLike(value) && - (isStrict || isArray(value) || isArguments(value))) { - if (isDeep) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, isDeep, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForIn` and `baseForOwn` which iterates - * over `object` properties returned by `keysFunc` invoking `iteratee` for - * each property. Iteratee functions may exit iteration early by explicitly - * returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forIn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForIn(object, iteratee) { - return baseFor(object, iteratee, keysIn); - } - - /** - * The base implementation of `_.forOwn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from those provided. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the new array of filtered property names. - */ - function baseFunctions(object, props) { - var index = -1, - length = props.length, - resIndex = -1, - result = []; - - while (++index < length) { - var key = props[index]; - if (isFunction(object[key])) { - result[++resIndex] = key; - } - } - return result; - } - - /** - * The base implementation of `get` without support for string paths - * and default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path of the property to get. - * @param {string} [pathKey] The key representation of path. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path, pathKey) { - if (object == null) { - return; - } - if (pathKey !== undefined && pathKey in toObject(object)) { - path = [pathKey]; - } - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[path[index++]]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `_.isEqual` without support for `this` binding - * `customizer` functions. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing objects. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA=[]] Tracks traversed `value` objects. - * @param {Array} [stackB=[]] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = arrayTag, - othTag = arrayTag; - - if (!objIsArr) { - objTag = objToString.call(object); - if (objTag == argsTag) { - objTag = objectTag; - } else if (objTag != objectTag) { - objIsArr = isTypedArray(object); - } - } - if (!othIsArr) { - othTag = objToString.call(other); - if (othTag == argsTag) { - othTag = objectTag; - } else if (othTag != objectTag) { - othIsArr = isTypedArray(other); - } - } - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && !(objIsArr || objIsObj)) { - return equalByTag(object, other, objTag); - } - if (!isLoose) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); - } - } - if (!isSameTag) { - return false; - } - // Assume cyclic values are equal. - // For more information on detecting circular references see https://es5.github.io/#JO. - stackA || (stackA = []); - stackB || (stackB = []); - - var length = stackA.length; - while (length--) { - if (stackA[length] == object) { - return stackB[length] == other; - } - } - // Add `object` and `other` to the stack of traversed objects. - stackA.push(object); - stackB.push(other); - - var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); - - stackA.pop(); - stackB.pop(); - - return result; - } - - /** - * The base implementation of `_.isMatch` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} matchData The propery names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparing objects. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = toObject(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var result = customizer ? customizer(objValue, srcValue, key) : undefined; - if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.map` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - /** - * The base implementation of `_.matches` which does not clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - var key = matchData[0][0], - value = matchData[0][1]; - - return function(object) { - if (object == null) { - return false; - } - return object[key] === value && (value !== undefined || (key in toObject(object))); - }; - } - return function(object) { - return baseIsMatch(object, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which does not clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to compare. - * @returns {Function} Returns the new function. - */ - function baseMatchesProperty(path, srcValue) { - var isArr = isArray(path), - isCommon = isKey(path) && isStrictComparable(srcValue), - pathKey = (path + ''); - - path = toPath(path); - return function(object) { - if (object == null) { - return false; - } - var key = pathKey; - object = toObject(object); - if ((isArr || !isCommon) && !(key in object)) { - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - if (object == null) { - return false; - } - key = last(path); - object = toObject(object); - } - return object[key] === srcValue - ? (srcValue !== undefined || (key in object)) - : baseIsEqual(srcValue, object[key], undefined, true); - }; - } - - /** - * The base implementation of `_.merge` without support for argument juggling, - * multiple sources, and `this` binding `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} [customizer] The function to customize merged values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {Object} Returns `object`. - */ - function baseMerge(object, source, customizer, stackA, stackB) { - if (!isObject(object)) { - return object; - } - var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), - props = isSrcArr ? undefined : keys(source); - - arrayEach(props || source, function(srcValue, key) { - if (props) { - key = srcValue; - srcValue = source[key]; - } - if (isObjectLike(srcValue)) { - stackA || (stackA = []); - stackB || (stackB = []); - baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); - } - else { - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = result === undefined; - - if (isCommon) { - result = srcValue; - } - if ((result !== undefined || (isSrcArr && !(key in object))) && - (isCommon || (result === result ? (result !== value) : (value === value)))) { - object[key] = result; - } - } - }); - return object; - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize merged values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { - var length = stackA.length, - srcValue = source[key]; - - while (length--) { - if (stackA[length] == srcValue) { - object[key] = stackB[length]; - return; - } - } - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = result === undefined; - - if (isCommon) { - result = srcValue; - if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { - result = isArray(value) - ? value - : (isArrayLike(value) ? arrayCopy(value) : []); - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - result = isArguments(value) - ? toPlainObject(value) - : (isPlainObject(value) ? value : {}); - } - else { - isCommon = false; - } - } - // Add the source value to the stack of traversed objects and associate - // it with its merged value. - stackA.push(srcValue); - stackB.push(result); - - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); - } else if (result === result ? (result !== value) : (value === value)) { - object[key] = result; - } - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new function. - */ - function basePropertyDeep(path) { - var pathKey = (path + ''); - path = toPath(path); - return function(object) { - return baseGet(object, path, pathKey); - }; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * index arguments and capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0; - while (length--) { - var index = indexes[length]; - if (index != previous && isIndex(index)) { - var previous = index; - splice.call(array, index, 1); - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for argument juggling - * and returning floating-point numbers. - * - * @private - * @param {number} min The minimum possible value. - * @param {number} max The maximum possible value. - * @returns {number} Returns the random number. - */ - function baseRandom(min, max) { - return min + nativeFloor(nativeRandom() * (max - min + 1)); - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight` without support - * for callback shorthands and `this` binding, which iterates over `collection` - * using the provided `eachFunc`. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initFromCollection Specify using the first or last element - * of `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initFromCollection - ? (initFromCollection = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `setData` without support for hot loop detection. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - start = start == null ? 0 : (+start || 0); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : (+end || 0); - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * The base implementation of `_.some` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortBy` which uses `comparer` to define - * the sort order of `array` and replaces criteria objects with their - * corresponding values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - - /** - * The base implementation of `_.sortByOrder` without param guards. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {boolean[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseSortByOrder(collection, iteratees, orders) { - var callback = getCallback(), - index = -1; - - iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); - - var result = baseMap(collection, function(value) { - var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.sum` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(collection, iteratee) { - var result = 0; - baseEach(collection, function(value, index, collection) { - result += +iteratee(value, index, collection) || 0; - }); - return result; - } - - /** - * The base implementation of `_.uniq` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The function invoked per iteration. - * @returns {Array} Returns the new duplicate-value-free array. - */ - function baseUniq(array, iteratee) { - var index = -1, - indexOf = getIndexOf(), - length = array.length, - isCommon = indexOf == baseIndexOf, - isLarge = isCommon && length >= LARGE_ARRAY_SIZE, - seen = isLarge ? createCache() : null, - result = []; - - if (seen) { - indexOf = cacheIndexOf; - isCommon = false; - } else { - isLarge = false; - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value, index, array) : value; - - if (isCommon && value === value) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (indexOf(seen, computed, 0) < 0) { - if (iteratee || isLarge) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - var index = -1, - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; - } - - /** - * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`, - * and `_.takeWhile` without support for callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to peform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - var index = -1, - length = actions.length; - - while (++index < length) { - var action = actions[index]; - result = action.func.apply(action.thisArg, arrayPush([result], action.args)); - } - return result; - } - - /** - * Performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function binaryIndex(array, value, retHighest) { - var low = 0, - high = array ? array.length : low; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return binaryIndexBy(array, value, identity, retHighest); - } - - /** - * This function is like `binaryIndex` except that it invokes `iteratee` for - * `value` and each element of `array` to compute their sort ranking. The - * iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The function invoked per iteration. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function binaryIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); - - var low = 0, - high = array ? array.length : 0, - valIsNaN = value !== value, - valIsNull = value === null, - valIsUndef = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - isDef = computed !== undefined, - isReflexive = computed === computed; - - if (valIsNaN) { - var setLow = isReflexive || retHighest; - } else if (valIsNull) { - setLow = isReflexive && isDef && (retHighest || computed != null); - } else if (valIsUndef) { - setLow = isReflexive && (retHighest || isDef); - } else if (computed == null) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * A specialized version of `baseCallback` which only supports `this` binding - * and specifying the number of arguments to provide to `func`. - * - * @private - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ - function bindCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - if (thisArg === undefined) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - case 5: return function(value, other, key, object, source) { - return func.call(thisArg, value, other, key, object, source); - }; - } - return function() { - return func.apply(thisArg, arguments); - }; - } - - /** - * Creates a clone of the given array buffer. - * - * @private - * @param {ArrayBuffer} buffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function bufferClone(buffer) { - var result = new ArrayBuffer(buffer.byteLength), - view = new Uint8Array(result); - - view.set(new Uint8Array(buffer)); - return result; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array|Object} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders) { - var holdersLength = holders.length, - argsIndex = -1, - argsLength = nativeMax(args.length - holdersLength, 0), - leftIndex = -1, - leftLength = partials.length, - result = Array(leftLength + argsLength); - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - while (argsLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array|Object} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders) { - var holdersIndex = -1, - holdersLength = holders.length, - argsIndex = -1, - argsLength = nativeMax(args.length - holdersLength, 0), - rightIndex = -1, - rightLength = partials.length, - result = Array(argsLength + rightLength); - - while (++argsIndex < argsLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - return result; - } - - /** - * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function. - * - * @private - * @param {Function} setter The function to set keys and values of the accumulator object. - * @param {Function} [initializer] The function to initialize the accumulator object. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee, thisArg) { - var result = initializer ? initializer() : {}; - iteratee = getCallback(iteratee, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - setter(result, value, iteratee(value, index, collection), collection); - } - } else { - baseEach(collection, function(value, key, collection) { - setter(result, value, iteratee(value, key, collection), collection); - }); - } - return result; - }; - } - - /** - * Creates a `_.assign`, `_.defaults`, or `_.merge` function. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return restParam(function(object, sources) { - var index = -1, - length = object == null ? 0 : sources.length, - customizer = length > 2 ? sources[length - 2] : undefined, - guard = length > 2 ? sources[2] : undefined, - thisArg = length > 1 ? sources[length - 1] : undefined; - - if (typeof customizer == 'function') { - customizer = bindCallback(customizer, thisArg, 5); - length -= 2; - } else { - customizer = typeof thisArg == 'function' ? thisArg : undefined; - length -= (customizer ? 1 : 0); - } - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - var length = collection ? getLength(collection) : 0; - if (!isLength(length)) { - return eachFunc(collection, iteratee); - } - var index = fromRight ? length : -1, - iterable = toObject(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for `_.forIn` or `_.forInRight`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var iterable = toObject(object), - props = keysFunc(object), - length = props.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length)) { - var key = props[index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` and invokes it with the `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to bind. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new bound function. - */ - function createBindWrapper(func, thisArg) { - var Ctor = createCtorWrapper(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(thisArg, arguments); - } - return wrapper; - } - - /** - * Creates a `Set` cache object to optimize linear searches of large arrays. - * - * @private - * @param {Array} [values] The values to cache. - * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. - */ - function createCache(values) { - return (nativeCreate && Set) ? new SetCache(values) : null; - } - - /** - * Creates a function that produces compound words out of the words in a - * given string. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - var index = -1, - array = words(deburr(string)), - length = array.length, - result = ''; - - while (++index < length) { - result = callback(result, array[index], index); - } - return result; - }; - } - - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtorWrapper(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. - // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a `_.curry` or `_.curryRight` function. - * - * @private - * @param {boolean} flag The curry bit flag. - * @returns {Function} Returns the new curry function. - */ - function createCurry(flag) { - function curryFunc(func, arity, guard) { - if (guard && isIterateeCall(func, arity, guard)) { - arity = undefined; - } - var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryFunc.placeholder; - return result; - } - return curryFunc; - } - - /** - * Creates a `_.defaults` or `_.defaultsDeep` function. - * - * @private - * @param {Function} assigner The function to assign values. - * @param {Function} customizer The function to customize assigned values. - * @returns {Function} Returns the new defaults function. - */ - function createDefaults(assigner, customizer) { - return restParam(function(args) { - var object = args[0]; - if (object == null) { - return object; - } - args.push(customizer); - return assigner.apply(undefined, args); - }); - } - - /** - * Creates a `_.max` or `_.min` function. - * - * @private - * @param {Function} comparator The function used to compare values. - * @param {*} exValue The initial extremum value. - * @returns {Function} Returns the new extremum function. - */ - function createExtremum(comparator, exValue) { - return function(collection, iteratee, thisArg) { - if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { - iteratee = undefined; - } - iteratee = getCallback(iteratee, thisArg, 3); - if (iteratee.length == 1) { - collection = isArray(collection) ? collection : toIterable(collection); - var result = arrayExtremum(collection, iteratee, comparator, exValue); - if (!(collection.length && result === exValue)) { - return result; - } - } - return baseExtremum(collection, iteratee, comparator, exValue); - }; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new find function. - */ - function createFind(eachFunc, fromRight) { - return function(collection, predicate, thisArg) { - predicate = getCallback(predicate, thisArg, 3); - if (isArray(collection)) { - var index = baseFindIndex(collection, predicate, fromRight); - return index > -1 ? collection[index] : undefined; - } - return baseFind(collection, predicate, eachFunc); - }; - } - - /** - * Creates a `_.findIndex` or `_.findLastIndex` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new find function. - */ - function createFindIndex(fromRight) { - return function(array, predicate, thisArg) { - if (!(array && array.length)) { - return -1; - } - predicate = getCallback(predicate, thisArg, 3); - return baseFindIndex(array, predicate, fromRight); - }; - } - - /** - * Creates a `_.findKey` or `_.findLastKey` function. - * - * @private - * @param {Function} objectFunc The function to iterate over an object. - * @returns {Function} Returns the new find function. - */ - function createFindKey(objectFunc) { - return function(object, predicate, thisArg) { - predicate = getCallback(predicate, thisArg, 3); - return baseFind(object, predicate, objectFunc, true); - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return function() { - var wrapper, - length = arguments.length, - index = fromRight ? length : -1, - leftIndex = 0, - funcs = Array(length); - - while ((fromRight ? index-- : ++index < length)) { - var func = funcs[leftIndex++] = arguments[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') { - wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? -1 : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }; - } - - /** - * Creates a function for `_.forEach` or `_.forEachRight`. - * - * @private - * @param {Function} arrayFunc The function to iterate over an array. - * @param {Function} eachFunc The function to iterate over a collection. - * @returns {Function} Returns the new each function. - */ - function createForEach(arrayFunc, eachFunc) { - return function(collection, iteratee, thisArg) { - return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) - ? arrayFunc(collection, iteratee) - : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); - }; - } - - /** - * Creates a function for `_.forIn` or `_.forInRight`. - * - * @private - * @param {Function} objectFunc The function to iterate over an object. - * @returns {Function} Returns the new each function. - */ - function createForIn(objectFunc) { - return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || thisArg !== undefined) { - iteratee = bindCallback(iteratee, thisArg, 3); - } - return objectFunc(object, iteratee, keysIn); - }; - } - - /** - * Creates a function for `_.forOwn` or `_.forOwnRight`. - * - * @private - * @param {Function} objectFunc The function to iterate over an object. - * @returns {Function} Returns the new each function. - */ - function createForOwn(objectFunc) { - return function(object, iteratee, thisArg) { - if (typeof iteratee != 'function' || thisArg !== undefined) { - iteratee = bindCallback(iteratee, thisArg, 3); - } - return objectFunc(object, iteratee); - }; - } - - /** - * Creates a function for `_.mapKeys` or `_.mapValues`. - * - * @private - * @param {boolean} [isMapKeys] Specify mapping keys instead of values. - * @returns {Function} Returns the new map function. - */ - function createObjectMapper(isMapKeys) { - return function(object, iteratee, thisArg) { - var result = {}; - iteratee = getCallback(iteratee, thisArg, 3); - - baseForOwn(object, function(value, key, object) { - var mapped = iteratee(value, key, object); - key = isMapKeys ? mapped : key; - value = isMapKeys ? value : mapped; - result[key] = value; - }); - return result; - }; - } - - /** - * Creates a function for `_.padLeft` or `_.padRight`. - * - * @private - * @param {boolean} [fromRight] Specify padding from the right. - * @returns {Function} Returns the new pad function. - */ - function createPadDir(fromRight) { - return function(string, length, chars) { - string = baseToString(string); - return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string); - }; - } - - /** - * Creates a `_.partial` or `_.partialRight` function. - * - * @private - * @param {boolean} flag The partial bit flag. - * @returns {Function} Returns the new partial function. - */ - function createPartial(flag) { - var partialFunc = restParam(function(func, partials) { - var holders = replaceHolders(partials, partialFunc.placeholder); - return createWrapper(func, flag, undefined, partials, holders); - }); - return partialFunc; - } - - /** - * Creates a function for `_.reduce` or `_.reduceRight`. - * - * @private - * @param {Function} arrayFunc The function to iterate over an array. - * @param {Function} eachFunc The function to iterate over a collection. - * @returns {Function} Returns the new each function. - */ - function createReduce(arrayFunc, eachFunc) { - return function(collection, iteratee, accumulator, thisArg) { - var initFromArray = arguments.length < 3; - return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) - ? arrayFunc(collection, iteratee, accumulator, initFromArray) - : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); - }; - } - - /** - * Creates a function that wraps `func` and invokes it with optional `this` - * binding of, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & ARY_FLAG, - isBind = bitmask & BIND_FLAG, - isBindKey = bitmask & BIND_KEY_FLAG, - isCurry = bitmask & CURRY_FLAG, - isCurryBound = bitmask & CURRY_BOUND_FLAG, - isCurryRight = bitmask & CURRY_RIGHT_FLAG, - Ctor = isBindKey ? undefined : createCtorWrapper(func); - - function wrapper() { - // Avoid `arguments` object use disqualifying optimizations by - // converting it to an array before providing it to other functions. - var length = arguments.length, - index = length, - args = Array(length); - - while (index--) { - args[index] = arguments[index]; - } - if (partials) { - args = composeArgs(args, partials, holders); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight); - } - if (isCurry || isCurryRight) { - var placeholder = wrapper.placeholder, - argsHolders = replaceHolders(args, placeholder); - - length -= argsHolders.length; - if (length < arity) { - var newArgPos = argPos ? arrayCopy(argPos) : undefined, - newArity = nativeMax(arity - length, 0), - newsHolders = isCurry ? argsHolders : undefined, - newHoldersRight = isCurry ? undefined : argsHolders, - newPartials = isCurry ? args : undefined, - newPartialsRight = isCurry ? undefined : args; - - bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); - - if (!isCurryBound) { - bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); - } - var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], - result = createHybridWrapper.apply(undefined, newData); - - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return result; - } - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - if (argPos) { - args = reorder(args, argPos); - } - if (isAry && ary < args.length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtorWrapper(func); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates the padding required for `string` based on the given `length`. - * The `chars` string is truncated if the number of characters exceeds `length`. - * - * @private - * @param {string} string The string to create padding for. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the pad for `string`. - */ - function createPadding(string, length, chars) { - var strLength = string.length; - length = +length; - - if (strLength >= length || !nativeIsFinite(length)) { - return ''; - } - var padLength = length - strLength; - chars = chars == null ? ' ' : (chars + ''); - return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength); - } - - /** - * Creates a function that wraps `func` and invokes it with the optional `this` - * binding of `thisArg` and the `partials` prepended to those provided to - * the wrapper. - * - * @private - * @param {Function} func The function to partially apply arguments to. - * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to the new function. - * @returns {Function} Returns the new bound function. - */ - function createPartialWrapper(func, bitmask, thisArg, partials) { - var isBind = bitmask & BIND_FLAG, - Ctor = createCtorWrapper(func); - - function wrapper() { - // Avoid `arguments` object use disqualifying optimizations by - // converting it to an array before providing it `func`. - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength); - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.ceil`, `_.floor`, or `_.round` function. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - precision = precision === undefined ? 0 : (+precision || 0); - if (precision) { - precision = pow(10, precision); - return func(number * precision) / precision; - } - return func(number); - }; - } - - /** - * Creates a `_.sortedIndex` or `_.sortedLastIndex` function. - * - * @private - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {Function} Returns the new index function. - */ - function createSortedIndex(retHighest) { - return function(array, value, iteratee, thisArg) { - var callback = getCallback(iteratee); - return (iteratee == null && callback === baseCallback) - ? binaryIndex(array, value, retHighest) - : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest); - }; - } - - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of flags. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - length -= (holders ? holders.length : 0); - if (bitmask & PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func), - newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; - - if (data) { - mergeData(newData, data); - bitmask = newData[1]; - arity = newData[9]; - } - newData[9] = arity == null - ? (isBindKey ? 0 : func.length) - : (nativeMax(arity - length, 0) || 0); - - if (bitmask == BIND_FLAG) { - var result = createBindWrapper(newData[0], newData[2]); - } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { - result = createPartialWrapper.apply(undefined, newData); - } else { - result = createHybridWrapper.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setter(result, newData); - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing arrays. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { - var index = -1, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isLoose && othLength > arrLength)) { - return false; - } - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index], - result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; - - if (result !== undefined) { - if (result) { - continue; - } - return false; - } - // Recursively compare arrays (susceptible to call stack limits). - if (isLoose) { - if (!arraySome(other, function(othValue) { - return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); - })) { - return false; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { - return false; - } - } - return true; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag) { - switch (tag) { - case boolTag: - case dateTag: - // Coerce dates and booleans to numbers, dates to milliseconds and booleans - // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. - return +object == +other; - - case errorTag: - return object.name == other.name && object.message == other.message; - - case numberTag: - // Treat `NaN` vs. `NaN` as equal. - return (object != +object) - ? other != +other - : object == +other; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings primitives and string - // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. - return object == (other + ''); - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objProps = keys(object), - objLength = objProps.length, - othProps = keys(other), - othLength = othProps.length; - - if (objLength != othLength && !isLoose) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var skipCtor = isLoose; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key], - result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; - - // Recursively compare objects (susceptible to call stack limits). - if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { - return false; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (!skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - return false; - } - } - return true; - } - - /** - * Gets the appropriate "callback" function. If the `_.callback` method is - * customized this function returns the custom method, otherwise it returns - * the `baseCallback` function. If arguments are provided the chosen function - * is invoked with them and its result is returned. - * - * @private - * @returns {Function} Returns the chosen function or its result. - */ - function getCallback(func, thisArg, argCount) { - var result = lodash.callback || callback; - result = result === callback ? baseCallback : result; - return argCount ? result(func, thisArg, argCount) : result; - } - - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = func.name, - array = realNames[result], - length = array ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the appropriate "indexOf" function. If the `_.indexOf` method is - * customized this function returns the custom method, otherwise it returns - * the `baseIndexOf` function. If arguments are provided the chosen function - * is invoked with them and its result is returned. - * - * @private - * @returns {Function|number} Returns the chosen function or its result. - */ - function getIndexOf(collection, target, fromIndex) { - var result = lodash.indexOf || indexOf; - result = result === indexOf ? baseIndexOf : result; - return collection ? result(collection, target, fromIndex) : result; - } - - /** - * Gets the "length" property value of `object`. - * - * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) - * that affects Safari on at least iOS 8.1-8.3 ARM64. - * - * @private - * @param {Object} object The object to query. - * @returns {*} Returns the "length" value. - */ - var getLength = baseProperty('length'); - - /** - * Gets the propery names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = pairs(object), - length = result.length; - - while (length--) { - result[length][2] = isStrictComparable(result[length][1]); - } - return result; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = object == null ? undefined : object[key]; - return isNative(value) ? value : undefined; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add array properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - var Ctor = object.constructor; - if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { - Ctor = Object; - } - return new Ctor; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return bufferClone(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - var buffer = object.buffer; - return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - var result = new Ctor(object.source, reFlags.exec(object)); - result.lastIndex = object.lastIndex; - } - return result; - } - - /** - * Invokes the method at `path` on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function invokePath(object, path, args) { - if (object != null && !isKey(path, object)) { - path = toPath(path); - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - path = last(path); - } - var func = object == null ? object : object[path]; - return func == null ? undefined : func.apply(object, args); - } - - /** - * Checks if `value` is array-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - */ - function isArrayLike(value) { - return value != null && isLength(getLength(value)); - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; - length = length == null ? MAX_SAFE_INTEGER : length; - return value > -1 && value % 1 == 0 && value < length; - } - - /** - * Checks if the provided arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object)) { - var other = object[index]; - return value === value ? (value === other) : (other !== other); - } - return false; - } - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - var type = typeof value; - if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { - return true; - } - if (isArray(value)) { - return false; - } - var result = !reIsDeepProp.test(value); - return result || (object != null && value in toObject(object)); - } - - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func); - if (!(funcName in LazyWrapper.prototype)) { - return false; - } - var other = lodash[funcName]; - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - */ - function isLength(value) { - return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers required to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` - * augment function arguments, making the order in which they are executed important, - * preventing the merging of metadata. However, we make an exception for a safe - * common case where curried functions have `_.ary` and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < ARY_FLAG; - - var isCombo = - (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || - (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || - (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = arrayCopy(value); - } - // Use source `ary` if it's smaller. - if (srcBitmask & ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use. - * - * @private - * @param {*} objectValue The destination object property value. - * @param {*} sourceValue The source object property value. - * @returns {*} Returns the value to assign to the destination object. - */ - function mergeDefaults(objectValue, sourceValue) { - return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults); - } - - /** - * A specialized version of `_.pick` which picks `object` properties specified - * by `props`. - * - * @private - * @param {Object} object The source object. - * @param {string[]} props The property names to pick. - * @returns {Object} Returns the new object. - */ - function pickByArray(object, props) { - object = toObject(object); - - var index = -1, - length = props.length, - result = {}; - - while (++index < length) { - var key = props[index]; - if (key in object) { - result[key] = object[key]; - } - } - return result; - } - - /** - * A specialized version of `_.pick` which picks `object` properties `predicate` - * returns truthy for. - * - * @private - * @param {Object} object The source object. - * @param {Function} predicate The function invoked per iteration. - * @returns {Object} Returns the new object. - */ - function pickByCallback(object, predicate) { - var result = {}; - baseForIn(object, function(value, key, object) { - if (predicate(value, key, object)) { - result[key] = value; - } - }); - return result; - } - - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = arrayCopy(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity function - * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = (function() { - var count = 0, - lastCalled = 0; - - return function(key, value) { - var stamp = now(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return key; - } - } else { - count = 0; - } - return baseSetData(key, value); - }; - }()); - - /** - * A fallback implementation of `Object.keys` which creates an array of the - * own enumerable property names of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function shimKeys(object) { - var props = keysIn(object), - propsLength = props.length, - length = propsLength && object.length; - - var allowIndexes = !!length && isLength(length) && - (isArray(object) || isArguments(object)); - - var index = -1, - result = []; - - while (++index < propsLength) { - var key = props[index]; - if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to an array-like object if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Array|Object} Returns the array-like object. - */ - function toIterable(value) { - if (value == null) { - return []; - } - if (!isArrayLike(value)) { - return values(value); - } - return isObject(value) ? value : Object(value); - } - - /** - * Converts `value` to an object if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Object} Returns the object. - */ - function toObject(value) { - return isObject(value) ? value : Object(value); - } - - /** - * Converts `value` to property path array if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Array} Returns the property path array. - */ - function toPath(value) { - if (isArray(value)) { - return value; - } - var result = []; - baseToString(value).replace(rePropName, function(match, number, quote, string) { - result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - } - - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - return wrapper instanceof LazyWrapper - ? wrapper.clone() - : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `collection` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the new array containing chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if (guard ? isIterateeCall(array, size, guard) : size == null) { - size = 1; - } else { - size = nativeMax(nativeFloor(size) || 1, 1); - } - var index = 0, - length = array ? array.length : 0, - resIndex = -1, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[++resIndex] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array ? array.length : 0, - resIndex = -1, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[++resIndex] = value; - } - } - return result; - } - - /** - * Creates an array of unique `array` values not included in the other - * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The arrays of values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.difference([1, 2, 3], [4, 2]); - * // => [1, 3] - */ - var difference = restParam(function(array, values) { - return (isObjectLike(array) && isArrayLike(array)) - ? baseDifference(array, baseFlatten(values, false, true)) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (guard ? isIterateeCall(array, n, guard) : n == null) { - n = 1; - } - return baseSlice(array, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (guard ? isIterateeCall(array, n, guard) : n == null) { - n = 1; - } - n = length - (+n || 0); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * bound to `thisArg` and invoked with three arguments: (value, index, array). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that match the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRightWhile([1, 2, 3], function(n) { - * return n > 1; - * }); - * // => [1] - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); - * // => ['barney', 'fred'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); - * // => ['barney'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.dropRightWhile(users, 'active'), 'user'); - * // => ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate, thisArg) { - return (array && array.length) - ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * bound to `thisArg` and invoked with three arguments: (value, index, array). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropWhile([1, 2, 3], function(n) { - * return n < 3; - * }); - * // => [3] - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); - * // => ['fred', 'pebbles'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.dropWhile(users, 'active', false), 'user'); - * // => ['pebbles'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.dropWhile(users, 'active'), 'user'); - * // => ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate, thisArg) { - return (array && array.length) - ? baseWhile(array, getCallback(predicate, thisArg, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8], '*', 1, 2); - * // => [4, '*', 8] - */ - function fill(array, value, start, end) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(chr) { - * return chr.user == 'barney'; - * }); - * // => 0 - * - * // using the `_.matches` callback shorthand - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // using the `_.matchesProperty` callback shorthand - * _.findIndex(users, 'active', false); - * // => 0 - * - * // using the `_.property` callback shorthand - * _.findIndex(users, 'active'); - * // => 2 - */ - var findIndex = createFindIndex(); - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(chr) { - * return chr.user == 'pebbles'; - * }); - * // => 2 - * - * // using the `_.matches` callback shorthand - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // using the `_.matchesProperty` callback shorthand - * _.findLastIndex(users, 'active', false); - * // => 2 - * - * // using the `_.property` callback shorthand - * _.findLastIndex(users, 'active'); - * // => 0 - */ - var findLastIndex = createFindIndex(true); - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @alias head - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.first([1, 2, 3]); - * // => 1 - * - * _.first([]); - * // => undefined - */ - function first(array) { - return array ? array[0] : undefined; - } - - /** - * Flattens a nested array. If `isDeep` is `true` the array is recursively - * flattened, otherwise it is only flattened a single level. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to flatten. - * @param {boolean} [isDeep] Specify a deep flatten. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, 3, [4]]]); - * // => [1, 2, 3, [4]] - * - * // using `isDeep` - * _.flatten([1, [2, 3, [4]]], true); - * // => [1, 2, 3, 4] - */ - function flatten(array, isDeep, guard) { - var length = array ? array.length : 0; - if (guard && isIterateeCall(array, isDeep, guard)) { - isDeep = false; - } - return length ? baseFlatten(array, isDeep) : []; - } - - /** - * Recursively flattens a nested array. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to recursively flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, 3, [4]]]); - * // => [1, 2, 3, 4] - */ - function flattenDeep(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, true) : []; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it is used as the offset - * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` - * performs a faster binary search. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {boolean|number} [fromIndex=0] The index to search from or `true` - * to perform a binary search on a sorted array. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // using `fromIndex` - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - * - * // performing a binary search - * _.indexOf([1, 1, 2, 2], 2, true); - * // => 2 - */ - function indexOf(array, value, fromIndex) { - var length = array ? array.length : 0; - if (!length) { - return -1; - } - if (typeof fromIndex == 'number') { - fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; - } else if (fromIndex) { - var index = binaryIndex(array, value); - if (index < length && - (value === value ? (value === array[index]) : (array[index] !== array[index]))) { - return index; - } - return -1; - } - return baseIndexOf(array, value, fromIndex || 0); - } - - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - return dropRight(array, 1); - } - - /** - * Creates an array of unique values that are included in all of the provided - * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of shared values. - * @example - * _.intersection([1, 2], [4, 2], [2, 1]); - * // => [2] - */ - var intersection = restParam(function(arrays) { - var othLength = arrays.length, - othIndex = othLength, - caches = Array(length), - indexOf = getIndexOf(), - isCommon = indexOf == baseIndexOf, - result = []; - - while (othIndex--) { - var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : []; - caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null; - } - var array = arrays[0], - index = -1, - length = array ? array.length : 0, - seen = caches[0]; - - outer: - while (++index < length) { - value = array[index]; - if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { - var othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) { - continue outer; - } - } - if (seen) { - seen.push(value); - } - result.push(value); - } - } - return result; - }); - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array ? array.length : 0; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {boolean|number} [fromIndex=array.length-1] The index to search from - * or `true` to perform a binary search on a sorted array. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // using `fromIndex` - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - * - * // performing a binary search - * _.lastIndexOf([1, 1, 2, 2], 2, true); - * // => 3 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array ? array.length : 0; - if (!length) { - return -1; - } - var index = length; - if (typeof fromIndex == 'number') { - index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; - } else if (fromIndex) { - index = binaryIndex(array, value, true) - 1; - var other = array[index]; - if (value === value ? (value === other) : (other !== other)) { - return index; - } - return -1; - } - if (value !== value) { - return indexOfNaN(array, index, true); - } - while (index--) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * Removes all provided values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3, 1, 2, 3]; - * - * _.pull(array, 2, 3); - * console.log(array); - * // => [1, 1] - */ - function pull() { - var args = arguments, - array = args[0]; - - if (!(array && array.length)) { - return array; - } - var index = 0, - indexOf = getIndexOf(), - length = args.length; - - while (++index < length) { - var fromIndex = 0, - value = args[index]; - - while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * Removes elements from `array` corresponding to the given indexes and returns - * an array of the removed elements. Indexes may be specified as an array of - * indexes or as individual arguments. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove, - * specified as individual indexes or arrays of indexes. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [5, 10, 15, 20]; - * var evens = _.pullAt(array, 1, 3); - * - * console.log(array); - * // => [5, 15] - * - * console.log(evens); - * // => [10, 20] - */ - var pullAt = restParam(function(array, indexes) { - indexes = baseFlatten(indexes); - - var result = baseAt(array, indexes); - basePullAt(array, indexes.sort(baseCompareAscending)); - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is bound to - * `thisArg` and invoked with three arguments: (value, index, array). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * **Note:** Unlike `_.filter`, this method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to modify. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate, thisArg) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getCallback(predicate, thisArg, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @alias tail - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.rest([1, 2, 3]); - * // => [2, 3] - */ - function rest(array) { - return drop(array, 1); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of `Array#slice` to support node - * lists in IE < 9 and to ensure dense arrays are returned. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` should - * be inserted into `array` in order to maintain its sort order. If an iteratee - * function is provided it is invoked for `value` and each element of `array` - * to compute their sort ranking. The iteratee is bound to `thisArg` and - * invoked with one argument; (value). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - * - * _.sortedIndex([4, 4, 5, 5], 5); - * // => 2 - * - * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; - * - * // using an iteratee function - * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { - * return this.data[word]; - * }, dict); - * // => 1 - * - * // using the `_.property` callback shorthand - * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); - * // => 1 - */ - var sortedIndex = createSortedIndex(); - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 4, 5, 5], 5); - * // => 4 - */ - var sortedLastIndex = createSortedIndex(true); - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (guard ? isIterateeCall(array, n, guard) : n == null) { - n = 1; - } - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (guard ? isIterateeCall(array, n, guard) : n == null) { - n = 1; - } - n = length - (+n || 0); - return baseSlice(array, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is bound to `thisArg` - * and invoked with three arguments: (value, index, array). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRightWhile([1, 2, 3], function(n) { - * return n > 1; - * }); - * // => [2, 3] - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); - * // => ['pebbles'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); - * // => ['fred', 'pebbles'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.takeRightWhile(users, 'active'), 'user'); - * // => [] - */ - function takeRightWhile(array, predicate, thisArg) { - return (array && array.length) - ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is bound to - * `thisArg` and invoked with three arguments: (value, index, array). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeWhile([1, 2, 3], function(n) { - * return n < 3; - * }); - * // => [1, 2] - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false}, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); - * // => ['barney'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.takeWhile(users, 'active', false), 'user'); - * // => ['barney', 'fred'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.takeWhile(users, 'active'), 'user'); - * // => [] - */ - function takeWhile(array, predicate, thisArg) { - return (array && array.length) - ? baseWhile(array, getCallback(predicate, thisArg, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all of the provided arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([1, 2], [4, 2], [2, 1]); - * // => [1, 2, 4] - */ - var union = restParam(function(arrays) { - return baseUniq(baseFlatten(arrays, false, true)); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurence of each element - * is kept. Providing `true` for `isSorted` performs a faster search algorithm - * for sorted arrays. If an iteratee function is provided it is invoked for - * each element in the array to generate the criterion by which uniqueness - * is computed. The `iteratee` is bound to `thisArg` and invoked with three - * arguments: (value, index, array). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias unique - * @category Array - * @param {Array} array The array to inspect. - * @param {boolean} [isSorted] Specify the array is sorted. - * @param {Function|Object|string} [iteratee] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new duplicate-value-free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - * - * // using `isSorted` - * _.uniq([1, 1, 2], true); - * // => [1, 2] - * - * // using an iteratee function - * _.uniq([1, 2.5, 1.5, 2], function(n) { - * return this.floor(n); - * }, Math); - * // => [1, 2.5] - * - * // using the `_.property` callback shorthand - * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniq(array, isSorted, iteratee, thisArg) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - if (isSorted != null && typeof isSorted != 'boolean') { - thisArg = iteratee; - iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted; - isSorted = false; - } - var callback = getCallback(); - if (!(iteratee == null && callback === baseCallback)) { - iteratee = callback(iteratee, thisArg, 3); - } - return (isSorted && getIndexOf() == baseIndexOf) - ? sortedUniq(array, iteratee) - : baseUniq(array, iteratee); - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); - * // => [['fred', 30, true], ['barney', 40, false]] - * - * _.unzip(zipped); - * // => [['fred', 'barney'], [30, 40], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var index = -1, - length = 0; - - array = arrayFilter(array, function(group) { - if (isArrayLike(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - var result = Array(length); - while (++index < length) { - result[index] = arrayMap(array, baseProperty(index)); - } - return result; - } - - /** - * This method is like `_.unzip` except that it accepts an iteratee to specify - * how regrouped values should be combined. The `iteratee` is bound to `thisArg` - * and invoked with four arguments: (accumulator, value, index, group). - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee] The function to combine regrouped values. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee, thisArg) { - var length = array ? array.length : 0; - if (!length) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - iteratee = bindCallback(iteratee, thisArg, 4); - return arrayMap(result, function(group) { - return arrayReduce(group, iteratee, undefined, true); - }); - } - - /** - * Creates an array excluding all provided values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to filter. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.without([1, 2, 1, 3], 1, 2); - * // => [3] - */ - var without = restParam(function(array, values) { - return isArrayLike(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the provided arrays. - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of values. - * @example - * - * _.xor([1, 2], [4, 2]); - * // => [1, 4] - */ - function xor() { - var index = -1, - length = arguments.length; - - while (++index < length) { - var array = arguments[index]; - if (isArrayLike(array)) { - var result = result - ? arrayPush(baseDifference(result, array), baseDifference(array, result)) - : array; - } - } - return result ? baseUniq(result) : []; - } - - /** - * Creates an array of grouped elements, the first of which contains the first - * elements of the given arrays, the second of which contains the second elements - * of the given arrays, and so on. - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['fred', 'barney'], [30, 40], [true, false]); - * // => [['fred', 30, true], ['barney', 40, false]] - */ - var zip = restParam(unzip); - - /** - * The inverse of `_.pairs`; this method returns an object composed from arrays - * of property names and values. Provide either a single two dimensional array, - * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names - * and one of corresponding values. - * - * @static - * @memberOf _ - * @alias object - * @category Array - * @param {Array} props The property names. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject([['fred', 30], ['barney', 40]]); - * // => { 'fred': 30, 'barney': 40 } - * - * _.zipObject(['fred', 'barney'], [30, 40]); - * // => { 'fred': 30, 'barney': 40 } - */ - function zipObject(props, values) { - var index = -1, - length = props ? props.length : 0, - result = {}; - - if (length && !values && !isArray(props[0])) { - values = []; - } - while (++index < length) { - var key = props[index]; - if (values) { - result[key] = values[index]; - } else if (key) { - result[key[0]] = key[1]; - } - } - return result; - } - - /** - * This method is like `_.zip` except that it accepts an iteratee to specify - * how grouped values should be combined. The `iteratee` is bound to `thisArg` - * and invoked with four arguments: (accumulator, value, index, group). - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee] The function to combine grouped values. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], _.add); - * // => [111, 222] - */ - var zipWith = restParam(function(arrays) { - var length = arrays.length, - iteratee = length > 2 ? arrays[length - 2] : undefined, - thisArg = length > 1 ? arrays[length - 1] : undefined; - - if (length > 2 && typeof iteratee == 'function') { - length -= 2; - } else { - iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; - thisArg = undefined; - } - arrays.length = length; - return unzipWith(arrays, iteratee, thisArg); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object that wraps `value` with explicit method - * chaining enabled. - * - * @static - * @memberOf _ - * @category Chain - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _.chain(users) - * .sortBy('age') - * .map(function(chr) { - * return chr.user + ' is ' + chr.age; - * }) - * .first() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor is - * bound to `thisArg` and invoked with one argument; (value). The purpose of - * this method is to "tap into" a method chain in order to perform operations - * on intermediate results within the chain. - * - * @static - * @memberOf _ - * @category Chain - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @param {*} [thisArg] The `this` binding of `interceptor`. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor, thisArg) { - interceptor.call(thisArg, value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * - * @static - * @memberOf _ - * @category Chain - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @param {*} [thisArg] The `this` binding of `interceptor`. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor, thisArg) { - return interceptor.call(thisArg, value); - } - - /** - * Enables explicit method chaining on the wrapper object. - * - * @name chain - * @memberOf _ - * @category Chain - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // without explicit chaining - * _(users).first(); - * // => { 'user': 'barney', 'age': 36 } - * - * // with explicit chaining - * _(users).chain() - * .first() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chained sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @category Chain - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Creates a new array joining a wrapped array with any additional arrays - * and/or values. - * - * @name concat - * @memberOf _ - * @category Chain - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var wrapped = _(array).concat(2, [3], [[4]]); - * - * console.log(wrapped.value()); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - var wrapperConcat = restParam(function(values) { - values = baseFlatten(values); - return this.thru(function(array) { - return arrayConcat(isArray(array) ? array : [toObject(array)], values); - }); - }); - - /** - * Creates a clone of the chained sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @category Chain - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).map(function(value) { - * return Math.pow(value, 2); - * }); - * - * var other = [3, 4]; - * var otherWrapped = wrapped.plant(other); - * - * otherWrapped.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * Reverses the wrapped array so the first element becomes the last, the - * second element becomes the second to last, and so on. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @category Chain - * @returns {Object} Returns the new reversed `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - - var interceptor = function(value) { - return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse(); - }; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(interceptor); - } - - /** - * Produces the result of coercing the unwrapped value to a string. - * - * @name toString - * @memberOf _ - * @category Chain - * @returns {string} Returns the coerced string value. - * @example - * - * _([1, 2, 3]).toString(); - * // => '1,2,3' - */ - function wrapperToString() { - return (this.value() + ''); - } - - /** - * Executes the chained sequence to extract the unwrapped value. - * - * @name value - * @memberOf _ - * @alias run, toJSON, valueOf - * @category Chain - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements corresponding to the given keys, or indexes, - * of `collection`. Keys may be specified as individual arguments or as arrays - * of keys. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {...(number|number[]|string|string[])} [props] The property names - * or indexes of elements to pick, specified individually or in arrays. - * @returns {Array} Returns the new array of picked elements. - * @example - * - * _.at(['a', 'b', 'c'], [0, 2]); - * // => ['a', 'c'] - * - * _.at(['barney', 'fred', 'pebbles'], 0, 2); - * // => ['barney', 'pebbles'] - */ - var at = restParam(function(collection, props) { - return baseAt(collection, baseFlatten(props)); - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` through `iteratee`. The corresponding value - * of each key is the number of times the key was returned by `iteratee`. - * The `iteratee` is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([4.3, 6.1, 6.4], function(n) { - * return Math.floor(n); - * }); - * // => { '4': 1, '6': 2 } - * - * _.countBy([4.3, 6.1, 6.4], function(n) { - * return this.floor(n); - * }, Math); - * // => { '4': 1, '6': 2 } - * - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * The predicate is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias all - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // using the `_.matches` callback shorthand - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // using the `_.matchesProperty` callback shorthand - * _.every(users, 'active', false); - * // => true - * - * // using the `_.property` callback shorthand - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, thisArg) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (thisArg && isIterateeCall(collection, predicate, thisArg)) { - predicate = undefined; - } - if (typeof predicate != 'function' || thisArg !== undefined) { - predicate = getCallback(predicate, thisArg, 3); - } - return func(collection, predicate); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is bound to `thisArg` and - * invoked with three arguments: (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias select - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the new filtered array. - * @example - * - * _.filter([4, 5, 6], function(n) { - * return n % 2 == 0; - * }); - * // => [4, 6] - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); - * // => ['barney'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.filter(users, 'active', false), 'user'); - * // => ['fred'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.filter(users, 'active'), 'user'); - * // => ['barney'] - */ - function filter(collection, predicate, thisArg) { - var func = isArray(collection) ? arrayFilter : baseFilter; - predicate = getCallback(predicate, thisArg, 3); - return func(collection, predicate); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is bound to `thisArg` and - * invoked with three arguments: (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias detect - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.result(_.find(users, function(chr) { - * return chr.age < 40; - * }), 'user'); - * // => 'barney' - * - * // using the `_.matches` callback shorthand - * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); - * // => 'pebbles' - * - * // using the `_.matchesProperty` callback shorthand - * _.result(_.find(users, 'active', false), 'user'); - * // => 'fred' - * - * // using the `_.property` callback shorthand - * _.result(_.find(users, 'active'), 'user'); - * // => 'barney' - */ - var find = createFind(baseEach); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(baseEachRight, true); - - /** - * Performs a deep comparison between each element in `collection` and the - * source object, returning the first element that has equivalent property - * values. - * - * **Note:** This method supports comparing arrays, booleans, `Date` objects, - * numbers, `Object` objects, regexes, and strings. Objects are compared by - * their own, not inherited, enumerable properties. For comparing a single - * own or inherited property value see `_.matchesProperty`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {Object} source The object of property values to match. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); - * // => 'barney' - * - * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); - * // => 'fred' - */ - function findWhere(collection, source) { - return find(collection, baseMatches(source)); - } - - /** - * Iterates over elements of `collection` invoking `iteratee` for each element. - * The `iteratee` is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). Iteratee functions may exit iteration early - * by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" property - * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` - * may be used for object iteration. - * - * @static - * @memberOf _ - * @alias each - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2]).forEach(function(n) { - * console.log(n); - * }).value(); - * // => logs each value from left to right and returns the array - * - * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { - * console.log(n, key); - * }); - * // => logs each value-key pair and returns the object (iteration order is not guaranteed) - */ - var forEach = createForEach(arrayEach, baseEach); - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @alias eachRight - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2]).forEachRight(function(n) { - * console.log(n); - * }).value(); - * // => logs each value from right to left and returns the array - */ - var forEachRight = createForEach(arrayEachRight, baseEachRight); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` through `iteratee`. The corresponding value - * of each key is an array of the elements responsible for generating the key. - * The `iteratee` is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([4.2, 6.1, 6.4], function(n) { - * return Math.floor(n); - * }); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * _.groupBy([4.2, 6.1, 6.4], function(n) { - * return this.floor(n); - * }, Math); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * // using the `_.property` callback shorthand - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - result[key] = [value]; - } - }); - - /** - * Checks if `value` is in `collection` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it is used as the offset - * from the end of `collection`. - * - * @static - * @memberOf _ - * @alias contains, include - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {*} target The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. - * @returns {boolean} Returns `true` if a matching element is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); - * // => true - * - * _.includes('pebbles', 'eb'); - * // => true - */ - function includes(collection, target, fromIndex, guard) { - var length = collection ? getLength(collection) : 0; - if (!isLength(length)) { - collection = values(collection); - length = collection.length; - } - if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { - fromIndex = 0; - } else { - fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); - } - return (typeof collection == 'string' || !isArray(collection) && isString(collection)) - ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1) - : (!!length && getIndexOf(collection, target, fromIndex) > -1); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` through `iteratee`. The corresponding value - * of each key is the last element responsible for generating the key. The - * iteratee function is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var keyData = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.indexBy(keyData, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(keyData, function(object) { - * return String.fromCharCode(object.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(keyData, function(object) { - * return this.fromCharCode(object.code); - * }, String); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - */ - var indexBy = createAggregator(function(result, value, key) { - result[key] = value; - }); - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `methodName` is a function it is - * invoked for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invoke([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invoke = restParam(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - isProp = isKey(path), - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); - result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); - }); - return result; - }); - - /** - * Creates an array of values by running each element in `collection` through - * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three - * arguments: (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, - * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, - * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, - * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, - * `sum`, `uniq`, and `words` - * - * @static - * @memberOf _ - * @alias collect - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new mapped array. - * @example - * - * function timesThree(n) { - * return n * 3; - * } - * - * _.map([1, 2], timesThree); - * // => [3, 6] - * - * _.map({ 'a': 1, 'b': 2 }, timesThree); - * // => [3, 6] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // using the `_.property` callback shorthand - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee, thisArg) { - var func = isArray(collection) ? arrayMap : baseMap; - iteratee = getCallback(iteratee, thisArg, 3); - return func(collection, iteratee); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, while the second of which - * contains elements `predicate` returns falsey for. The predicate is bound - * to `thisArg` and invoked with three arguments: (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * _.partition([1, 2, 3], function(n) { - * return n % 2; - * }); - * // => [[1, 3], [2]] - * - * _.partition([1.2, 2.3, 3.4], function(n) { - * return this.floor(n) % 2; - * }, Math); - * // => [[1.2, 3.4], [2.3]] - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * var mapper = function(array) { - * return _.pluck(array, 'user'); - * }; - * - * // using the `_.matches` callback shorthand - * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); - * // => [['pebbles'], ['barney', 'fred']] - * - * // using the `_.matchesProperty` callback shorthand - * _.map(_.partition(users, 'active', false), mapper); - * // => [['barney', 'pebbles'], ['fred']] - * - * // using the `_.property` callback shorthand - * _.map(_.partition(users, 'active'), mapper); - * // => [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Gets the property value of `path` from all elements in `collection`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|string} path The path of the property to pluck. - * @returns {Array} Returns the property values. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * _.pluck(users, 'user'); - * // => ['barney', 'fred'] - * - * var userIndex = _.indexBy(users, 'user'); - * _.pluck(userIndex, 'age'); - * // => [36, 40] (iteration order is not guaranteed) - */ - function pluck(collection, path) { - return map(collection, property(path)); - } - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` through `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not provided the first element of `collection` is used as the initial - * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`, - * and `sortByOrder` - * - * @static - * @memberOf _ - * @alias foldl, inject - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {*} Returns the accumulated value. - * @example - * - * _.reduce([1, 2], function(total, n) { - * return total + n; - * }); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { - * result[key] = n * 3; - * return result; - * }, {}); - * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) - */ - var reduce = createReduce(arrayReduce, baseEach); - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @alias foldr - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {*} Returns the accumulated value. - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - var reduceRight = createReduce(arrayReduceRight, baseEachRight); - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Array} Returns the new filtered array. - * @example - * - * _.reject([1, 2, 3, 4], function(n) { - * return n % 2 == 0; - * }); - * // => [1, 3] - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * // using the `_.matches` callback shorthand - * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); - * // => ['barney'] - * - * // using the `_.matchesProperty` callback shorthand - * _.pluck(_.reject(users, 'active', false), 'user'); - * // => ['fred'] - * - * // using the `_.property` callback shorthand - * _.pluck(_.reject(users, 'active'), 'user'); - * // => ['barney'] - */ - function reject(collection, predicate, thisArg) { - var func = isArray(collection) ? arrayFilter : baseFilter; - predicate = getCallback(predicate, thisArg, 3); - return func(collection, function(value, index, collection) { - return !predicate(value, index, collection); - }); - } - - /** - * Gets a random element or `n` random elements from a collection. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to sample. - * @param {number} [n] The number of elements to sample. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {*} Returns the random sample(s). - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - * - * _.sample([1, 2, 3, 4], 2); - * // => [3, 1] - */ - function sample(collection, n, guard) { - if (guard ? isIterateeCall(collection, n, guard) : n == null) { - collection = toIterable(collection); - var length = collection.length; - return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; - } - var index = -1, - result = toArray(collection), - length = result.length, - lastIndex = length - 1; - - n = nativeMin(n < 0 ? 0 : (+n || 0), length); - while (++index < n) { - var rand = baseRandom(index, lastIndex), - value = result[rand]; - - result[rand] = result[index]; - result[index] = value; - } - result.length = n; - return result; - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - return sample(collection, POSITIVE_INFINITY); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable properties for objects. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the size of `collection`. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - var length = collection ? getLength(collection) : 0; - return isLength(length) ? length : keys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * The function returns as soon as it finds a passing value and does not iterate - * over the entire collection. The predicate is bound to `thisArg` and invoked - * with three arguments: (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias any - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // using the `_.matches` callback shorthand - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // using the `_.matchesProperty` callback shorthand - * _.some(users, 'active', false); - * // => true - * - * // using the `_.property` callback shorthand - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, thisArg) { - var func = isArray(collection) ? arraySome : baseSome; - if (thisArg && isIterateeCall(collection, predicate, thisArg)) { - predicate = undefined; - } - if (typeof predicate != 'function' || thisArg !== undefined) { - predicate = getCallback(predicate, thisArg, 3); - } - return func(collection, predicate); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection through `iteratee`. This method performs - * a stable sort, that is, it preserves the original sort order of equal elements. - * The `iteratee` is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new sorted array. - * @example - * - * _.sortBy([1, 2, 3], function(n) { - * return Math.sin(n); - * }); - * // => [3, 1, 2] - * - * _.sortBy([1, 2, 3], function(n) { - * return this.sin(n); - * }, Math); - * // => [3, 1, 2] - * - * var users = [ - * { 'user': 'fred' }, - * { 'user': 'pebbles' }, - * { 'user': 'barney' } - * ]; - * - * // using the `_.property` callback shorthand - * _.pluck(_.sortBy(users, 'user'), 'user'); - * // => ['barney', 'fred', 'pebbles'] - */ - function sortBy(collection, iteratee, thisArg) { - if (collection == null) { - return []; - } - if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { - iteratee = undefined; - } - var index = -1; - iteratee = getCallback(iteratee, thisArg, 3); - - var result = baseMap(collection, function(value, key, collection) { - return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; - }); - return baseSortBy(result, compareAscending); - } - - /** - * This method is like `_.sortBy` except that it can sort by multiple iteratees - * or property names. - * - * If a property name is provided for an iteratee the created `_.property` - * style callback returns the property value of the given element. - * - * If an object is provided for an iteratee the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees - * The iteratees to sort by, specified as individual values or arrays of values. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 42 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.map(_.sortByAll(users, ['user', 'age']), _.values); - * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] - * - * _.map(_.sortByAll(users, 'user', function(chr) { - * return Math.floor(chr.age / 10); - * }), _.values); - * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] - */ - var sortByAll = restParam(function(collection, iteratees) { - if (collection == null) { - return []; - } - var guard = iteratees[2]; - if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { - iteratees.length = 1; - } - return baseSortByOrder(collection, baseFlatten(iteratees), []); - }); - - /** - * This method is like `_.sortByAll` except that it allows specifying the - * sort orders of the iteratees to sort by. If `orders` is unspecified, all - * values are sorted in ascending order. Otherwise, a value is sorted in - * ascending order if its corresponding order is "asc", and descending if "desc". - * - * If a property name is provided for an iteratee the created `_.property` - * style callback returns the property value of the given element. - * - * If an object is provided for an iteratee the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {boolean[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 42 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // sort by `user` in ascending order and by `age` in descending order - * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values); - * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] - */ - function sortByOrder(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (guard && isIterateeCall(iteratees, orders, guard)) { - orders = undefined; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseSortByOrder(collection, iteratees, orders); - } - - /** - * Performs a deep comparison between each element in `collection` and the - * source object, returning an array of all elements that have equivalent - * property values. - * - * **Note:** This method supports comparing arrays, booleans, `Date` objects, - * numbers, `Object` objects, regexes, and strings. Objects are compared by - * their own, not inherited, enumerable properties. For comparing a single - * own or inherited property value see `_.matchesProperty`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {Object} source The object of property values to match. - * @returns {Array} Returns the new filtered array. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, - * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } - * ]; - * - * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); - * // => ['barney'] - * - * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); - * // => ['fred'] - */ - function where(collection, source) { - return filter(collection, baseMatches(source)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Gets the number of milliseconds that have elapsed since the Unix epoch - * (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @category Date - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => logs the number of milliseconds it took for the deferred function to be invoked - */ - var now = nativeNow || function() { - return new Date().getTime(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it is called `n` or more times. - * - * @static - * @memberOf _ - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => logs 'done saving!' after the two async saves have completed - */ - function after(n, func) { - if (typeof func != 'function') { - if (typeof n == 'function') { - var temp = n; - n = func; - func = temp; - } else { - throw new TypeError(FUNC_ERROR_TEXT); - } - } - n = nativeIsFinite(n = +n) ? n : 0; - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that accepts up to `n` arguments ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Function} Returns the new function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - if (guard && isIterateeCall(func, n, guard)) { - n = undefined; - } - n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); - return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it is called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery('#add').on('click', _.before(5, addContactToList)); - * // => allows adding up to 4 contacts to the list - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - if (typeof n == 'function') { - var temp = n; - n = func; - func = temp; - } else { - throw new TypeError(FUNC_ERROR_TEXT); - } - } - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and prepends any additional `_.bind` arguments to those provided to the - * bound function. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind` this method does not set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var greet = function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * }; - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // using placeholders - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = restParam(function(func, thisArg, partials) { - var bitmask = BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, bind.placeholder); - bitmask |= PARTIAL_FLAG; - } - return createWrapper(func, bitmask, thisArg, partials, holders); - }); - - /** - * Binds methods of an object to the object itself, overwriting the existing - * method. Method names may be specified as individual arguments or as arrays - * of method names. If no method names are provided all enumerable function - * properties, own and inherited, of `object` are bound. - * - * **Note:** This method does not set the "length" property of bound functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Object} object The object to bind and assign the bound methods to. - * @param {...(string|string[])} [methodNames] The object method names to bind, - * specified as individual method names or arrays of method names. - * @returns {Object} Returns `object`. - * @example - * - * var view = { - * 'label': 'docs', - * 'onClick': function() { - * console.log('clicked ' + this.label); - * } - * }; - * - * _.bindAll(view); - * jQuery('#docs').on('click', view.onClick); - * // => logs 'clicked docs' when the element is clicked - */ - var bindAll = restParam(function(object, methodNames) { - methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); - - var index = -1, - length = methodNames.length; - - while (++index < length) { - var key = methodNames[index]; - object[key] = createWrapper(object[key], BIND_FLAG, object); - } - return object; - }); - - /** - * Creates a function that invokes the method at `object[key]` and prepends - * any additional `_.bindKey` arguments to those provided to the bound function. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. - * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @category Function - * @param {Object} object The object the method belongs to. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // using placeholders - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = restParam(function(object, key, partials) { - var bitmask = BIND_FLAG | BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, bindKey.placeholder); - bitmask |= PARTIAL_FLAG; - } - return createWrapper(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts one or more arguments of `func` that when - * called either invokes `func` returning its result, if all `func` arguments - * have been provided, or returns a function that accepts one or more of the - * remaining `func` arguments, and so on. The arity of `func` may be specified - * if `func.length` is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method does not set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // using placeholders - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - var curry = createCurry(CURRY_FLAG); - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method does not set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // using placeholders - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - var curryRight = createCurry(CURRY_RIGHT_FLAG); - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed invocations. Provide an options object to indicate that `func` - * should be invoked on the leading and/or trailing edge of the `wait` timeout. - * Subsequent calls to the debounced function return the result of the last - * `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked - * on the trailing edge of the timeout only if the the debounced function is - * invoked more than once during the `wait` timeout. - * - * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=false] Specify invoking on the leading - * edge of the timeout. - * @param {number} [options.maxWait] The maximum time `func` is allowed to be - * delayed before it is invoked. - * @param {boolean} [options.trailing=true] Specify invoking on the trailing - * edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // avoid costly calculations while the window size is in flux - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // invoke `sendMail` when the click event is fired, debouncing subsequent calls - * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // ensure `batchLog` is invoked once after 1 second of debounced calls - * var source = new EventSource('/stream'); - * jQuery(source).on('message', _.debounce(batchLog, 250, { - * 'maxWait': 1000 - * })); - * - * // cancel a debounced call - * var todoChanges = _.debounce(batchLog, 1000); - * Object.observe(models.todo, todoChanges); - * - * Object.observe(models, function(changes) { - * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { - * todoChanges.cancel(); - * } - * }, ['delete']); - * - * // ...at some point `models.todo` is changed - * models.todo.completed = true; - * - * // ...before 1 second has passed `models.todo` is deleted - * // which cancels the debounced `todoChanges` call - * delete models.todo; - */ - function debounce(func, wait, options) { - var args, - maxTimeoutId, - result, - stamp, - thisArg, - timeoutId, - trailingCall, - lastCalled = 0, - maxWait = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = wait < 0 ? 0 : (+wait || 0); - if (options === true) { - var leading = true; - trailing = false; - } else if (isObject(options)) { - leading = !!options.leading; - maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function cancel() { - if (timeoutId) { - clearTimeout(timeoutId); - } - if (maxTimeoutId) { - clearTimeout(maxTimeoutId); - } - lastCalled = 0; - maxTimeoutId = timeoutId = trailingCall = undefined; - } - - function complete(isCalled, id) { - if (id) { - clearTimeout(id); - } - maxTimeoutId = timeoutId = trailingCall = undefined; - if (isCalled) { - lastCalled = now(); - result = func.apply(thisArg, args); - if (!timeoutId && !maxTimeoutId) { - args = thisArg = undefined; - } - } - } - - function delayed() { - var remaining = wait - (now() - stamp); - if (remaining <= 0 || remaining > wait) { - complete(trailingCall, maxTimeoutId); - } else { - timeoutId = setTimeout(delayed, remaining); - } - } - - function maxDelayed() { - complete(trailing, timeoutId); - } - - function debounced() { - args = arguments; - stamp = now(); - thisArg = this; - trailingCall = trailing && (timeoutId || !leading); - - if (maxWait === false) { - var leadingCall = leading && !timeoutId; - } else { - if (!maxTimeoutId && !leading) { - lastCalled = stamp; - } - var remaining = maxWait - (stamp - lastCalled), - isCalled = remaining <= 0 || remaining > maxWait; - - if (isCalled) { - if (maxTimeoutId) { - maxTimeoutId = clearTimeout(maxTimeoutId); - } - lastCalled = stamp; - result = func.apply(thisArg, args); - } - else if (!maxTimeoutId) { - maxTimeoutId = setTimeout(maxDelayed, remaining); - } - } - if (isCalled && timeoutId) { - timeoutId = clearTimeout(timeoutId); - } - else if (!timeoutId && wait !== maxWait) { - timeoutId = setTimeout(delayed, wait); - } - if (leadingCall) { - isCalled = true; - result = func.apply(thisArg, args); - } - if (isCalled && !timeoutId && !maxTimeoutId) { - args = thisArg = undefined; - } - return result; - } - debounced.cancel = cancel; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // logs 'deferred' after one or more milliseconds - */ - var defer = restParam(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => logs 'later' after one second - */ - var delay = restParam(function(func, wait, args) { - return baseDelay(func, wait, args); - }); - - /** - * Creates a function that returns the result of invoking the provided - * functions with the `this` binding of the created function, where each - * successive invocation is supplied the return value of the previous. - * - * @static - * @memberOf _ - * @category Function - * @param {...Function} [funcs] Functions to invoke. - * @returns {Function} Returns the new function. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var addSquare = _.flow(_.add, square); - * addSquare(1, 2); - * // => 9 - */ - var flow = createFlow(); - - /** - * This method is like `_.flow` except that it creates a function that - * invokes the provided functions from right to left. - * - * @static - * @memberOf _ - * @alias backflow, compose - * @category Function - * @param {...Function} [funcs] Functions to invoke. - * @returns {Function} Returns the new function. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var addSquare = _.flowRight(square, _.add); - * addSquare(1, 2); - * // => 9 - */ - var flowRight = createFlow(true); - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is coerced to a string and used as the - * cache key. The `func` is invoked with the `this` binding of the memoized - * function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object) - * method interface of `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoizing function. - * @example - * - * var upperCase = _.memoize(function(string) { - * return string.toUpperCase(); - * }); - * - * upperCase('fred'); - * // => 'FRED' - * - * // modifying the result cache - * upperCase.cache.set('fred', 'BARNEY'); - * upperCase('fred'); - * // => 'BARNEY' - * - * // replacing `_.memoize.Cache` - * var object = { 'user': 'fred' }; - * var other = { 'user': 'barney' }; - * var identity = _.memoize(_.identity); - * - * identity(object); - * // => { 'user': 'fred' } - * identity(other); - * // => { 'user': 'fred' } - * - * _.memoize.Cache = WeakMap; - * var identity = _.memoize(_.identity); - * - * identity(object); - * // => { 'user': 'fred' } - * identity(other); - * // => { 'user': 'barney' } - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result); - return result; - }; - memoized.cache = new memoize.Cache; - return memoized; - } - - /** - * Creates a function that runs each argument through a corresponding - * transform function. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms] The functions to transform - * arguments, specified as individual functions or arrays of functions. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var modded = _.modArgs(function(x, y) { - * return [x, y]; - * }, square, doubled); - * - * modded(1, 2); - * // => [1, 4] - * - * modded(5, 10); - * // => [25, 20] - */ - var modArgs = restParam(function(func, transforms) { - transforms = baseFlatten(transforms); - if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = transforms.length; - return restParam(function(args) { - var index = nativeMin(args.length, length); - while (index--) { - args[index] = transforms[index](args[index]); - } - return func.apply(this, args); - }); - }); - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - return !predicate.apply(this, arguments); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first call. The `func` is invoked - * with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // `initialize` invokes `createApplication` once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with `partial` arguments prepended - * to those provided to the new function. This method is like `_.bind` except - * it does **not** alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method does not set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var greet = function(greeting, name) { - * return greeting + ' ' + name; - * }; - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // using placeholders - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = createPartial(PARTIAL_FLAG); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to those provided to the new function. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method does not set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var greet = function(greeting, name) { - * return greeting + ' ' + name; - * }; - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // using placeholders - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = createPartial(PARTIAL_RIGHT_FLAG); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified indexes where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes, - * specified as individual indexes or arrays of indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, 2, 0, 1); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - * - * var map = _.rearg(_.map, [1, 0]); - * map(function(n) { - * return n * 3; - * }, [1, 2, 3]); - * // => [3, 6, 9] - */ - var rearg = restParam(function(func, indexes) { - return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes)); - }); - - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as an array. - * - * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.restParam(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function restParam(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - rest = Array(length); - - while (++index < length) { - rest[index] = args[start + index]; - } - switch (start) { - case 0: return func.call(this, rest); - case 1: return func.call(this, args[0], rest); - case 2: return func.call(this, args[0], args[1], rest); - } - var otherArgs = Array(start + 1); - index = -1; - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = rest; - return func.apply(this, otherArgs); - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of the created - * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). - * - * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to spread arguments over. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * // with a Promise - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function(array) { - return func.apply(this, array); - }; - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed invocations. Provide an options object to indicate - * that `func` should be invoked on the leading and/or trailing edge of the - * `wait` timeout. Subsequent calls to the throttled function return the - * result of the last `func` call. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked - * on the trailing edge of the timeout only if the the throttled function is - * invoked more than once during the `wait` timeout. - * - * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=true] Specify invoking on the leading - * edge of the timeout. - * @param {boolean} [options.trailing=true] Specify invoking on the trailing - * edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // avoid excessively updating the position while scrolling - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes - * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { - * 'trailing': false - * })); - * - * // cancel a trailing throttled call - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (options === false) { - leading = false; - } else if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing }); - } - - /** - * Creates a function that provides `value` to the wrapper function as its - * first argument. Any additional arguments provided to the function are - * appended to those provided to the wrapper function. The wrapper is invoked - * with the `this` binding of the created function. - * - * @static - * @memberOf _ - * @category Function - * @param {*} value The value to wrap. - * @param {Function} wrapper The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - wrapper = wrapper == null ? identity : wrapper; - return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, - * otherwise they are assigned by reference. If `customizer` is provided it is - * invoked to produce the cloned values. If `customizer` returns `undefined` - * cloning is handled by the method instead. The `customizer` is bound to - * `thisArg` and invoked with two argument; (value [, index|key, object]). - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). - * The enumerable properties of `arguments` objects and objects created by - * constructors other than `Object` are cloned to plain `Object` objects. An - * empty object is returned for uncloneable values such as functions, DOM nodes, - * Maps, Sets, and WeakMaps. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {*} Returns the cloned value. - * @example - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * var shallow = _.clone(users); - * shallow[0] === users[0]; - * // => true - * - * var deep = _.clone(users, true); - * deep[0] === users[0]; - * // => false - * - * // using a customizer callback - * var el = _.clone(document.body, function(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * }); - * - * el === document.body - * // => false - * el.nodeName - * // => BODY - * el.childNodes.length; - * // => 0 - */ - function clone(value, isDeep, customizer, thisArg) { - if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { - isDeep = false; - } - else if (typeof isDeep == 'function') { - thisArg = customizer; - customizer = isDeep; - isDeep = false; - } - return typeof customizer == 'function' - ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1)) - : baseClone(value, isDeep); - } - - /** - * Creates a deep clone of `value`. If `customizer` is provided it is invoked - * to produce the cloned values. If `customizer` returns `undefined` cloning - * is handled by the method instead. The `customizer` is bound to `thisArg` - * and invoked with two argument; (value [, index|key, object]). - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). - * The enumerable properties of `arguments` objects and objects created by - * constructors other than `Object` are cloned to plain `Object` objects. An - * empty object is returned for uncloneable values such as functions, DOM nodes, - * Maps, Sets, and WeakMaps. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {*} Returns the deep cloned value. - * @example - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * var deep = _.cloneDeep(users); - * deep[0] === users[0]; - * // => false - * - * // using a customizer callback - * var el = _.cloneDeep(document.body, function(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * }); - * - * el === document.body - * // => false - * el.nodeName - * // => BODY - * el.childNodes.length; - * // => 20 - */ - function cloneDeep(value, customizer, thisArg) { - return typeof customizer == 'function' - ? baseClone(value, true, bindCallback(customizer, thisArg, 1)) - : baseClone(value, true); - } - - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`. - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ - function gt(value, other) { - return value > other; - } - - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`. - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ - function gte(value, other) { - return value >= other; - } - - /** - * Checks if `value` is classified as an `arguments` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - return isObjectLike(value) && isArrayLike(value) && - hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(function() { return arguments; }()); - * // => false - */ - var isArray = nativeIsArray || function(value) { - return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; - }; - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag); - } - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - function isDate(value) { - return isObjectLike(value) && objToString.call(value) == dateTag; - } - - /** - * Checks if `value` is a DOM element. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); - } - - /** - * Checks if `value` is empty. A value is considered empty unless it is an - * `arguments` object, array, string, or jQuery-like collection with a length - * greater than `0` or an object with own enumerable properties. - * - * @static - * @memberOf _ - * @category Lang - * @param {Array|Object|string} value The value to inspect. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || - (isObjectLike(value) && isFunction(value.splice)))) { - return !value.length; - } - return !keys(value).length; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. If `customizer` is provided it is invoked to compare values. - * If `customizer` returns `undefined` comparisons are handled by the method - * instead. The `customizer` is bound to `thisArg` and invoked with three - * arguments: (value, other [, index|key]). - * - * **Note:** This method supports comparing arrays, booleans, `Date` objects, - * numbers, `Object` objects, regexes, and strings. Objects are compared by - * their own, not inherited, enumerable properties. Functions and DOM nodes - * are **not** supported. Provide a customizer function to extend support - * for comparing other values. - * - * @static - * @memberOf _ - * @alias eq - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize value comparisons. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'user': 'fred' }; - * var other = { 'user': 'fred' }; - * - * object == other; - * // => false - * - * _.isEqual(object, other); - * // => true - * - * // using a customizer callback - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqual(array, other, function(value, other) { - * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { - * return true; - * } - * }); - * // => true - */ - function isEqual(value, other, customizer, thisArg) { - customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag; - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite). - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(10); - * // => true - * - * _.isFinite('10'); - * // => false - * - * _.isFinite(true); - * // => false - * - * _.isFinite(Object(10)); - * // => false - * - * _.isFinite(Infinity); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in older versions of Chrome and Safari which return 'function' for regexes - // and Safari 8 equivalents which return 'object' for typed array constructors. - return isObject(value) && objToString.call(value) == funcTag; - } - - /** - * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ - function isObject(value) { - // Avoid a V8 JIT bug in Chrome 19-20. - // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Performs a deep comparison between `object` and `source` to determine if - * `object` contains equivalent property values. If `customizer` is provided - * it is invoked to compare values. If `customizer` returns `undefined` - * comparisons are handled by the method instead. The `customizer` is bound - * to `thisArg` and invoked with three arguments: (value, other, index|key). - * - * **Note:** This method supports comparing properties of arrays, booleans, - * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions - * and DOM nodes are **not** supported. Provide a customizer function to extend - * support for comparing other values. - * - * @static - * @memberOf _ - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize value comparisons. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'user': 'fred', 'age': 40 }; - * - * _.isMatch(object, { 'age': 40 }); - * // => true - * - * _.isMatch(object, { 'age': 36 }); - * // => false - * - * // using a customizer callback - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatch(object, source, function(value, other) { - * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; - * }); - * // => true - */ - function isMatch(object, source, customizer, thisArg) { - customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; - return baseIsMatch(object, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) - * which returns `true` for `undefined` and other non-numeric values. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some host objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a native function. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (value == null) { - return false; - } - if (isFunction(value)) { - return reIsNative.test(fnToString.call(value)); - } - return isObjectLike(value) && reIsHostCtor.test(value); - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified - * as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isNumber(8.4); - * // => true - * - * _.isNumber(NaN); - * // => true - * - * _.isNumber('8.4'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * **Note:** This method assumes objects created by the `Object` constructor - * have no inherited enumerable properties. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - var Ctor; - - // Exit early for non `Object` objects. - if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) || - (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { - return false; - } - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - var result; - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - baseForIn(value, function(subValue, key) { - result = key; - }); - return result === undefined || hasOwnProperty.call(value, result); - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - function isRegExp(value) { - return isObject(value) && objToString.call(value) == regexpTag; - } - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); - } - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - function isTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; - } - - /** - * Checks if `value` is `undefined`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`. - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ - function lt(value, other) { - return value < other; - } - - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`. - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - function lte(value, other) { - return value <= other; - } - - /** - * Converts `value` to an array. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * (function() { - * return _.toArray(arguments).slice(1); - * }(1, 2, 3)); - * // => [2, 3] - */ - function toArray(value) { - var length = value ? getLength(value) : 0; - if (!isLength(length)) { - return values(value); - } - if (!length) { - return []; - } - return arrayCopy(value); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable - * properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return baseCopy(value, keysIn(value)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Recursively merges own enumerable properties of the source object(s), that - * don't resolve to `undefined` into the destination object. Subsequent sources - * overwrite property assignments of previous sources. If `customizer` is - * provided it is invoked to produce the merged values of the destination and - * source properties. If `customizer` returns `undefined` merging is handled - * by the method instead. The `customizer` is bound to `thisArg` and invoked - * with five arguments: (objectValue, sourceValue, key, object, source). - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {Object} Returns `object`. - * @example - * - * var users = { - * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] - * }; - * - * var ages = { - * 'data': [{ 'age': 36 }, { 'age': 40 }] - * }; - * - * _.merge(users, ages); - * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } - * - * // using a customizer callback - * var object = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var other = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * _.merge(object, other, function(a, b) { - * if (_.isArray(a)) { - * return a.concat(b); - * } - * }); - * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } - */ - var merge = createAssigner(baseMerge); - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object. Subsequent sources overwrite property assignments of previous sources. - * If `customizer` is provided it is invoked to produce the assigned values. - * The `customizer` is bound to `thisArg` and invoked with five arguments: - * (objectValue, sourceValue, key, object, source). - * - * **Note:** This method mutates `object` and is based on - * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign). - * - * @static - * @memberOf _ - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {Object} Returns `object`. - * @example - * - * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); - * // => { 'user': 'fred', 'age': 40 } - * - * // using a customizer callback - * var defaults = _.partialRight(_.assign, function(value, other) { - * return _.isUndefined(value) ? other : value; - * }); - * - * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); - * // => { 'user': 'barney', 'age': 36 } - */ - var assign = createAssigner(function(object, source, customizer) { - return customizer - ? assignWith(object, source, customizer) - : baseAssign(object, source); - }); - - /** - * Creates an object that inherits from the given `prototype` object. If a - * `properties` object is provided its own enumerable properties are assigned - * to the created object. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties, guard) { - var result = baseCreate(prototype); - if (guard && isIterateeCall(prototype, properties, guard)) { - properties = undefined; - } - return properties ? baseAssign(result, properties) : result; - } - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object for all destination properties that resolve to `undefined`. Once a - * property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); - * // => { 'user': 'barney', 'age': 36 } - */ - var defaults = createDefaults(assign, assignDefaults); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } }); - * // => { 'user': { 'name': 'barney', 'age': 36 } } - * - */ - var defaultsDeep = createDefaults(merge, mergeDefaults); - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {string|undefined} Returns the key of the matched element, else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(chr) { - * return chr.age < 40; - * }); - * // => 'barney' (iteration order is not guaranteed) - * - * // using the `_.matches` callback shorthand - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // using the `_.matchesProperty` callback shorthand - * _.findKey(users, 'active', false); - * // => 'fred' - * - * // using the `_.property` callback shorthand - * _.findKey(users, 'active'); - * // => 'barney' - */ - var findKey = createFindKey(baseForOwn); - - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {string|undefined} Returns the key of the matched element, else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(chr) { - * return chr.age < 40; - * }); - * // => returns `pebbles` assuming `_.findKey` returns `barney` - * - * // using the `_.matches` callback shorthand - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // using the `_.matchesProperty` callback shorthand - * _.findLastKey(users, 'active', false); - * // => 'fred' - * - * // using the `_.property` callback shorthand - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - var findLastKey = createFindKey(baseForOwnRight); - - /** - * Iterates over own and inherited enumerable properties of an object invoking - * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns `object`. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) - */ - var forIn = createForIn(baseFor); - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns `object`. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' - */ - var forInRight = createForIn(baseForRight); - - /** - * Iterates over own enumerable properties of an object invoking `iteratee` - * for each property. The `iteratee` is bound to `thisArg` and invoked with - * three arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns `object`. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => logs 'a' and 'b' (iteration order is not guaranteed) - */ - var forOwn = createForOwn(baseForOwn); - - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns `object`. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b' - */ - var forOwnRight = createForOwn(baseForOwnRight); - - /** - * Creates an array of function property names from all enumerable properties, - * own and inherited, of `object`. - * - * @static - * @memberOf _ - * @alias methods - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the new array of property names. - * @example - * - * _.functions(_); - * // => ['after', 'ary', 'assign', ...] - */ - function functions(object) { - return baseFunctions(object, keysIn(object)); - } - - /** - * Gets the property value at `path` of `object`. If the resolved value is - * `undefined` the `defaultValue` is used in its place. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); - return result === undefined ? defaultValue : result; - } - - /** - * Checks if `path` is a direct property. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` is a direct property, else `false`. - * @example - * - * var object = { 'a': { 'b': { 'c': 3 } } }; - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b.c'); - * // => true - * - * _.has(object, ['a', 'b', 'c']); - * // => true - */ - function has(object, path) { - if (object == null) { - return false; - } - var result = hasOwnProperty.call(object, path); - if (!result && !isKey(path)) { - path = toPath(path); - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - if (object == null) { - return false; - } - path = last(path); - result = hasOwnProperty.call(object, path); - } - return result || (isLength(object.length) && isIndex(path, object.length) && - (isArray(object) || isArguments(object))); - } - - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite property - * assignments of previous values unless `multiValue` is `true`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to invert. - * @param {boolean} [multiValue] Allow multiple values per key. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - * - * // with `multiValue` - * _.invert(object, true); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ - function invert(object, multiValue, guard) { - if (guard && isIterateeCall(object, multiValue, guard)) { - multiValue = undefined; - } - var index = -1, - props = keys(object), - length = props.length, - result = {}; - - while (++index < length) { - var key = props[index], - value = object[key]; - - if (multiValue) { - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - } - else { - result[value] = key; - } - } - return result; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) - * for more details. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - var keys = !nativeKeys ? shimKeys : function(object) { - var Ctor = object == null ? undefined : object.constructor; - if ((typeof Ctor == 'function' && Ctor.prototype === object) || - (typeof object != 'function' && isArrayLike(object))) { - return shimKeys(object); - } - return isObject(object) ? nativeKeys(object) : []; - }; - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - if (object == null) { - return []; - } - if (!isObject(object)) { - object = Object(object); - } - var length = object.length; - length = (length && isLength(length) && - (isArray(object) || isArguments(object)) && length) || 0; - - var Ctor = object.constructor, - index = -1, - isProto = typeof Ctor == 'function' && Ctor.prototype === object, - result = Array(length), - skipIndexes = length > 0; - - while (++index < length) { - result[index] = (index + ''); - } - for (var key in object) { - if (!(skipIndexes && isIndex(key, length)) && - !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * property of `object` through `iteratee`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns the new mapped object. - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - var mapKeys = createObjectMapper(true); - - /** - * Creates an object with the same keys as `object` and values generated by - * running each own enumerable property of `object` through `iteratee`. The - * iteratee function is bound to `thisArg` and invoked with three arguments: - * (value, key, object). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Object} Returns the new mapped object. - * @example - * - * _.mapValues({ 'a': 1, 'b': 2 }, function(n) { - * return n * 3; - * }); - * // => { 'a': 3, 'b': 6 } - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * // using the `_.property` callback shorthand - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - var mapValues = createObjectMapper(); - - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable properties of `object` that are not omitted. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {Function|...(string|string[])} [predicate] The function invoked per - * iteration or property names to omit, specified as individual property - * names or arrays of property names. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'user': 'fred', 'age': 40 }; - * - * _.omit(object, 'age'); - * // => { 'user': 'fred' } - * - * _.omit(object, _.isNumber); - * // => { 'user': 'fred' } - */ - var omit = restParam(function(object, props) { - if (object == null) { - return {}; - } - if (typeof props[0] != 'function') { - var props = arrayMap(baseFlatten(props), String); - return pickByArray(object, baseDifference(keysIn(object), props)); - } - var predicate = bindCallback(props[0], props[1], 3); - return pickByCallback(object, function(value, key, object) { - return !predicate(value, key, object); - }); - }); - - /** - * Creates a two dimensional array of the key-value pairs for `object`, - * e.g. `[[key1, value1], [key2, value2]]`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the new array of key-value pairs. - * @example - * - * _.pairs({ 'barney': 36, 'fred': 40 }); - * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) - */ - function pairs(object) { - object = toObject(object); - - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - var key = props[index]; - result[index] = [key, object[key]]; - } - return result; - } - - /** - * Creates an object composed of the picked `object` properties. Property - * names may be specified as individual arguments or as arrays of property - * names. If `predicate` is provided it is invoked for each property of `object` - * picking the properties `predicate` returns truthy for. The predicate is - * bound to `thisArg` and invoked with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {Function|...(string|string[])} [predicate] The function invoked per - * iteration or property names to pick, specified as individual property - * names or arrays of property names. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'user': 'fred', 'age': 40 }; - * - * _.pick(object, 'user'); - * // => { 'user': 'fred' } - * - * _.pick(object, _.isString); - * // => { 'user': 'fred' } - */ - var pick = restParam(function(object, props) { - if (object == null) { - return {}; - } - return typeof props[0] == 'function' - ? pickByCallback(object, bindCallback(props[0], props[1], 3)) - : pickByArray(object, baseFlatten(props)); - }); - - /** - * This method is like `_.get` except that if the resolved value is a function - * it is invoked with the `this` binding of its parent object and its result - * is returned. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a.b.c', 'default'); - * // => 'default' - * - * _.result(object, 'a.b.c', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - var result = object == null ? undefined : object[path]; - if (result === undefined) { - if (object != null && !isKey(path, object)) { - path = toPath(path); - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - result = object == null ? undefined : object[last(path)]; - } - result = result === undefined ? defaultValue : result; - } - return isFunction(result) ? result.call(object) : result; - } - - /** - * Sets the property value of `path` on `object`. If a portion of `path` - * does not exist it is created. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to augment. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, 'x[0].y.z', 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - if (object == null) { - return object; - } - var pathKey = (path + ''); - path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = path[index]; - if (isObject(nested)) { - if (index == lastIndex) { - nested[key] = value; - } else if (nested[key] == null) { - nested[key] = isIndex(path[index + 1]) ? [] : {}; - } - } - nested = nested[key]; - } - return object; - } - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own enumerable - * properties through `iteratee`, with each invocation potentially mutating - * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked - * with four arguments: (accumulator, value, key, object). Iteratee functions - * may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Array|Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { - * result[key] = n * 3; - * }); - * // => { 'a': 3, 'b': 6 } - */ - function transform(object, iteratee, accumulator, thisArg) { - var isArr = isArray(object) || isTypedArray(object); - iteratee = getCallback(iteratee, thisArg, 4); - - if (accumulator == null) { - if (isArr || isObject(object)) { - var Ctor = object.constructor; - if (isArr) { - accumulator = isArray(object) ? new Ctor : []; - } else { - accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined); - } - } else { - accumulator = {}; - } - } - (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - /** - * Creates an array of the own enumerable property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ - function values(object) { - return baseValues(object, keys(object)); - } - - /** - * Creates an array of the own and inherited enumerable property values - * of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Checks if `n` is between `start` and up to but not including, `end`. If - * `end` is not specified it is set to `start` with `start` then set to `0`. - * - * @static - * @memberOf _ - * @category Number - * @param {number} n The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `n` is in the range, else `false`. - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - */ - function inRange(value, start, end) { - start = +start || 0; - if (end === undefined) { - end = start; - start = 0; - } else { - end = +end || 0; - } - return value >= nativeMin(start, end) && value < nativeMax(start, end); - } - - /** - * Produces a random number between `min` and `max` (inclusive). If only one - * argument is provided a number between `0` and the given number is returned. - * If `floating` is `true`, or either `min` or `max` are floats, a floating-point - * number is returned instead of an integer. - * - * @static - * @memberOf _ - * @category Number - * @param {number} [min=0] The minimum possible value. - * @param {number} [max=1] The maximum possible value. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(min, max, floating) { - if (floating && isIterateeCall(min, max, floating)) { - max = floating = undefined; - } - var noMin = min == null, - noMax = max == null; - - if (floating == null) { - if (noMax && typeof min == 'boolean') { - floating = min; - min = 1; - } - else if (typeof max == 'boolean') { - floating = max; - noMax = true; - } - } - if (noMin && noMax) { - max = 1; - noMax = false; - } - min = +min || 0; - if (noMax) { - max = min; - min = 0; - } else { - max = +max || 0; - } - if (floating || min % 1 || max % 1) { - var rand = nativeRandom(); - return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); - } - return baseRandom(min, max); - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar'); - * // => 'fooBar' - * - * _.camelCase('__foo_bar__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); - }); - - /** - * Capitalizes the first character of `string`. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('fred'); - * // => 'Fred' - */ - function capitalize(string) { - string = baseToString(string); - return string && (string.charAt(0).toUpperCase() + string.slice(1)); - } - - /** - * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = baseToString(string); - return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); - } - - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to search. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search from. - * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = baseToString(string); - target = (target + ''); - - var length = string.length; - position = position === undefined - ? length - : nativeMin(position < 0 ? 0 : (+position || 0), length); - - position -= target.length; - return position >= 0 && string.indexOf(target, position) == position; - } - - /** - * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to - * their corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional characters - * use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. - * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * Backticks are escaped because in Internet Explorer < 9, they can break out - * of attribute values or HTML comments. See [#59](https://html5sec.org/#59), - * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and - * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) - * for more details. - * - * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) - * to reduce XSS vectors. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - // Reset `lastIndex` because in IE < 9 `String#replace` does not. - string = baseToString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /** - * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", - * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' - */ - function escapeRegExp(string) { - string = baseToString(string); - return (string && reHasRegExpChars.test(string)) - ? string.replace(reRegExpChars, escapeRegExpChar) - : (string || '(?:)'); - } - - /** - * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__foo_bar__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); - - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = baseToString(string); - length = +length; - - var strLength = string.length; - if (strLength >= length || !nativeIsFinite(length)) { - return string; - } - var mid = (length - strLength) / 2, - leftLength = nativeFloor(mid), - rightLength = nativeCeil(mid); - - chars = createPadding('', rightLength, chars); - return chars.slice(0, leftLength) + string + chars; - } - - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padLeft('abc', 6); - * // => ' abc' - * - * _.padLeft('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padLeft('abc', 3); - * // => 'abc' - */ - var padLeft = createPadDir(); - - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padRight('abc', 6); - * // => 'abc ' - * - * _.padRight('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padRight('abc', 3); - * // => 'abc' - */ - var padRight = createPadDir(true); - - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, - * in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E) - * of `parseInt`. - * - * @static - * @memberOf _ - * @category String - * @param {string} string The string to convert. - * @param {number} [radix] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. - // Chrome fails to trim leading whitespace characters. - // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. - if (guard ? isIterateeCall(string, radix, guard) : radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - string = trim(string); - return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); - } - - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=0] The number of times to repeat the string. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n) { - var result = ''; - string = baseToString(string); - n = +n; - if (n < 1 || !string || !nativeIsFinite(n)) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - string += string; - } while (n); - - return result; - } - - /** - * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--foo-bar'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__foo_bar__'); - * // => 'Foo Bar' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); - }); - - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The string to search. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - function startsWith(string, target, position) { - string = baseToString(string); - position = position == null - ? 0 - : nativeMin(position < 0 ? 0 : (+position || 0), string.length); - - return string.lastIndexOf(target, position) == position; - } - - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is provided it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options] The options object. - * @param {RegExp} [options.escape] The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate] The "evaluate" delimiter. - * @param {Object} [options.imports] An object to import into the template as free variables. - * @param {RegExp} [options.interpolate] The "interpolate" delimiter. - * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. - * @param {string} [options.variable] The data object variable name. - * @param- {Object} [otherOptions] Enables the legacy `options` param signature. - * @returns {Function} Returns the compiled template function. - * @example - * - * // using the "interpolate" delimiter to create a compiled template - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // using the HTML "escape" delimiter to escape data property values - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': ' - - - - - - -

Centrally managed scientific software environments

- -

-The speed, depth and quality of open source scientific software development has grown consistently for many years. - -Additionally, the modular nature of languages like Python has resulted in a large number of dependencies needing to be packaged - -it has reached the point where no one team or individual can possibly remain abreast of the frequent changes that take place in the scientific software stack. - -This combination of pace rapidly makes centrally deployed scientific software stacks date quickly and often results in scientific -lab software environments being out of date and missing new features and bug fixes. - -

- -

-The challenge is heightened by the dichotomy of stability and modernity for users, such that logically we arrive at the prospect -wanting to deploy multiple software environments to the same systems. -

- -

The solution

-

-This article outlines the tools and a workflow that enables deployment of multiple up-to-date centrally managed scientific software environments. -

- -

-Conda has emerged as the leading tool for managing individual scientific software environments, and was chosen as a basis for extension into the centrally managed use case. -

-

-To separate concerns and to simplify development the deployment was broken into three distinct phases: -

    -
  • First, we build up a body of conda "distributions" into a conda channel - these are simply compiled packages that conda knows how to install
  • -
  • Next, we define our environments and resolve them for their dependencies
  • -
  • Finally we deploy them to a number of different targets
  • -
-

-

-Unlike conda itself we have separated the resolve and deploy stages allowing us to resolve the environment once, and then subsequently deploy to a number of different targets such as RPM, tarball or directly to disk. -

- - -

Conda channel

-

-A conda channel is simply a platform specific directory of conda distributions (.tar.bz2 files). -A distribution represents the metadata of a single package, including details of version, dependencies, and pre-compiled files that should be installed. -When conda is used to install a distribution from a channel, it recursively resolves the package's dependencies and places all necessary files in the desired destination. -

- - -

-Generating a conda distribution is best done with conda-build. -The input of conda-build is a "recipe" containing metadata about the package, its dependencies, and build steps needed to compile the package. -The metadata is stored as a YAML document and is therefore ideal for putting under a VCS such as git. -

- -

-In order to facilitate the sharing and canonicalisation of recipes in a single location, conda-forge has been developed. -It takes a community oriented maintenance model to enable package developers and software packagers to come together in a single place to collaborate publicly. -Because of this, the majority of recipes for a lab's software stack can be drawn from this public resource into a private repository of recipes. -

- -

-As part of developing conda-forge and its predecessor conda-recipes-scitools, conda-build-all was produced to orchestrate the building of a collection of recipes against a matrix of targeted dependency versions (e.g. python 2.7 and 3.5). -This same tool can be used for building a private repository of recipes. -

- - -

-With the build of all recipes complete, we can now move the distributions (the things that were actually built) into a conda channel. -At this point individuals could use vanilla conda to manage personal environments. -Combined with site-wide conda configuration it should be stressed how valuable this option is for development purposes as well as for enabling early testing of recently built distributions. -

- -

-

- -

Environment definition

- -

-Whilst conda can be used to manage personal environments it doesn't easily enable centrally managed deployments in a reproducible manner. -Instead we separate the environment "resolve & deploy" step that are part of the normal "conda create/install". -

- - - -

-Environment definitions themselves are best tracked through a VCS such as git as it enables environment diffing, provides an audit trail of what and when changes occurred. -

- - -

-conda-gitenv takes a git repository containing an environment specification and resolves this into a full manifest of the environment in a distinct "manifest" branch within the repo. -We are able to represent a "release" of a software environment by using git tags, and are therefore able to benefit from continuous development to automatically resolve the environment on a regular basis whilst having the option of putting a human in the loop to do the actual tagging. -

- - -

Environment deployment

- -

-With the environment definition in the form of a git repo in place, we now wish to deploy it. -Decoupling of the resolve and deploy steps means that we are able to deploy the same environment in a multitude of different ways. -

- - - -

-One deployment mechanism that ships with conda-gitenv enables environment deployment direct to disk. -This gives us feature parity with conda itself, with the additional benefit of having the environment git repository to track changes to the deployed environments. -This would be an excellent choice for environment deployment to a centralised directory such as a network mounted disk. -

- -

-Another deployment option is conda-rpms, which turns the environments into a collection of RPMs for installation on compatible systems (e.g. Red Hat Enterprise Linux, Fedora). -

- -

Summary

- -

-By separating the build, resolve and deploy phases we have achieved a highly customisable scientific software deployment mechanism. -

-

-We have developed conda-forge to enable community-wide recipe sharing and conda-build-all to enable building of these recipes into a fully featured conda channel of distributions. -

-

-Using any desired conda channel, conda-gitenv was developed to enable environment representation within a git repository for diffing, reviewing and tagging purposes. -

-

-With a git repository containing environment definitions we can deploy the environment in any desired form, including through RPM or by writing directly to disk. -

- - -

-

- - - diff --git a/tmp_overview_docs/wheels.png b/tmp_overview_docs/wheels.png deleted file mode 100644 index 5ced3f4cde44b5f330776f20160ddf4e3d684120..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7799 zcmV--9*E(IP)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2jB<; z2qrr7lwKnM03G*9L_t(|+U;Gva@)w#Jyt1Ebh){z48;tVdICXs0ZTEfVCo4ZhKxu? z3?)ASX;d*b{Q?mD1mXsag|ABa<&6~X7ocI&G=Bz|8O#jOr%JV6TLgi@^qJE=J>4I` zU@!mxtFYSw(AoGaf8)!q0Az(C+Odd9f!=s;~cxp%UK94994TG_Z zWS+NFiwyp1NAoq0>~Wm%5HK2q8-*kT#n)n@VK8a}kB7hvPI(9z3@JsED0c520DPkV z{Q+Rsj^-&V8U~}eXelO{M*xq=cDsB4LjbRavN3cELTah-@zdj&qy+i z&;6?Cei8t;HYO1|sc0r~d;{Q~{#RsT4kvMZIS7I!o3wQV)1npqp~T1US7F!W_OGYl z8bgKm<0H#_zO?NJ616V*&5L^Fxw)+CNc$kNG0wwR}f{!u3JuAt&5yXrhl;<(3rvKtgX z&}k6UBmbT#{=Uz26kxOpyEg(`%Z*brfac6#N~{w}C*Q{PAPABJ*DagfdGNYhYUWj9 zLW~DNFk)IcxUxT^e5%4R+_t0nVuzCOk=1&sVj)P7ZCv~SkhG)un(pCM6VY7QOf;t& zNv4A=v99c@baBLe(kYQ|Bqu}4RB{x3Qn@(;IqE_!k;Q9tz*~jgS5gm;21sTXI?$J$KDPaR z>m(XkhP~IYZG4nyD8Ay=`K4Q?YIN;Fc?}uE#O71m+KGl%b(!S47Oh6RPDq_a}2 zX6#Tkx&y;afD_}VI~eRE+s>B3&j2nd93R>CpsXBD>E{Q4WDo=ishO$7HSd^cii6x7 zk4K`Enz?Q~(GWR&lk`m!0N;@viqv@md%dBg%BqTZN<=-WYQ3b>DT zF({4Atio=K+Pyp@i&G8(Jk#IVPc(!l)H}E23!mbaRy8R&Ff59tN;N|&<^{XY8a}8f zfL;mFkP+5(#aa`Qmck^CdvpTaXZxxBf}{#c#%N2$cn5xUDp}yG+T!GsIM$hVZcM_K zIc`9i(^LF@z_jtZR#e_|3dS)ckSIh>DrE}s-M*)GG%qa{swSEa^rfAf!bQ=8o|N@G z+@p>zZS2@UE7~J|ofDctaT7E8jzg#W8GkC9TgtL7GR9?#!I$3U`cS|)S~LOHGTj6e zY~%FQV+nlRoHzN z=`FMo_+^q&gK4g86snkg-&5$FeGniT(Q_y%vR#v;p(L}31&x_(P_sV>f+tfCLG@f- zB#2;!Jpp4Pq8H`{J<1xuXXrgYR%jRMgFsxNs85y<;iL^E8I>^VLaoBCiud=k7giob zgxgvSkOC;B873FtQ7!L2;zC(k7BBiDB15cpcn*k+E5!VzvzD2IboryGSly04!A1)S(zx?vmGqbV{q3!bG!S zgby@`Rj&G#SDmAB7CK8cERof)v98YWD(sF7yyMDUZ{2N5D6{$=Zs(&(shCnkvtfiD zshcVW&{%0p1U zEodY@8Ho>fq1Z;MS%$Fp1+b#j8YcVPhfkBSzv%{HEWI=1-Q6qffSD%Q$K$ zWSPEBpETUh8fMP+9ChO~UDv7l$?a%90&oF|K2{a2%-6P(42@#~;2H)F%$^0TEN!X_R`q{cgzo6__d??UpBfYZG3IuT>Fk1lvK5WX#RF^+*BJ}ir-^ZYhBUqzYpzR;U2Io)W*t5MO0Cj#)?RqrXCE#&t2GMwB z^Jo$cH#2l#!0y?A7*(SVxkIIhMpI+@p3OmF3IhA8S1OnKIx!fP5{*VxGqrfEble-O z83q&05q#HhKR$I>uuaX3pl4h7W)jD*Ha;_hq0+8ph(^~Lj7RDlWs}RKGk)X&m@?ro zSkdeN#TIn9Pc1S$<9&&V@V-^_bxb&nouIx?E@O5gVT3K{%WdcYcs5BkL^98){ve@l z!bu&StQ|BLEDP`wIn^1AAN+y+TzA2EzoHrQK*-G3dNu;X?#A2n3b z^kC;kNwULUH>*!B+tGXh6g<66+s}CqsH&L!brQ$dRkdUx5}jH?GMftL-UR7dgex=` zo&f^+vgNU)GWk5G1q^V6EMcu`18f0!nZ)sU5Cqy*G;-61u=iwhhwg3EP-APd>r^$# ze$ADLDx3%ypg)P@S29AAtNc(`+=8z83j50^d~C3>wWt_+6X936Y>{Iw%?FGf)z=vkJRj!wQsFtvnMQ7u`oRF7Ir3 zaJP!wUiF}IdwYv;WG2=>h751iAh)UN1yYM^dUC*r=gM#D@FY2&eM_IqM7-p4gXYb> zf$!9^c?cLrU z1i=#;*xo`h7J2T^APCm<=c0sTJK>v{Bf|#F9TU%(>WY6I%cGHz>?T$_+uVw~U23ra z;aIC?HejOWv9}7lBUUr+EE)%ihPI1~ZYQn*^anw33E;Y+WOMY4mLTD{;J%t7!h7mb zRX38!^Vdwk({)l@3gB*^VOVw=S~sp;APB{)u*nv?{dP2es>wL|WG6OY zjqG6MlZpgB;W81EIDX#YH?9GE5jpHgWHUwm562~gAh>QA(R7eylAFS%>+N#M4YV;E zUkTw9A)4)hNJzz`1+LLTRxVbbs1i_-N4@YNlswnANJ2%R4lG#Lxtjy}n z8ln-{y{e-Nby2tSn-sXLvZQO7alcbtB~Ib^<=r*v6h264%#&UJcvA7rG$D0-6D?Zt z>qIgmWSauM<>UU1w%u(TzXwt>Ud`sZM`P|8RWy#OnOqL`B(LLqZVlylOdT|kC9+(b z#PImpt^!qIXI@h!L_@n(FOE#oC4jF0W`iJD)4jh!F25l~whQH)3q=O<2)jzUmR&T) zRTs^&ELdIzcDBVit?0`iBuQq5EIt1QS!qKb>Jpps;!od^CENWr5s7T>AlI?dgM%Fm zNamX^O0Nn%0KHY%t%Ptk2<9Hm$cWFeFycBXQUn*<1VEX_9z9*i}b^(st5q+V>At5RFVZLTf7hkqb3Oxm~0M z+^OE*YoM|GEO5UHyTGpk_iOxF+VUfQb$@7bQ@dSiCNW7gYl(^br9c36saerr5Cl(? zI4;tvB}I1b$)%*dzu9JfD{z0q!y%_;fNJt+%2w%H7gPcNt7t&)L|r~)J58=-2LE82 zVH8#D$6QYBL_>ylfnPZ(!VGESb}+?@#z&OZ^&klPj%EbUz#TB^2%R;+kBW(ts*H0G z1a|-~1s^u8u*||$iRT$%cdL={AP6p9PR^qpm^-%1S|Mpi^FHkeT`MM>nMkU@X_Zf# zm-eI++(Yb-b+}L~_YPTL*rylQmnogGiTCJyJJ9F@NYBEzSrre~j^>M1*iF!!!>@J5 z8o=$wyG;Njv|Bb*@Q#IS^@GU~pkoQ!HBy&U*u3bqMktqkX*|E>JvtvDYmDX{lfP%- zTP4lpXq)?$?bLaaIe3y?l5l42XfC9FPfU)&AP8oIAh;lPkdPnQs4|%E(Rl~r1*t3B zP9-@!)-?G!22>6D$I4~2qj@6XQVGwGQyWHu`bx{X1qs|dPf}#-zYx)oQo2HRykd41 zz7;j_CqbnpiUqR3VO}PIq0zNJRwHJca03&)TCf^!r`hKS*;cwf~Jf%7@9B|f$SrL*csc;IZ-8vCXTJm#06cbE~l*B6; z`jq~EC(gpRMALW-caYSuDB%z($m9Zz+tK`DJI{g)fyqV>$w-gu7U85@uJ2vZL#ZF? zG{RfKtibDJvuMa zWnys_zTFB;v=PK&U@5X7M~IcS?7c_l`+jGs@P2wI z7Q7X8p+*Ak=@YVMZiQSea-%N6yHT=uAmzbCQ!|q3p;#-};Q=>B6kf^iIHW*Cad*H? zx}@yWQe;8fu-7U{x1q3788Xqxq3Ee}U%@Vvr%=rR1$Ga}Kfm1|gC(*!jFR>y8)UQK zsZ|;sa&xT$$7tjfO_}O}e*}if{SsA1Gh~(FmfJzx_vpN6@vpscBa^V8mvXp58k8mlvKqJA~3(;BiMST?2%`e5*Nyv zEPGZoYLv|jiXRV1VYVxTt!lBBft{^SOn_rFie6}m&v=IK*;X|(JoM}@*nKclmlSVmY$hc&tTQvZWqN#h*J=Msp1+tSfWE-_q873m zE3U*CcJ4ZDJ^Nla@hp5(wwqDl993PgMi$fix_L;ES`h1WAFsf#1j#lcQR z#Ir<}#hr*A(WszS^Ih4ZSWGnPNXCa)vRK}#cjh?B$U@46Dp}`76k|GZen?4m=;z}G z`FK^`gCX)Qbx*S3BM84k^yRk5mwx2&lIkfw)I>5zyPVP~^8_2^Dl3SQ2%#O#N2{>= zNz(#mWV3>IoqnmA9ynR7C`ywAshOUp`}$I{T!l>~Ds&XET0_1G0256`YKE~P!zDhe zi_}v|m1PBJcSz-PERpRx8BsLsI-ztOmnI`cwgZ>gNPeb_NfVLF?wGAz-9-jO=*-UuWUlhs_@V7sv`vJ)wNp2U$EJ+uD{TnT3XNPfhHo9Kc6ORU_L6JwaCa z(73|mU8i5FrbzKA)tDjMGEWQMvyZI7ThB!mLuYWNP!|xE+Pc+Hq9SiuB0EmsP^@NA z-V(){gTAb22-MU162;qs%C71cXW`pjndG;#@GYT)JKeQ*RjHWm6?;J{ZLC1uB$lZe zmAES~J_}^|LsnH2U`4ZADcm62=JYgu#Tr=-%1rTnkDxZFtz5+%She$%fwJmMI=x;) zvYZk{L-*Fh;d5pwshGq@n_{9lY`70lpX;$k)|+Xm>7I{G$U-ZrYBCfw_F+N7QEAZs zDtsJe_eJ-%?|8x!EDwUS>vY&Pc_L}A%Gk7$4Bhh#>RQd-S3Ty`n>%+0MOWv3L#E{I z)?7>=+2)27ja|w{l}fm-YD-w*Jztot#zz6#A@=9pC~X64v!ZbstZ2mWNx?P7Rpy>9Ff0>Vo)?&#kyNl|`#)C+d2`aJEYSQJ1Jg zE4_E*S7lc>8!|M%!rbu+*N`f_))yX5cAdUK|B3CyhIqwU__lnH&es*G4d3y3(Z{dK zdooJqi-}5hOf>evtKd6+SoFM0aAB{bpk1uX9et+K18QekqtX;iG!6InnP{pdoEeXT zI&d&pzj51w|MBZ!Fwrn-0}8Y=7)&$_t>BDU1`|z%@GQEQ|5W8JT3Sn(VGtY)ZVu7N zZr5(cn^I)mEjN*q%aUI^gNf#Mqm5++m+(=*V_vk!tVIoB`E*G+5FwwXK z*}$<+ty`*widHe5_vrlDq$*=D(KH3$RTzDhsrlqGsUkNYz%vsLqb#_dskjUBUj>)a z-q(rlw}Y(wrmj4p1QmC6U@+0ton(AuaSl~#M0cl3A6ZeaD$W}*;V_tJ6sQ=PUeL$L z=I$(fTPVKg2gnD1%V2gEzTNSxVKC7YGuR#(tZr2>1JIY<)p?K3J!D-eeS^bhw4)`1 ziN+;@=@7wGX|QW#MXYB<4V4IHs7ZAd#b3M)&S0WBZnQVZVjCv0Kvris*%!mv$W;CW zd-@Nt>%?H95hR*t*jZCI!R`)`Hi6wH#zAmBnqRQhP<+eBZOkOYI0jDG+b|e#IfOf8 zeYO+9-xoTV%3v_j5NK6ya%aKWS@ffC9>?^+|_W|*p}on?NfUD6wa7QhQW$P zPSs4YJ2z!b2KKb|`yFHnbFL|y!m1=c7^?fc7K4eV2}IKZ@QU9vgBQq-4Xh7*=Gj5A zxmA4>g27;-5ht5GHj%pti6BAgIv-_?s$npgXv`DT2!<-^Nnmd!cPBaJTRDl!%hSV4|^D&3Kl%OhscZw%tF2iH5NQHW+DsB;b;MijvJkm3567 z%>f^(RHtTo1wS@MmMnLLEbF$cfiIC2PhV{3w!BB@V-&Br_lPVxkHJs|4hE|snxZ8p zc5W%tmU_NL?g?J&U>;1tBNYI!J`3Oe;7aNihnk zRAYXt3?>@)k)DNbqpH4)+$j#w(WqtXf#6N4d*{|ET@`Ib!=NR0ph002ov JPDHLkV1l+`#CHGy From 9bc2dd4551b22648d78e5f08030660e0bedf7c24 Mon Sep 17 00:00:00 2001 From: James Penn Date: Wed, 30 Jun 2021 10:58:57 +0000 Subject: [PATCH 3/9] Added Dockerfile for dev environment --- Dockerfile | 20 ++++++++++++++++++++ dev-env.yml | 8 ++++++++ 2 files changed, 28 insertions(+) create mode 100644 Dockerfile create mode 100644 dev-env.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c26e204 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +FROM continuumio/miniconda3 + +SHELL ["/bin/bash", "-c"] + +ENV TINI_VERSION v0.19.0 +ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini +RUN chmod +x /tini + + +COPY ./dev-env.yml environment.yml +RUN conda env create --quiet -n conda-rpms-dev --file environment.yml + +RUN echo "source activate conda-rpms-dev" > ~/.bashrc +ENV PATH /opt/conda/envs/conda-rpms-dev/bin:$PATH + +COPY . /conda-rpms +WORKDIR /conda-rpms +RUN pip install -e .[test] + +ENTRYPOINT ["/tini", "--"] \ No newline at end of file diff --git a/dev-env.yml b/dev-env.yml new file mode 100644 index 0000000..4c12566 --- /dev/null +++ b/dev-env.yml @@ -0,0 +1,8 @@ +name: conda-rpms-dev +dependencies: + - jinja2 + - conda + - pytest + - mock + - pytest-cov + - click From ec27cdef2df3bd4b0399560cd1d67819a937c460 Mon Sep 17 00:00:00 2001 From: James Penn Date: Wed, 16 Jun 2021 13:25:42 +0100 Subject: [PATCH 4/9] Tidying up conda_compat and added sign --- .gitignore | 1 + src/conda_rpms/__init__.py | 2 +- src/conda_rpms/conda_compat.py | 2 +- src/conda_rpms/generate.py | 17 +++----- src/conda_rpms/sign.py | 79 ++++++++++++++++++++++++++++++++++ 5 files changed, 89 insertions(+), 12 deletions(-) create mode 100755 src/conda_rpms/sign.py diff --git a/.gitignore b/.gitignore index 0e66f44..4bdcdef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *.py[co] rpmbuild/ +_version.py # Packages *.egg diff --git a/src/conda_rpms/__init__.py b/src/conda_rpms/__init__.py index c7810fb..f0aee1f 100644 --- a/src/conda_rpms/__init__.py +++ b/src/conda_rpms/__init__.py @@ -1 +1 @@ -__version__ = "2.0.dev0" +from ._version import version as __version__ diff --git a/src/conda_rpms/conda_compat.py b/src/conda_rpms/conda_compat.py index 28574ea..deb8b64 100755 --- a/src/conda_rpms/conda_compat.py +++ b/src/conda_rpms/conda_compat.py @@ -1,6 +1,6 @@ from __future__ import annotations -from dataclasses import dataclass, asdict, fields +from dataclasses import asdict, dataclass, fields from pathlib import Path from typing import Iterable, List, Optional diff --git a/src/conda_rpms/generate.py b/src/conda_rpms/generate.py index bc5ea1d..6837026 100755 --- a/src/conda_rpms/generate.py +++ b/src/conda_rpms/generate.py @@ -169,7 +169,7 @@ def create_installer( pkg = CondaPackage.from_url(f"python=={py_ver}") spec = write_installer_rpm_spec(pkg, outdir, install_prefix, rpm_namespace) tarball = make_package_tarball(pkg) - shutil.copy(install_script_path, outdir / "SOURCES") + shutil.copy(install_script_path, outdir / "SOURCES" / install_script_path.name) return PackageSpec(pkg, spec, tarball) @@ -186,8 +186,10 @@ def environment_to_rpms( with open(lockfile, "r") as f: urls = read_conda_lockfile(f) - if not outdir.is_dir(): - outdir.mkdir() + sourcedir = outdir / "SOURCES" + specdir = outdir / "SPECS" + for dir in (outdir, sourcedir, specdir): + dir.mkdir(exist_ok=True) log.info(f"Generating RPM environment from {lockfile}.") log.info(f"{len(urls)} packages to be rendered.") @@ -196,8 +198,6 @@ def environment_to_rpms( pkgs = [CondaPackage.from_url(url) for url in urls] log.info("Rendering all package specs.") - specdir = outdir / "SPECS" - specdir.mkdir(exist_ok=True) specs: List[PackageSpec] = [create_rpm_spec(pkg, *config) for pkg in pkgs] log.info("Rendering installer") @@ -205,10 +205,9 @@ def environment_to_rpms( specs.append(installer) log.info("Copying sources") - sourcedir = outdir / "SOURCES" - sourcedir.mkdir(exist_ok=True) for spec in specs: - shutil.copy(spec.tarball, sourcedir) + log.info("Coping %s to %s", spec.tarball, sourcedir / spec.tarball.name) + shutil.copy(spec.tarball, sourcedir / spec.tarball.name) environment = CondaEnvironment(args.name, "1.0", None) write_environment_rpm_spec(environment, pkgs, outdir, install_prefix, rpm_namespace) @@ -224,8 +223,6 @@ def create_rpm_spec(pkg, outdir, install_prefix, rpm_namespace): import argparse from textwrap import dedent - from tqdm.contrib.logging import logging_redirect_tqdm - parser = argparse.ArgumentParser() parser.add_argument( "file", help="The conda lockfile to produce an RPM package for." diff --git a/src/conda_rpms/sign.py b/src/conda_rpms/sign.py new file mode 100755 index 0000000..19a6e0b --- /dev/null +++ b/src/conda_rpms/sign.py @@ -0,0 +1,79 @@ +from pathlib import Path +import subprocess +from typing import Any, List + +from .logger import log + + +def find_rpm_deps(rpm: Path) -> List[str]: + """For a given rpm, return all its named dependencies.""" + namespace = rpm.name.split("-")[0] + proc = subprocess.run(["rpm", "-qpR", rpm], capture_output=True) + lines = proc.stdout.decode().splitlines() + deps = [line for line in lines if line.startswith(namespace)] + return deps + +def _sign_rpm(rpm: Path, *args: str) -> None: + log.info(f"Signing {rpm.name}.") + proc = subprocess.run(["rpmsign", "--addsign", *args, rpm], capture_output=True) + log.debug(proc.stdout.decode()) + log.debug(proc.stderr.decode()) + proc.check_returncode() + +def sign_rpm(rpm: Path, *args: str, include_dependencies=True) -> None: + """Sign an rpm. + + If `include_dependencies` is True (the default), also inspect the + rpm for its dependencies and sign those rpms too, assumed to be + found next to the parent rpm file. + + By default, no args are passed to `rpmsign`, instead it is assumed + that a `~/.rpmmacros` file is available containing configuration. + Alternatively, any command line arguments can be given as additional + arguments to this function. + + Returns None, raises error on non-zero exit code from `rpmsign`. + """ + rpms = [rpm] + if include_dependencies: + rpm_dir = rpm.parent + deps = find_rpm_deps(rpm) + + for d in deps: + # look in the same directory as `rpm` and find + # all the `.rpm` files that match the dependency name + matches = list(sorted(rpm_dir.glob(f'{d}*.rpm'))) + rpms.extend(matches) + + for rpm in rpms: + _sign_rpm(rpm, *args) + +if __name__ == "__main__": + import argparse + from textwrap import dedent + import logging + + parser = argparse.ArgumentParser() + parser.add_argument( + "rpm", help="The rpm file to sign." + ) + parser.add_argument( + "--no-deps", action='store_true', + help=dedent( + r"""Set this to only sign the passed argument and ignore dependencies. + + By default, rpms are inspected for their dependecies + and these are signed too (assumed to be found next to the + passed rpm).""" + ) + ) + + parser.add_argument('--verbose', '-v', action='store_true') + + args = parser.parse_args() + + if args.verbose: + log.setLevel("DEBUG") + + rpm = Path(args.rpm).resolve() + sign_rpm(rpm, include_dependencies=(not args.no_deps)) \ No newline at end of file From 05c656db0e7b894e531c8235a1fc0f3d1aaa2dc2 Mon Sep 17 00:00:00 2001 From: James Penn Date: Wed, 16 Jun 2021 13:37:35 +0100 Subject: [PATCH 5/9] Removed build and sign --- README.md | 55 +++++++++++----------------- src/conda_rpms/build.py | 61 ------------------------------- src/conda_rpms/sign.py | 79 ----------------------------------------- 3 files changed, 21 insertions(+), 174 deletions(-) delete mode 100644 src/conda_rpms/build.py delete mode 100755 src/conda_rpms/sign.py diff --git a/README.md b/README.md index 5d67d66..ea46740 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,7 @@ -Create RPMs from a conda-gitenv -=============================== +Create RPMs from a conda environment +=================================== -conda-rpms is designed to convert a resolved [conda-gitenv](https://github.com/SciTools/conda-gitenv) environment into a collection of RPM specs suitable for deployment on compatible platforms (Red Hat Enterprise Linux, Fedora, etc.). - -A high level description of the motivation for the creation of RPMs from a [conda-gitenv](https://github.com/SciTools/conda-gitenv) is described in the [centrally managed scientific software workflow](https://rawgit.com/pelson/conda-rpms/master/tmp_overview_docs/scitools-env-workflow.html) document. - -To transform the conda distribution to RPM specs, conda-rpms uses tools including git-python, Jinja and conda. +conda-rpms is designed to convert a conda environment into a collection of RPM specs suitable for deployment on compatible platforms (Red Hat Enterprise Linux, Fedora, etc.). Because a built RPM knows its destined installation location, a number of RPM abstractions have been made that enable us to retain conda's hard-linking and relocatability benefits. @@ -13,12 +9,20 @@ Because a built RPM knows its destined installation location, a number of RPM ab Usage ===== -There are two conda-rpms command entrypoints. - -`python -m conda_rpms.build_rpm_structure` creates the RPM specs and sources. +There is a single conda-rpms command entrypoint: -`python -m conda_rpms.build` is a general purpose rpmbuild wrapper that inspects the RPM build directory for RPMs that have already been built, and then builds those that haven't. This is a general purpose tool that has nothing to do with conda - if you are aware of such a tool already existing, please raise an issue let us know! `;)` +`python -m conda_rpms.generate` creates the RPM specs and sources. +`conda-rpms` no longer builds specs to RPMs, this is left to the user as may +require context-specific congfiguration. However, typically it can be achieved +with something like the example below. +Assuming you have a [conda-lock](https://github.com/conda-incubator/conda-lock) +named `~/data_science.lock`: +``` +python -m conda_rpms.generate --name data_science --output rpmbuild ~/data_science.lock +rpmbuild -bb --define "_topdir $(pwd)/rpmbuild" rpmbuild/SPECS/*. +spec +``` RPM Types ========= @@ -26,32 +30,15 @@ RPM Types Package RPM ----------- -RPM name format: ``-pkg---`` +RPM name format: ``-pkg---`` A package RPM represents the conda "package cache" (the thing that normally lives in `/pkgs/--`). A package RPM *does not* express its dependencies and can not be usefully installed as a standalone entity. -Tagged environment RPM ----------------------- - -RPM name format: ``-env--tag-`` - -A tagged environment RPM represents a resolved conda environment. -It depends on all Package RPMs that should be installed in order to produce a working environment. The tagged environment RPM knows its target installation prefix, and uses conda functionality at install time to link the Package RPMs to the desired installation prefix. - -Labelled environment RPM ------------------------- - -RPM name format: `-env--label-