diff --git a/CHANGES.md b/CHANGES.md index a4c683a..f6ebaa2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,8 +1,119 @@ -### 0.14.9 (2018-03-19 13:10:00 UTC) +### 0.15.0 (2018-03-22 00:00:00 UTC) + +* Add showRSS torrent provider +* Add choice to delete watched episodes from a list of played media at Kodi, Emby, and/or Plex, + instructions at Shows/History/Layout/"Watched" +* Add installable SickGear Kodi repository containing addon "SickGear Watched State Updater" +* Change add Emby setting for watched state scheduler at Config/Notifications/Emby/"Update watched interval" +* Change add Plex setting for watched state scheduler at Config/Notifications/Plex/"Update watched interval" +* Change add map parent folder setting at Notifications for Emby, Kodi, and Plex +* Add API cmd=sg.updatewatchedstate, instructions for use are linked to in layout "Watched" at /history +* Change history page table filter input values are saved across page refreshes +* Change history page table filter inputs, accept values like "dvd or web" to only display both +* Change history page table filter inputs, press 'ESC' key inside a filter input to reset it +* Add provider activity stats to Shows/History/Layout/ drop down +* Change move provider failures table from Manage/Media Search to Shows/History/Layout/Provider fails +* Change sort provider failures by most recent failure, and with paused providers at the top +* Add SickGear-NZBGet dedicated post processing script, see.. \autoProcessTV\SickGear-NG\INSTALL.txt +* Add non standard multi episode name parsing e.g. S01E02and03 and 1x02and03and04 +* Change overhaul and add API functions +* Change API version... start with 10 +* Change set application response header to 'SickGear' + add API version +* Change return timezone (of network) in API +* Add indexer to calls +* Add SickGear Command tip for old SickBeard commands +* Add warning old sickbeard API calls only support tvdb shows +* Add "tvdbid" fallback only for sickbeard calls +* Add listcommands +* Add list of all commands (old + new) in listcommand page at the beginning +* Change hide 'listcommands' command from commands list, since it needs the API builder CSS + is html not json +* Add missing help in webapi +* Add episode info: absolute_number, scene_season, scene_episode, scene_absolute_number +* Add fork to SB command +* Add sg +* Add sg.activatescenenumbering +* Add sg.addrootdir +* Add sg.checkscheduler +* Add sg.deleterootdir +* Add sg.episode +* Add sg.episode.search +* Add sg.episode.setstatus +* Add sg.episode.subtitlesearch +* Add sg.exceptions +* Add sg.forcesearch +* Add sg.future +* Add sg.getdefaults +* Add sg.getindexericon +* Add sg.getindexers to list all indexers +* Add sg.getmessages +* Add sg.getnetworkicon +* Add sg.getrootdirs +* Add sg.getqualities +* Add sg.getqualitystrings +* Add sg.history +* Add sg.history.clear +* Add sg.history.trim +* Add sg.listtraktaccounts +* Add sg.listignorewords +* Add sg.listrequiedwords +* Add sg.logs +* Add sg.pausebacklog +* Add sg.postprocess +* Add sg.ping +* Add sg.restart +* Add sg.searchqueue +* Add sg.searchtv to search all indexers +* Add sg.setexceptions +* Add sg.setignorewords +* Add sg.setrequiredwords +* Add sg.setscenenumber +* Add sg.show +* Add sg.show.addexisting +* Add sg.show.addnew +* Add sg.show.cache +* Add sg.show.delete +* Add sg.show.getbanner +* Add sg.show.getfanart +* Add sg.show.getposter +* Add sg.show.getquality +* Add sg.show.listfanart +* Add sg.show.ratefanart +* Add sg.show.seasonlist +* Add sg.show.seasons +* Add sg.show.setquality +* Add sg.show.stats +* Add sg.show.refresh +* Add sg.show.pause +* Add sg.show.update +* Add sg.shows +* Add sg.shows.browsetrakt +* Add sg.shows.forceupdate +* Add sg.shows.queue +* Add sg.shows.stats +* Change sickbeard to sickgear +* Change sickbeard_call to property +* Change sg.episode.setstatus allow setting of quality +* Change sg.history, history command output +* Change sg.searchtv to list of indexers +* Add uhd4kweb to qualities +* Add upgrade_once to add existing shows +* Add upgrade_once to add new show +* Add upgrade_once to show quality settings (get/set) +* Add 'ids' to Show + Shows +* Add ids to coming eps + get tvdb id from ids +* Add 'status_str' to coming eps +* Add 'local_datetime' to comming eps + runtime +* Add X-Filename response header to getbanner, getposter +* Add X-Fanartname response header for sg.show.getfanart +* Change remove some non-release group stuff from newnab results + + +### 0.14.9 (2018-03-19 13:10:00 UTC) Change remove dead tor caches and stop searching episodes that have a magnet saved Change AlphaRatio provider freeleech mode; prevent spoiling user ratio from ambiguous filtered results + ### 0.14.8 (2018-03-13 22:00:00 UTC) Fix changing status from "Skipped" to "Wanted" in Manage/Episode Status diff --git a/autoProcessTV/SickGear-NG/INSTALL.txt b/autoProcessTV/SickGear-NG/INSTALL.txt new file mode 100644 index 0000000..015215d --- /dev/null +++ b/autoProcessTV/SickGear-NG/INSTALL.txt @@ -0,0 +1,34 @@ +SickGear PostProcessing script for NZBGet +========================================= + +If NZBGet v17+ is installed on the same system as SickGear then as a local install, + +1) Add the location of this script file to NZBGet Settings/PATHS/ScriptDir + +2) Navigate to any named TV category at Settings/Categories, click "Choose" Category.Extensions then Apply SickGear-NG + +This is the best set up to automatically get script updates from SickGear + +############# + +If NZBGet v16 or earlier is installed, then as an older install, + +1) Copy the directory with/or this single script file to path set in NZBGet Settings/PATHS/ScriptDir + +2) Refresh the NZBGet page and navigate to Settings/SickGear-NG + +3) Click View -> Compact to remove any tick and un hide tips and suggestions + +4) The bare minimum change is the sg_base_path setting or enter `python -m pip install requests` at admin commandline + +5) Navigate to any named TV category at Settings/Categories, click "Choose" Category.Extensions then Apply SickGear-NG + +You will need to manually update your script with this set up + +############# + +Notes: +Debian doesn't have pip, _if_ requests is needed, try "apt install python-requests" + +----- +Enjoy diff --git a/autoProcessTV/SickGear-NG/SickGear-NG.py b/autoProcessTV/SickGear-NG/SickGear-NG.py new file mode 100755 index 0000000..72f91f2 --- /dev/null +++ b/autoProcessTV/SickGear-NG/SickGear-NG.py @@ -0,0 +1,647 @@ +#!/usr/bin/env python +# +# ############################################################################## +# ############################################################################## +# +# SickGear PostProcessing script for NZBGet +# ========================================= +# +# If NZBGet v17+ is installed on the same system as SickGear then as a local install, +# +# 1) Add the location of this script file to NZBGet Settings/PATHS/ScriptDir +# +# 2) Navigate to any named TV category at Settings/Categories, click "Choose" Category.Extensions then Apply SickGear-NG +# +# This is the best set up to automatically get script updates from SickGear +# +# ############# +# +# If NZBGet v16 or earlier is installed, then as an older install, +# +# 1) Copy the directory with/or this single script file to path set in NZBGet Settings/PATHS/ScriptDir +# +# 2) Refresh the NZBGet page and navigate to Settings/SickGear-NG +# +# 3) Click View -> Compact to remove any tick and un hide tips and suggestions +# +# 4) The bare minimum change is the sg_base_path setting or enter `python -m pip install requests` at admin commandline +# +# 5) Navigate to any named TV category at Settings/Categories, click "Choose" Category.Extensions then Apply SickGear-NG +# +# You will need to manually update your script with this set up +# +# ############ +# +# Notes: +# Debian doesn't have pip, _if_ requests is needed, try "apt install python-requests" +# ----- +# Enjoy +# +# ############################################################################## +# ############################################################################## +# +# Copyright (C) 2016 SickGear Developers +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# + +############################################################################## +### NZBGET QUEUE/POST-PROCESSING SCRIPT ### +### QUEUE EVENTS: NZB_ADDED, NZB_DELETED, URL_COMPLETED, NZB_MARKED ### + +# Send PostProcessing requests to SickGear +# +# PostProcessing-Script version: 1.3. +# +# +# +# Setup steps NZBGet Version +# +# +# +# 1 +# +# +# If NZBGet v17 or newer is installed on the same system as SickGear, then add the +# location of this script file to NZBGet Settings/PATHS/ScriptDir +#

+# Or, if NZBGet v16 or earlier is installed on the same system as SickGear and +# if python requests library +# is not installed, then sg_base_path must be set +#
+#
+# +# +# 2 +# +# +# Then, for any install type, click Choose +# then apply "SickGear-NG" in a TV Category at NZBGet Settings/CATEGORIES, +# save all changes and reload NZBGet +# +# +# +#
+# +# Note This script requires Python 2.7+ and may not work with Python 3.x+ +# +############################################################################## +### OPTIONS ### +# +#test connection@Test SickGear connection +# +# +# Optional +# SickGear base installation path. +# use where NZBGet v16 or older is installed on the same system as SickGear, and no python requests library is installed +# (use "pip list" to check installed modules) +#sg_base_path= + +# +# Optional +# SickGear server ipaddress [default:127.0.0.1 aka localhost]. +# change if SickGear is not installed on the same localhost as NZBGet +#sg_host=localhost + +# +# Optional +# SickGear HTTP Port [default:8081] (1025-65535). +#sg_port=8081 + +# +# Optional +# SickGear Username. +#sg_username= + +# +# Optional +# SickGear Password. +#sg_password= + +# +# Optional +# SickGear has SSL enabled [default:No] (yes, no). +#sg_ssl=no + +# +# Advanced use +# SickGear Web Root. +# change if using a custom SickGear web_root setting (e.g. for a reverse proxy) +#sg_web_root= + +# +# Optional +# Print more logging messages [default:No] (yes, no). +# For debugging or if you need to report a bug. +#sg_verbose=no + +### NZBGET QUEUE/POST-PROCESSING SCRIPT ### +############################################################################## +import locale +import os +import re +import sys + +__version__ = '1.3' + +verbose = 0 or 'yes' == os.environ.get('NZBPO_SG_VERBOSE', 'no') + +# NZBGet exit codes for post-processing scripts (Queue-scripts don't have any special exit codes). +POSTPROCESS_SUCCESS, POSTPROCESS_ERROR, POSTPROCESS_NONE = 93, 94, 95 + +failed = False + +# define minimum dir size, downloads under this size will be handled as failure +min_dir_size = 20 * 1024 * 1024 + + +class Logger: + INFO, DETAIL, ERROR, WARNING = 'INFO', 'DETAIL', 'ERROR', 'WARNING' + # '[NZB]' send a command message to NZBGet (no log) + NZB = 'NZB' + + def __init__(self): + pass + + @staticmethod + def safe_print(msg_type, message): + try: + print '[%s] %s' % (msg_type, message.encode(SYS_ENCODING)) + except (StandardError, Exception): + try: + print '[%s] %s' % (msg_type, message) + except (StandardError, Exception): + try: + print '[%s] %s' % (msg_type, repr(message)) + except (StandardError, Exception): + pass + + @staticmethod + def log(message, msg_type=INFO): + size = 900 + if size > len(message): + Logger.safe_print(msg_type, message) + else: + for group in (message[pos:pos + size] for pos in xrange(0, len(message), size)): + Logger.safe_print(msg_type, group) + + +if 'nt' == os.name: + import ctypes + + class WinEnv: + def __init__(self): + pass + + @staticmethod + def get_environment_variable(name): + name = unicode(name) # ensures string argument is unicode + n = ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0) + env_value = None + if n: + buf = ctypes.create_unicode_buffer(u'\0'*n) + ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n) + env_value = buf.value + verbose and Logger.log('Get var(%s) = %s' % (name, env_value or n)) + return env_value + + def __getitem__(self, key): + return self.get_environment_variable(key) + + def get(self, key, default=None): + r = self.get_environment_variable(key) + return r if r is not None else default + + env_var = WinEnv() +else: + class LinuxEnv(object): + def __init__(self, environ): + self.environ = environ + + def __getitem__(self, key): + v = self.environ.get(key) + try: + return v.decode(SYS_ENCODING) if isinstance(v, str) else v + except (UnicodeDecodeError, UnicodeEncodeError): + return v + + def get(self, key, default=None): + v = self[key] + return v if v is not None else default + + env_var = LinuxEnv(os.environ) + + +SYS_ENCODING = None +try: + locale.setlocale(locale.LC_ALL, '') +except (locale.Error, IOError): + pass +try: + SYS_ENCODING = locale.getpreferredencoding() +except (locale.Error, IOError): + pass +if not SYS_ENCODING or SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): + SYS_ENCODING = 'UTF-8' + + +verbose and Logger.log('%s(%s) env dump = %s' % (('posix', 'nt')['nt' == os.name], SYS_ENCODING, os.environ)) + + +class Ek: + def __init__(self): + pass + + @staticmethod + def fix_string_encoding(x): + if str == type(x): + try: + return x.decode(SYS_ENCODING) + except UnicodeDecodeError: + return None + elif unicode == type(x): + return x + return None + + @staticmethod + def fix_list_encoding(x): + if type(x) not in (list, tuple): + return x + return filter(lambda i: None is not i, map(Ek.fix_string_encoding, i)) + + @staticmethod + def encode_item(x): + try: + return x.encode(SYS_ENCODING) + except UnicodeEncodeError: + return x.encode(SYS_ENCODING, 'ignore') + + @staticmethod + def ek(func, *args, **kwargs): + if 'nt' == os.name: + func_result = func(*args, **kwargs) + else: + func_result = func(*[Ek.encode_item(x) if type(x) == str else x for x in args], **kwargs) + + if type(func_result) in (list, tuple): + return Ek.fix_list_encoding(func_result) + elif str == type(func_result): + return Ek.fix_string_encoding(func_result) + return func_result + + +# Depending on the mode in which the script was called (queue-script NZBNA_DELETESTATUS +# or post-processing-script) a different set of parameters (env. vars) +# is passed. They also have different prefixes: +# - NZBNA in queue-script mode; +# - NZBPP in pp-script mode. +env_run_mode = ('PP', 'NA')['NZBNA_EVENT' in os.environ] + + +def nzbget_var(name, default='', namespace=env_run_mode): + return env_var.get('NZB%s_%s' % (namespace, name), default) + + +def nzbget_opt(name, default=''): + return nzbget_var(name, default, 'OP') + + +def nzbget_plugin_opt(name, default=''): + return nzbget_var('SG_%s' % name, default, 'PO') + + +sg_path = nzbget_plugin_opt('BASE_PATH') +if not sg_path or not Ek.ek(os.path.isdir, sg_path): + try: + script_path = Ek.ek(os.path.dirname, __file__) + sg_path = Ek.ek(os.path.dirname, Ek.ek(os.path.dirname, script_path)) + except (StandardError, Exception): + pass +if sg_path and Ek.ek(os.path.isdir, Ek.ek(os.path.join, sg_path, 'lib')): + sys.path.insert(1, Ek.ek(os.path.join, sg_path, 'lib')) + + +try: + import requests +except ImportError: + Logger.log('You must set SickGear sg_base_path in script config or install python requests library', Logger.ERROR) + sys.exit(1) + + +def get_size(start_path='.'): + if Ek.ek(os.path.isfile, start_path): + return Ek.ek(os.path.getsize, start_path) + total_size = 0 + for dirpath, dirnames, filenames in Ek.ek(os.walk, start_path): + for f in filenames: + if not f.lower().endswith(('.nzb', '.jpg', '.jpeg', '.gif', '.png', '.tif', '.nfo', '.txt', '.srt', '.sub', + '.sbv', '.idx', '.bat', '.sh', '.exe', '.pdf')): + fp = Ek.ek(os.path.join, dirpath, f) + total_size += Ek.ek(os.path.getsize, fp) + return total_size + + +def try_int(s, s_default=0): + try: + return int(s) + except (StandardError, Exception): + return s_default + + +def try_float(s, s_default=0): + try: + return float(s) + except (StandardError, Exception): + return s_default + + +class ExitReason: + def __init__(self): + pass + PP_SUCCESS = 0 + FAIL_SUCCESS = 1 + MARKED_BAD_SUCCESS = 2 + DELETED = 5 + SAME_DUPEKEY = 10 + UNFINISHED_DOWNLOAD = 11 + NONE = 20 + NONE_SG = 21 + PP_ERROR = 25 + FAIL_ERROR = 26 + MARKED_BAD_ERROR = 27 + + +def script_exit(status, reason, runmode=None): + Logger.log('NZBPR_SICKGEAR_PROCESSED=%s_%s_%s' % (status, runmode or env_run_mode, reason), Logger.NZB) + sys.exit(status) + + +def get_old_status(): + old_status = env_var.get('NZBPR_SICKGEAR_PROCESSED', '') + status_regex = re.compile(r'(\d+)_(\w\w)_(\d+)') + if old_status and status_regex.search(old_status) is not None: + s = status_regex.match(old_status) + return try_int(s.group(1)), s.group(2), try_int(s.group(3)) + return POSTPROCESS_NONE, env_run_mode, ExitReason.NONE + + +markbad = 'NZB_MARKED' == env_var.get('NZBNA_EVENT') and 'BAD' == env_var.get('NZBNA_MARKSTATUS') + +good_statuses = [(POSTPROCESS_SUCCESS, 'PP', ExitReason.FAIL_SUCCESS), # successfully failed pp'ed + (POSTPROCESS_SUCCESS, 'NA', ExitReason.FAIL_SUCCESS), # queue, successfully failed sent + (POSTPROCESS_SUCCESS, 'NA', ExitReason.MARKED_BAD_SUCCESS)] # queue, mark bad+successfully failed sent + +if not markbad: + good_statuses.append((POSTPROCESS_SUCCESS, 'PP', ExitReason.PP_SUCCESS)) # successfully pp'ed + + +# Start up checks +def start_check(): + + # Check if the script is called from a compatible NZBGet version (as queue-script or as pp-script) + nzbget_version = re.search(r'^(\d+\.\d+)', nzbget_opt('VERSION', '0.1')) + nzbget_version = nzbget_version.group(1) if nzbget_version and len(nzbget_version.groups()) >= 1 else '0.1' + nzbget_version = try_float(nzbget_version) + if 17 > nzbget_version: + Logger.log('This script is designed to be called from NZBGet 17.0 or later.') + sys.exit(0) + + if 'NZB_ADDED' == env_var.get('NZBNA_EVENT'): + Logger.log('NZBPR_SICKGEAR_PROCESSED=', Logger.NZB) # reset var in case of Download Again + sys.exit(0) + + # This script processes only certain queue events. + # For compatibility with newer NZBGet versions it ignores event types it doesn't know + if env_var.get('NZBNA_EVENT') not in ['NZB_DELETED', 'URL_COMPLETED', 'NZB_MARKED', None]: + sys.exit(0) + + if 'NZB_MARKED' == env_var.get('NZBNA_EVENT') and 'BAD' != env_var.get('NZBNA_MARKSTATUS'): + Logger.log('Marked as [%s], nothing to do, existing' % env_var.get('NZBNA_MARKSTATUS', '')) + sys.exit(0) + + old_exit_status = get_old_status() + if old_exit_status in good_statuses and not ( + ExitReason.FAIL_SUCCESS == old_exit_status[2] and 'SUCCESS' == nzbget_var('TOTALSTATUS')): + Logger.log('Found result from a previous completed run, exiting') + script_exit(old_exit_status[0], old_exit_status[2], old_exit_status[1]) + + # If called via "Post-process again" from history details dialog the download may not exist anymore + if 'NZBNA_EVENT' not in os.environ and 'NZBPP_DIRECTORY' in os.environ: + directory = nzbget_var('DIRECTORY') + if not directory or not Ek.ek(os.path.exists, directory): + Logger.log('No files for postprocessor, look back in your NZBGet logs if required, exiting') + script_exit(POSTPROCESS_NONE, ExitReason.NONE) + + +def call_nzbget_direct(url_command): + # Connect to NZBGet and call an RPC-API method without using python's XML-RPC which is slow for large amount of data + # First we need connection info: host, port and password of NZBGet server, NZBGet passes configuration options to + # scripts using environment variables + host, port, username, password = [nzbget_opt('CONTROL%s' % name) for name in 'IP', 'PORT', 'USERNAME', 'PASSWORD'] + url = 'http://%s:%s/jsonrpc/%s' % ((host, '127.0.0.1')['0.0.0.0' == host], port, url_command) + + try: + response = requests.get(url, auth=(username, password)) + except requests.RequestException: + return '' + + return response.content if response.ok else '' + + +def call_sickgear(nzb_name, dir_name, test=False): + + global failed + ssl, host, port, username, password, webroot = [nzbget_plugin_opt(name, default) for name, default in + ('SSL', 'no'), ('HOST', 'localhost'), ('PORT', '8081'), + ('USERNAME', ''), ('PASSWORD', ''), ('WEB_ROOT', '')] + protocol = 'http%s://' % ('', 's')['yes' == ssl] + webroot = any(webroot) and '/%s' % webroot.strip('/') or '' + url = '%s%s:%s%s/home/postprocess/processEpisode' % (protocol, host, port, webroot) + + dupescore = nzbget_var('DUPESCORE') + dupekey = nzbget_var('DUPEKEY') + nzbid = nzbget_var('NZBID') + params = {'nzbName': '%s.nzb' % (nzb_name and re.sub('(?i)\.nzb$', '', nzb_name) or None), 'dir': dir_name, + 'failed': int(failed), 'quiet': 1, 'stream': 1, 'force': 1, 'dupekey': dupekey, 'dupescore': dupescore, + 'nzbid': nzbid, 'ppVersion': __version__, 'is_basedir': 0, 'client': 'nzbget'} + if test: + params['test'] = '1' + Logger.log('Opening URL: %s with params: %s' % (url, params)) + try: + s = requests.Session() + if username or password: + login = '%s%s:%s%s/login' % (protocol, host, port, webroot) + login_params = {'username': username, 'password': password} + s.post(login, data=login_params, stream=True, verify=False) + r = s.get(url, auth=(username, password), params=params, stream=True, verify=False, timeout=900) + except (StandardError, Exception): + Logger.log('Unable to open URL: %s' % url, Logger.ERROR) + return False + + success = False + try: + if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]: + Logger.log('Server returned status %s' % str(r.status_code), Logger.ERROR) + return False + + for line in r.iter_lines(): + if line: + Logger.log(line, Logger.DETAIL) + if test: + if 'Connection success!' in line: + return True + elif not failed and 'Failed download detected:' in line: + failed = True + global markbad + markbad = True + Logger.log('MARK=BAD', Logger.NZB) + success = ('Processing succeeded' in line or 'Successfully processed' in line or + (1 == failed and 'Successful failed download processing' in line)) + except Exception as e: + Logger.log(str(e), Logger.ERROR) + + return success + + +def find_dupekey_history(dupekey, nzb_id): + + if not dupekey: + return False + data = call_nzbget_direct('history?hidden=true') + cur_status = cur_dupekey = cur_id = '' + cur_dupescore = 0 + for line in data.splitlines(): + if line.startswith('"NZBID" : '): + cur_id = line[10:-1] + elif line.startswith('"Status" : '): + cur_status = line[12:-2] + elif line.startswith('"DupeKey" : '): + cur_dupekey = line[13:-2] + elif line.startswith('"DupeScore" : '): + cur_dupescore = try_int(line[14:-1]) + elif cur_id and line.startswith('}'): + if (cur_status.startswith('SUCCESS') and dupekey == cur_dupekey and + cur_dupescore >= try_int(nzbget_var('DUPESCORE')) and cur_id != nzb_id): + return True + cur_status = cur_dupekey = cur_id = '' + cur_dupescore = 0 + return False + + +def find_dupekey_queue(dupekey, nzb_id): + + if not dupekey: + return False + data = call_nzbget_direct('listgroups') + cur_status = cur_dupekey = cur_id = '' + for line in data.splitlines(): + if line.startswith('"NZBID" : '): + cur_id = line[10:-1] + elif line.startswith('"Status" : '): + cur_status = line[12:-2] + elif line.startswith('"DupeKey" : '): + cur_dupekey = line[13:-2] + elif cur_id and line.startswith('}'): + if 'PAUSED' != cur_status and dupekey == cur_dupekey and cur_id != nzb_id: + return True + cur_status = cur_dupekey = cur_id = '' + return False + + +def check_for_failure(directory): + + failure = True + dupekey = nzbget_var('DUPEKEY') + if 'PP' == env_run_mode: + total_status = nzbget_var('TOTALSTATUS') + status = nzbget_var('STATUS') + if 'WARNING' == total_status and status in ['WARNING/REPAIRABLE', 'WARNING/SPACE', 'WARNING/DAMAGED']: + Logger.log('WARNING/REPAIRABLE' == status and 'Download is damaged but probably can be repaired' or + 'WARNING/SPACE' == status and 'Out of Diskspace' or + 'Par-check is required but is disabled in settings', Logger.WARNING) + script_exit(POSTPROCESS_ERROR, ExitReason.UNFINISHED_DOWNLOAD) + elif 'DELETED' == total_status: + Logger.log('Download was deleted and manually processed, nothing to do, exiting') + script_exit(POSTPROCESS_NONE, ExitReason.DELETED) + elif 'SUCCESS' == total_status: + # check for min dir size + if get_size(directory) > min_dir_size: + failure = False + else: + nzb_id = nzbget_var('NZBID') + if (not markbad and find_dupekey_queue(dupekey, nzb_id)) or find_dupekey_history(dupekey, nzb_id): + Logger.log('Download with same Dupekey in download queue or history, exiting') + script_exit(POSTPROCESS_NONE, ExitReason.SAME_DUPEKEY) + nzb_delete_status = nzbget_var('DELETESTATUS') + if nzb_delete_status == 'MANUAL': + Logger.log('Download was manually deleted, exiting') + script_exit(POSTPROCESS_NONE, ExitReason.DELETED) + + # Check if it's a Failed Download not added by SickGear + if failure and (not dupekey or not dupekey.startswith('SickGear-')): + Logger.log('Failed download was not added by SickGear, exiting') + script_exit(POSTPROCESS_NONE, ExitReason.NONE_SG) + + return failure + + +# Check if the script is executed from settings page with a custom command +command = os.environ.get('NZBCP_COMMAND') +if None is not command: + if 'test connection' == command: + Logger.log('Test connection...') + result = call_sickgear('', '', test=True) + if True is result: + Logger.log('Connection Test successful!') + sys.exit(POSTPROCESS_SUCCESS) + Logger.log('Connection Test failed!', Logger.ERROR) + sys.exit(POSTPROCESS_ERROR) + + Logger.log('Invalid command passed to SickGear-NG: ' + command, Logger.ERROR) + sys.exit(POSTPROCESS_ERROR) + + +# Script body +def main(): + + global failed + # Do start up check + start_check() + + # Read context (what nzb is currently being processed) + directory = nzbget_var('DIRECTORY') + nzbname = nzbget_var('NZBNAME') + failed = check_for_failure(directory) + + if call_sickgear(nzbname, directory): + Logger.log('Successfully post-processed %s' % nzbname) + sys.stdout.flush() + script_exit(POSTPROCESS_SUCCESS, + failed and (markbad and ExitReason.MARKED_BAD_SUCCESS or ExitReason.FAIL_SUCCESS) or + ExitReason.PP_SUCCESS) + + Logger.log('Failed to post-process %s' % nzbname, Logger.ERROR) + sys.stdout.flush() + script_exit(POSTPROCESS_ERROR, + failed and (markbad and ExitReason.MARKED_BAD_ERROR or ExitReason.FAIL_ERROR) or + ExitReason.PP_ERROR) + + +# Execute main script function +main() + +script_exit(POSTPROCESS_NONE, ExitReason.NONE) diff --git a/gui/slick/css/style.css b/gui/slick/css/style.css index c79f54e..d9043dd 100644 --- a/gui/slick/css/style.css +++ b/gui/slick/css/style.css @@ -653,22 +653,32 @@ inc_bottom.tmpl display:inline } +#history-table thead th .icon-glyph, .footer .icon-glyph{ opacity:0.4;filter:alpha(opacity=40); float:none; display:inline-block; - margin:0 0 -1px 2px; - height:12px; + margin:0 0 -2px 4px; + height:13px; width:14px } +#history-table thead th .icon-glyph:hover, +#history-table tfoot th .icon-glyph:hover, +.footer .icon-glyph:hover{ + opacity:0.6;filter:alpha(opacity=60) +} +#history-table thead th .icon-glyph:hover, .footer .icon-glyph:hover{ - opacity:0.6;filter:alpha(opacity=60); cursor:pointer } +#history-table thead th .icon-glyph.age, +#history-table thead th .icon-glyph.date:hover, .footer .icon-glyph.timeleft, .footer .icon-glyph.time:hover{ background-position:-49px -25px } +#history-table thead th .icon-glyph.date, +#history-table thead th .icon-glyph.age:hover, .footer .icon-glyph.time, .footer .icon-glyph.timeleft:hover{ background-position:-193px -121px @@ -2605,40 +2615,51 @@ h2.day.add-apace, h2.network.add-space{ /* ======================================================================= history.tmpl ========================================================================== */ +.strike-deleted{ + text-decoration:line-through +} + +.red-bg{ + background-color:#992828 +} -#historyTable td, -#historyTable td.provider span{ +.green-bg{ + background-color:#3f993f +} + +#history-table td, +#history-table td.provider span{ text-align:center } -#historyTable td.provider span{ +#history-table td.provider span{ padding:0 2px } -#historyTable td.provider > img{ +#history-table td.provider > img{ margin-right:3px } -#historyTable td.provider span.fail img{ +#history-table td.provider span.fail img{ opacity:0.5; filter:alpha(opacity=50) } -#historyTable td img, -#historyTable td span{ +#history-table td img, +#history-table td span{ vertical-align:middle } -#historyTable td span.article{ +#history-table td span.article{ vertical-align:initial } -#historyTable td img.help, -#historyTable td span.help{ +#history-table td img.help, +#history-table td span.help{ cursor:help } -#historyTable td.tvShow{ +#history-table td.tvShow{ text-align:left } @@ -3256,15 +3277,18 @@ input.get_less_eps{ #media-search .section{ padding-bottom:10px } -#media-search .btn{ +#media-search .btn, +#provider-failures .btn{ margin:0 6px 0 0; min-width:70px } #media-search .btn.shows-more, -#media-search .btn.shows-less{ +#media-search .btn.shows-less, +#provider-failures .btn.shows-more, +#provider-failures .btn.shows-less{ margin:6px 6px 6px 0; } -#media-search .btn.provider-retry{ +#provider-failures .btn.provider-retry{ margin:6px 0 6px 4px; } .tablesorter.provider-failures{width:auto;clear:both;margin-bottom:10px} @@ -3356,6 +3380,16 @@ input.get_less_eps{ Global ========================================================================== */ +.contrast-text, +a.contrast-text:focus, +a.contrast-text:active, +a.contrast-text:visited{ + color:#ddd +} +a.contrast-text:hover{ + color:#999 +} + span.path{ padding:3px; margin-left:3px diff --git a/gui/slick/images/providers/showrss.png b/gui/slick/images/providers/showrss.png new file mode 100644 index 0000000..0835754 Binary files /dev/null and b/gui/slick/images/providers/showrss.png differ diff --git a/gui/slick/interfaces/default/apiBuilder.tmpl b/gui/slick/interfaces/default/apiBuilder.tmpl index 44fb123..0f3232c 100644 --- a/gui/slick/interfaces/default/apiBuilder.tmpl +++ b/gui/slick/interfaces/default/apiBuilder.tmpl @@ -3,7 +3,9 @@ API Builder - - +
@@ -372,9 +596,10 @@ addOption("show.pause-opt", "Pause", "&pause=1"); +
- +
diff --git a/gui/slick/interfaces/default/config_general.tmpl b/gui/slick/interfaces/default/config_general.tmpl index 9425f48..39c92d1 100644 --- a/gui/slick/interfaces/default/config_general.tmpl +++ b/gui/slick/interfaces/default/config_general.tmpl @@ -364,12 +364,12 @@ -
+
@@ -490,6 +490,7 @@
+ #set $selected = ' selected="selected" class="selected"' +
+ +
+
+ +
+ +
+
-
-
- -
- -
-
Click below to test Plex server(s)
- - -
 
-
+#set $selected = ' selected="selected" class="selected"' +
+ +
+
+ +
+
+ +
+ +
+
Click below to test Plex server(s)
+ + +
 
@@ -1693,12 +1756,12 @@ -
+
-
+
@@ -750,7 +750,7 @@ - [Toggle Key] + [Toggle Key]
@@ -953,7 +953,7 @@ - [Toggle Key] + [Toggle Key]
@@ -1264,4 +1264,4 @@ //--> -#include $os.path.join($sickbeard.PROG_DIR, 'gui/slick/interfaces/default/inc_bottom.tmpl') \ No newline at end of file +#include $os.path.join($sickbeard.PROG_DIR, 'gui/slick/interfaces/default/inc_bottom.tmpl') diff --git a/gui/slick/interfaces/default/config_search.tmpl b/gui/slick/interfaces/default/config_search.tmpl index 02da241..de14957 100755 --- a/gui/slick/interfaces/default/config_search.tmpl +++ b/gui/slick/interfaces/default/config_search.tmpl @@ -82,7 +82,6 @@

minutes between checking recent updated shows (minimum $sickbeard.MIN_RECENTSEARCH_FREQUENCY)

-

enter 4489 for experimental internal provider frequencies

@@ -98,16 +97,16 @@
-
-
+
-
+
- - - - - - - - #if $prov['has_limit'] - - #end if - - - - #set $day = [] - #for $fail in $prov['fails'] - #set $child = True - #if $fail['date'] not in $day - #set $day += [$fail['date']] - #set $child = False - #end if - #slurp# - - #if $fail['multirow'] - #if not $child - - #else - - #end if - #else - - #end if - #set $blank = '-' - #set $title=None - #if $fail['http']['count'] - #set $title=$fail['http']['code'] - #end if - - - - - #if $prov['has_limit'] - - #end if - - #end for - -
period of 1hrserver/timeoutnetworkno dataotherhit limit
$sbdatetime.sbdatetime.sbfdate($fail['date_time'])$sbdatetime.sbdatetime.sbftime($fail['date_time'], markup=True)$sbdatetime.sbdatetime.sbfdatetime($fail['date_time'], markup=True)#if $fail['http']['count']#$fail['http']['count']#else#$blank#end if# / #echo $fail['timeout'].get('count', 0) or $blank##echo ($fail['connection'].get('count', 0) + $fail['connection_timeout'].get('count', 0)) or $blank##echo $fail['nodata'].get('count', 0) or $blank##echo $fail['other'].get('count', 0) or $blank##echo $fail.get('limit', {}).get('count', 0) or $blank#
- - #end if - #end for -#end if - - - -

Search Queues:

diff --git a/gui/slick/interfaces/default/repo_index.tmpl b/gui/slick/interfaces/default/repo_index.tmpl new file mode 100644 index 0000000..2d517cc --- /dev/null +++ b/gui/slick/interfaces/default/repo_index.tmpl @@ -0,0 +1,19 @@ + + + + +

Index of $basepath

+ + + + +#for $file in $filelist + + + +#end for + +
+ Tornado Server for SickGear + + diff --git a/gui/slick/interfaces/default/repo_kodi_addon.tmpl b/gui/slick/interfaces/default/repo_kodi_addon.tmpl new file mode 100644 index 0000000..1ffde5e --- /dev/null +++ b/gui/slick/interfaces/default/repo_kodi_addon.tmpl @@ -0,0 +1,27 @@ +## +#from sickbeard import WEB_PORT, WEB_ROOT, ENABLE_HTTPS +#set sg_host = $getVar('sbHost', 'localhost') +#set sg_port = str($getVar('sbHttpPort', WEB_PORT)) +#set sg_root = $getVar('sbRoot', WEB_ROOT) +#set sg_use_https = $getVar('sbHttpsEnabled', ENABLE_HTTPS) +## +#set $base_url = 'http%s://%s:%s%s' % (('', 's')[any([sg_use_https])], $sg_host, $sg_port, $sg_root) +## + + + + $base_url/kodi/addons.xml + $base_url/kodi/addons.xml.md5 + $base_url/kodi + false + + + Install Add-ons for SickGear + Download and install add-ons from a repository at a running SickGear instance.[CR][CR]Contains:[CR]* Watchedstate updater service + + all + https://github.com/SickGear/SickGear + true + + diff --git a/gui/slick/interfaces/default/repo_kodi_addons.tmpl b/gui/slick/interfaces/default/repo_kodi_addons.tmpl new file mode 100644 index 0000000..e69fb08 --- /dev/null +++ b/gui/slick/interfaces/default/repo_kodi_addons.tmpl @@ -0,0 +1,5 @@ + + +$watchedstate_updater_addon_xml +$repo_xml + diff --git a/gui/slick/js/apibuilder.js b/gui/slick/js/apibuilder.js index 8f7afdc..527fb26 100644 --- a/gui/slick/js/apibuilder.js +++ b/gui/slick/js/apibuilder.js @@ -10,7 +10,7 @@ var _disable_empty_list=false; var _hide_empty_list=false; -function goListGroup(apikey, L7, L6, L5, L4, L3, L2, L1){ +function goListGroup(apikey, L8, L7, L6, L5, L4, L3, L2, L1){ var GlobalOptions = ""; $('.global').each(function(){ var checked = $(this).prop('checked'); @@ -26,7 +26,7 @@ function goListGroup(apikey, L7, L6, L5, L4, L3, L2, L1){ }); // handle the show.getposter / show.getbanner differently as they return an image and not json - if (L1 == "?cmd=show.getposter" || L1 == "?cmd=show.getbanner") { + if (L1 == "?cmd=sg.getnetworkicon" || L1 == "?cmd=sg.show.getposter" || L1 == "?cmd=sg.show.getbanner" || L1 == "?cmd=show.getposter" || L1 == "?cmd=show.getbanner" || L1 == "?cmd=sg.getindexericon") { var imgcache = sbRoot + "/api/" + apikey + "/" + L1 + L2 + GlobalOptions; var html = imgcache + '

'; $('#apiResponse').html(html); @@ -36,14 +36,24 @@ function goListGroup(apikey, L7, L6, L5, L4, L3, L2, L1){ cache: false, dataType: "html", success: function (img) { - $('#imgcache').attr('src', imgcache); + $('#imgcache').attr('src', imgcache + "&random=" + Math.random() * 100000000000000000000); } }) } + else if (L1 == "?cmd=listcommands") + { + var html = $.ajax({ + url: sbRoot + "/api/" + apikey + "/" + L1 + L2 + L3 + L4 + L5 + L6 + L7 + L8 + GlobalOptions, + async: false, + dataType: "html", + }).responseText; + + $('#apiResponse').html(html); + } else { - var html = sbRoot + "/api/" + apikey + "/" + L1 + L2 + L3 + L4 + L5 + L6 + L7 + GlobalOptions + "
";
+        var html = sbRoot + "/api/" + apikey + "/" + L1 + L2 + L3 + L4 + L5 + L6 + L7 + L8 + GlobalOptions + "
";
         html += $.ajax({
-          url: sbRoot + "/api/" + apikey + "/" + L1 + L2 + L3 + L4 + L5 + L6 + L7 + GlobalOptions,
+          url: sbRoot + "/api/" + apikey + "/" + L1 + L2 + L3 + L4 + L5 + L6 + L7 + L8 + GlobalOptions,
           async: false,
           dataType: "html",
         }).responseText;
@@ -167,7 +177,7 @@ function cs_addL(dis,link,label,css) { this.items[this.items.length]=new cs_link
 function cs_addG(label,css) { this.items[this.items.length]=new cs_groupOBJ(label,css); }
 function cs_endG() { this.items[this.items.length]=new cs_groupOBJ2(); }
 
-function cs_showMsg(msg) { window.status=msg; }
+function cs_showMsg(msg) { console.error(msg); window.status=msg; }
 function cs_badContent(n) { cs_goodContent=false; cs_showMsg("["+n+"] Not Found."); }
 
 function _setCookie(name, value) {
@@ -636,6 +646,6 @@ function selectOptions(n,opts,mode) {
         }
       }
     }
-  }  
+  }
 }
 // ------
diff --git a/gui/slick/js/config.js b/gui/slick/js/config.js
index 7db58f4..9a0134b 100644
--- a/gui/slick/js/config.js
+++ b/gui/slick/js/config.js
@@ -1,6 +1,18 @@
+function toggle$(el, cond){
+	var ifId = '-if-' + $(el).attr('id');
+	if(cond){
+		$('.hide' + ifId).fadeOut('fast', 'linear');
+		$('.show' + ifId).fadeIn('fast', 'linear');
+	} else {
+		$('.show' + ifId).fadeOut('fast', 'linear');
+		$('.hide' + ifId).fadeIn('fast', 'linear');
+	}
+}
+
 $(document).ready(function () {
 	var enabler = $('.enabler'),
-		viewIf = $('.viewIf');
+		viewIf = $('input.view-if'),
+		viewIfSel = $('select.view-if');
 
 	enabler.each(function () {
 		if (!$(this).prop('checked'))
@@ -16,18 +28,19 @@ $(document).ready(function () {
 	});
 
 	viewIf.each(function () {
-		$(($(this).prop('checked') ? '.hide_if_' : '.show_if_') + $(this).attr('id')).hide();
+		$(($(this).prop('checked') ? '.hide-if-' : '.show-if-') + $(this).attr('id')).hide();
 	});
 
 	viewIf.click(function () {
-		var if_id = '_if_' + $(this).attr('id');
-		if ($(this).prop('checked')) {
-			$('.hide' + if_id).fadeOut('fast', 'linear');
-			$('.show' + if_id).fadeIn('fast', 'linear');
-		} else {
-			$('.show' + if_id).fadeOut('fast', 'linear');
-			$('.hide' + if_id).fadeIn('fast', 'linear');
-		}
+		toggle$(this, $(this).prop('checked'));
+	});
+
+	viewIfSel.each(function () {
+		$((0 < $(this).find('option:selected').val() ? '.hide-if-' : '.show-if-') + $(this).attr('id')).hide();
+	});
+
+	viewIfSel.change(function(){
+		toggle$(this, 0 < $(this).find('option:selected').val());
 	});
 
 	var idSelect = '#imdb-accounts', idDel = '#imdb-list-del', idInput = '#imdb-url', idOnOff = '#imdb-list-onoff',
diff --git a/gui/slick/js/confirmations.js b/gui/slick/js/confirmations.js
index 6ce7a10..7574459 100644
--- a/gui/slick/js/confirmations.js
+++ b/gui/slick/js/confirmations.js
@@ -68,12 +68,12 @@ $(document).ready(function () {
 		var showname = document.getElementById('showtitle').getAttribute('data-showname');
 		$.confirm({
 			'title'		: 'Remove Show',
-			'message'	: 'Are you sure you want to remove ' + showname + ' from the database ?

Check to delete files as well. IRREVERSIBLE', + 'message' : 'Are you sure you want to remove ' + showname + ' from the database ?

Check to delete files as well. IRREVERSIBLE', 'buttons' : { 'Yes' : { 'class' : 'green', 'action': function(){ - location.href = target + (document.getElementById('deleteFiles').checked ? '&full=1' : ''); + location.href = target + (document.getElementById('delete-files').checked ? '&full=1' : ''); // If checkbox is ticked, remove show and delete files. Else just remove show. } }, @@ -85,6 +85,98 @@ $(document).ready(function () { }); }); + $('#del-watched').bind('click', function(e) { + e.preventDefault(); + + var dedupe = [], delArr = [], mFiles = 0; + $('.del-check').each(function() { + if (!0 === this.checked) { + var pathFile = $(this).closest('tr').attr('data-file'), + thisId = $(this).attr('id'); + + if (-1 === jQuery.inArray(pathFile, dedupe)) { + dedupe.push(pathFile); + mFiles += 1 - $(this).closest('tr').find('.tvShow .strike-deleted').length; + } + + delArr.push(thisId.replace('del-', '')); + + /** @namespace $.SickGear.history.isCompact */ + if ($.SickGear.history.isCompact) { + // then select all related episode checkboxes + var tvepId = $(this).closest('tr').attr('data-tvep-id'); + $('tr[data-tvep-id="' + tvepId + '"] input.del-check:not("#' + thisId + '")') + .each(function(){ + delArr.push($(this).attr('id').replace('del-', '')); + }); + } + } + }); + if (0 === delArr.length) + return !1; + + /** @namespace $.SickGear.history.isTrashit */ + /** @namespace $.SickGear.history.lastDeleteFiles */ + /** @namespace $.SickGear.history.lastDeleteRecords */ + var action = $.SickGear.history.isTrashit ? 'Trash' : 'Delete', + btns = { + 'Yes' : { + 'class' : 'green', + 'action': function(){ + var deleteFiles = !!$('#delete-files:checked').length, + deleteRecords = !!$('#delete-records:checked').length, + checked = ' checked="checked"'; + $.SickGear.history.lastDeleteFiles = deleteFiles ? checked : ''; + $.SickGear.history.lastDeleteRecords = deleteRecords ? checked : ''; + $.post($.SickGear.Root + '/history/watched', + { + tvew_id: delArr.join('|'), + files: (deleteFiles ? '1' : ''), + records: (deleteRecords ? '1' : '') + }, + function(data){ + var result = $.parseJSON(data); + result.success && window.location.reload(true); + /* using window.location as the following is + sluggish when deleting 20 of 100 records + */ + /* + result.success && $.each(result.success, function(){ + var tr = $('#del-' + this).closest('tr'); + var t = tr.closest('table'); + tr.addClass('delete-me').fadeToggle('fast', 'linear').promise().done( + function(){ + $('.delete-me').html(''); + t.trigger('update'); + $.SickGear.sumChecked(); + }); + });*/ + }); + } + } + }; + + // btn pre-created here in order to use a custom btn text as named key to object + btns['No' + (0 < mFiles ? ', abort ' + ($.SickGear.history.isTrashit ? 'trash' : 'permanent delete') : '')] = {'class' : 'red'}; + $.confirm({ + 'title' : (action + (0 < mFiles ? ' media' : ' records') + + '("Send to trash" options)'), + 'message' : (0 < mFiles + ? '' + + '' + action + ' ' + mFiles + '' + + ' media file' + (1===mFiles?'':'s') + ' from disk' + : '' + ) + + '' + + '' + + 'Remove ' + + delArr.length + ' history record' + (1===delArr.length?'':'s') + + '' + + 'Are you sure ?', + 'buttons' : btns + }); + }); + $('a.clearhistory').bind('click',function(e) { e.preventDefault(); var target = $( this ).attr('href'); @@ -105,7 +197,7 @@ $(document).ready(function () { } }); }); - + $('a.trimhistory').bind('click',function(e) { e.preventDefault(); var target = $( this ).attr('href'); @@ -126,5 +218,5 @@ $(document).ready(function () { } }); }); - -}); \ No newline at end of file + +}); diff --git a/gui/slick/js/history.js b/gui/slick/js/history.js new file mode 100644 index 0000000..1ae8ae9 --- /dev/null +++ b/gui/slick/js/history.js @@ -0,0 +1,236 @@ +/** @namespace $.SickGear.Root */ +/** @namespace $.SickGear.history.isCompact */ +/** @namespace $.SickGear.history.isTrashit */ +/** @namespace $.SickGear.history.useSubtitles */ +/** @namespace $.SickGear.history.layoutName */ +/* + 2017 Jason Mulligan + @version 3.5.11 +*/ +!function(i){function e(i){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[],d=0,r=void 0,a=void 0,s=void 0,f=void 0,u=void 0,l=void 0,v=void 0,B=void 0,c=void 0,p=void 0,y=void 0,m=void 0,x=void 0,g=void 0;if(isNaN(i))throw new Error("Invalid arguments");return s=!0===e.bits,y=!0===e.unix,a=e.base||2,p=void 0!==e.round?e.round:y?1:2,m=void 0!==e.spacer?e.spacer:y?"":" ",g=e.symbols||e.suffixes||{},x=2===a?e.standard||"jedec":"jedec",c=e.output||"string",u=!0===e.fullform,l=e.fullforms instanceof Array?e.fullforms:[],r=void 0!==e.exponent?e.exponent:-1,B=Number(i),v=B<0,f=a>2?1e3:1024,v&&(B=-B),(-1===r||isNaN(r))&&(r=Math.floor(Math.log(B)/Math.log(f)))<0&&(r=0),r>8&&(r=8),0===B?(n[0]=0,n[1]=y?"":t[x][s?"bits":"bytes"][r]):(d=B/(2===a?Math.pow(2,10*r):Math.pow(1e3,r)),s&&(d*=8)>=f&&r<8&&(d/=f,r++),n[0]=Number(d.toFixed(r>0?p:0)),n[1]=10===a&&1===r?s?"kb":"kB":t[x][s?"bits":"bytes"][r],y&&(n[1]="jedec"===x?n[1].charAt(0):r>0?n[1].replace(/B$/,""):n[1],o.test(n[1])&&(n[0]=Math.floor(n[0]),n[1]=""))),v&&(n[0]=-n[0]),n[1]=g[n[1]]||n[1],"array"===c?n:"exponent"===c?r:"object"===c?{value:n[0],suffix:n[1],symbol:n[1]}:(u&&(n[1]=l[r]?l[r]:b[x][r]+(s?"bit":"byte")+(1===n[0]?"":"s")),n.join(m))}var o=/^(b|B)$/,t={iec:{bits:["b","Kib","Mib","Gib","Tib","Pib","Eib","Zib","Yib"],bytes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},jedec:{bits:["b","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"],bytes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]}},b={iec:["","kibi","mebi","gibi","tebi","pebi","exbi","zebi","yobi"],jedec:["","kilo","mega","giga","tera","peta","exa","zetta","yotta"]};e.partial=function(i){return function(o){return e(o,i)}},"undefined"!=typeof exports?module.exports=e:"function"==typeof define&&define.amd?define(function(){return e}):i.filesize=e}("undefined"!=typeof window?window:global); + +function rowCount(){ + var output$ = $('#row-count'); + if(!output$.length) + return; + + var tbody$ = $('#tbody'), + nRows = tbody$.find('tr').length, + compacted = tbody$.find('tr.hide').length, + compactedFiltered = tbody$.find('tr.filtered.hide').length, + filtered = tbody$.find('tr.filtered').length; + output$.text((filtered + ? nRows - (filtered + compacted - compactedFiltered) + ' / ' + nRows + ' filtered' + : nRows) + (1 === nRows ? ' row' : ' rows')); +} + +$(document).ready(function() { + + var extraction = {0: function(node) { + var dataSort = $(node).find('div[data-sort]').attr('data-sort') + || $(node).find('span[data-sort]').attr('data-sort'); + return !dataSort ? dataSort : dataSort.toLowerCase();}}, + tbody$ = $('#tbody'), + headers = {}, + layoutName = '' + $.SickGear.history.layoutName; + + if ('detailed' === layoutName) { + + jQuery.extend(extraction, { + 4: function (node) { + return $(node).find('span').text().toLowerCase(); + } + }); + + jQuery.extend(headers, {4: {sorter: 'quality'}}); + + } else if ('compact' === layoutName) { + + jQuery.extend(extraction, { + 1: function (node) { + return $(node).find('span[data-sort]').attr('data-sort').toLowerCase(); + }, + 2: function (node) { + return $(node).attr('provider').toLowerCase(); + }, + 5: function (node) { + return $(node).attr('quality').toLowerCase(); + } + }); + + var disable = {sorter: !1}, qualSort = {sorter: 'quality'}; + jQuery.extend(headers, $.SickGear.history.useSubtitles ? {4: disable, 5: qualSort} : {3: disable, 4: qualSort}); + + } else if (-1 !== layoutName.indexOf('watched')) { + + jQuery.extend(extraction, { + 3: function(node) { + return $(node).find('span[data-sort]').attr('data-sort'); + }, + 5: function(node) { + return $(node).find('span[data-sort]').attr('data-sort'); + }, + 6: function (node) { + return $(node).find('input:checked').length; + } + }); + + jQuery.extend(headers, {4: {sorter: 'quality'}}); + + rowCount(); + } else if (-1 !== layoutName.indexOf('compact_stats')) { + jQuery.extend(extraction, { + 3: function (node) { + return $(node).find('div[data-sort]').attr('data-sort'); + } + }); + + } + + var isWatched = -1 !== $('select[name="HistoryLayout"]').val().indexOf('watched'), + options = { + widgets: ['zebra', 'filter'], + widgetOptions : { + filter_hideEmpty: !0, filter_matchType : {'input': 'match', 'select': 'match'}, + filter_resetOnEsc: !0, filter_saveFilters: !0, filter_searchDelay: 300 + }, + sortList: isWatched ? [[1, 1], [0, 1]] : [0, 1], + textExtraction: extraction, + headers: headers}, + stateLayoutDate = function(table$, glyph$){table$.toggleClass('event-age');glyph$.toggleClass('age date');}; + + if(isWatched){ + jQuery.extend(options, { + selectorSort: '.tablesorter-header-inside', + headerTemplate: '
{content}{icon}
', + onRenderTemplate: function(index, template){ + if(0 === index){ + template = '' + + template; + } + return template; + }, + onRenderHeader: function(){ + var table$ = $('#history-table'), glyph$ = $('#watched-date'); + if($.tablesorter.storage(table$, 'isLayoutAge')){ + stateLayoutDate(table$, glyph$); + } + $(this).find('#watched-date').on('click', function(){ + stateLayoutDate(table$, glyph$); + $.tablesorter.storage(table$, 'isLayoutAge', table$.hasClass('event-age')); + return !1; + }); + } + }); + } + + $('#history-table').tablesorter(options).bind('filterEnd', function(){ + rowCount(); + }); + + $('#limit').change(function(){ + window.location.href = $.SickGear.Root + '/history/?limit=' + $(this).val() + }); + + $('#show-watched-help').click(function () { + $('#watched-help').fadeToggle('fast', 'linear'); + $.get($.SickGear.Root + '/history/toggle_help'); + }); + + var addQTip = (function(){ + $(this).css('cursor', 'help'); + $(this).qtip({ + show: {solo:true}, + position: {viewport:$(window), my:'left center', adjust:{y: -10, x: 2}}, + style: {tip: {corner:true, method:'polygon'}, classes:'qtip-dark qtip-rounded qtip-shadow'} + }); + }); + $('.add-qtip').each(addQTip); + + $.SickGear.sumChecked = (function(){ + var dedupe = [], sum = 0, output; + + $('.del-check:checked').each(function(){ + if ($(this).closest('tr').find('.tvShow .strike-deleted').length) + return; + var pathFile = $(this).closest('tr').attr('data-file'); + if (-1 === jQuery.inArray(pathFile, dedupe)) { + dedupe.push(pathFile); + output = $(this).closest('td').prev('td.size').find('span[data-sort]').attr('data-sort'); + sum = sum + parseInt(output, 10); + } + }); + $('#del-watched').attr('disabled', !dedupe.length && !$('#tbody').find('tr').find('.tvShow .strike-deleted').length); + + output = filesize(sum, {symbols: {B: 'Bytes'}}); + $('#sum-size').text(/\s(MB)$/.test(output) ? filesize(sum, {round:1}) + : /^1\sB/.test(output) ? output.replace('Bytes', 'Byte') : output); + }); + $.SickGear.sumChecked(); + + var className='.del-check', lastCheck = null, check, found; + tbody$.on('click', className, function(ev){ + if(!lastCheck || !ev.shiftKey){ + lastCheck = this; + } else { + check = this; found = 0; + $('#tbody').find('> tr:visible').find(className).each(function(){ + if (2 === found) + return !1; + if (1 === found) + this.checked = lastCheck.checked; + found += (1 && (this === check || this === lastCheck)); + }); + } + $(this).closest('table').trigger('update'); + $.SickGear.sumChecked(); + }); + + $('.shows-less').click(function(){ + var table$ = $(this).nextAll('table:first'); + table$ = table$.length ? table$ : $(this).parent().nextAll('table:first'); + table$.hide(); + $(this).hide(); + $(this).prevAll('input:first').show(); + }); + $('.shows-more').click(function(){ + var table$ = $(this).nextAll('table:first'); + table$ = table$.length ? table$ : $(this).parent().nextAll('table:first'); + table$.show(); + $(this).hide(); + $(this).nextAll('input:first').show(); + }); + + $('.provider-retry').click(function () { + $(this).addClass('disabled'); + var match = $(this).attr('id').match(/^(.+)-btn-retry$/); + $.ajax({ + url: $.SickGear.Root + '/manage/manageSearches/retryProvider?provider=' + match[1], + type: 'GET', + complete: function () { + window.location.reload(true); + } + }); + }); + + $('.provider-failures').tablesorter({widgets : ['zebra'], + headers : { 0:{sorter:!1}, 1:{sorter:!1}, 2:{sorter:!1}, 3:{sorter:!1}, 4:{sorter:!1}, 5:{sorter:!1} } + }); + + $('.provider-fail-parent-toggle').click(function(){ + $(this).closest('tr').nextUntil('tr:not(.tablesorter-childRow)').find('td').toggle(); + return !1; + }); + + // Make table cell focusable + // http://css-tricks.com/simple-css-row-column-highlighting/ + var focus$ = $('.focus-highlight'); + if (focus$.length){ + focus$.find('td, th') + .attr('tabindex', '1') + // add touch device support + .on('touchstart', function(){ + $(this).focus(); + }); + } +}); diff --git a/gui/slick/js/manageSearches.js b/gui/slick/js/manageSearches.js index e0ae9f7..1d563c8 100644 --- a/gui/slick/js/manageSearches.js +++ b/gui/slick/js/manageSearches.js @@ -34,37 +34,4 @@ $(function(){ $(this).hide(); $(this).nextAll('input:first').show(); }); - $('.provider-retry').click(function () { - $(this).addClass('disabled'); - var match = $(this).attr('id').match(/^(.+)-btn-retry$/); - $.ajax({ - url: sbRoot + '/manage/manageSearches/retryProvider?provider=' + match[1], - type: 'GET', - complete: function () { - window.location.reload(true); - } - }); - }); - - $('.provider-failures').tablesorter({widgets : ['zebra'], - headers : { 0:{sorter:!1}, 1:{sorter:!1}, 2:{sorter:!1}, 3:{sorter:!1}, 4:{sorter:!1}, 5:{sorter:!1} } - }); - - $('.provider-fail-parent-toggle').click(function(){ - $(this).closest('tr').nextUntil('tr:not(.tablesorter-childRow)').find('td').toggle(); - return !1; - }); - - // Make table cell focusable - // http://css-tricks.com/simple-css-row-column-highlighting/ - var focus$ = $('.focus-highlight'); - if (focus$.length){ - focus$.find('td, th') - .attr('tabindex', '1') - // add touch device support - .on('touchstart', function(){ - $(this).focus(); - }); - } - }); diff --git a/gui/slick/js/plot.ly/numeric/1.2.6/numeric.min.js b/gui/slick/js/plot.ly/numeric/1.2.6/numeric.min.js new file mode 100644 index 0000000..b61b2d3 --- /dev/null +++ b/gui/slick/js/plot.ly/numeric/1.2.6/numeric.min.js @@ -0,0 +1,3 @@ +"use strict";var numeric=typeof exports=="undefined"?function(){}:exports;typeof global!="undefined"&&(global.numeric=numeric),numeric.version="1.2.6",numeric.bench=function(t,n){var r,i,s,o;typeof n=="undefined"&&(n=15),s=.5,r=new Date;for(;;){s*=2;for(o=s;o>3;o-=4)t(),t(),t(),t();while(o>0)t(),o--;i=new Date;if(i-r>n)break}for(o=s;o>3;o-=4)t(),t(),t(),t();while(o>0)t(),o--;return i=new Date,1e3*(3*s-1)/(i-r)},numeric._myIndexOf=function(t){var n=this.length,r;for(r=0;rnumeric.largeArray)return r.push("...Large Array..."),!0;var f=!1;r.push("[");for(t=0;t0&&(r.push(","),f&&r.push("\n ")),f=i(e[t]);return r.push("]"),!0}r.push("{");var f=!1;for(t in e)e.hasOwnProperty(t)&&(f&&r.push(",\n"),f=!0,r.push(t),r.push(": \n"),i(e[t]));return r.push("}"),!0}var r=[];return i(t),r.join("")},numeric.parseDate=function(t){function n(e){if(typeof e=="string")return Date.parse(e.replace(/-/g,"/"));if(e instanceof Array){var t=[],r;for(r=0;r0){s[f]=[];for(r=0;r>2,u=((r&3)<<4)+(i>>4),a=((i&15)<<2)+(s>>6),f=s&63,n+1>=t?a=f=64:n+2>=t&&(f=64),c+=l.charAt(o)+l.charAt(u)+l.charAt(a)+l.charAt(f);return c}function r(e,t,n){typeof t=="undefined"&&(t=0),typeof n=="undefined"&&(n=e.length);var r=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],i=-1,s=0,o=e.length,u;for(u=t;u>>8^r[s];return i^-1}var i=t[0].length,s=t[0][0].length,o,u,a,f,l,c,h,p,d,v,m,g=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,s>>24&255,s>>16&255,s>>8&255,s&255,i>>24&255,i>>16&255,i>>8&255,i&255,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];m=r(g,12,29),g[29]=m>>24&255,g[30]=m>>16&255,g[31]=m>>8&255,g[32]=m&255,o=1,u=0;for(p=0;p>8&255,g.push(c),g.push(h),g.push(~c&255),g.push(~h&255),p===0&&g.push(0);for(d=0;d255?c=255:c<0?c=0:c=Math.round(c),o=(o+c)%65521,u=(u+o)%65521,g.push(c);g.push(0)}return v=(u<<16)+o,g.push(v>>24&255),g.push(v>>16&255),g.push(v>>8&255),g.push(v&255),l=g.length-41,g[33]=l>>24&255,g[34]=l>>16&255,g[35]=l>>8&255,g[36]=l&255,m=r(g,37),g.push(m>>24&255),g.push(m>>16&255),g.push(m>>8&255),g.push(m&255),g.push(0),g.push(0),g.push(0),g.push(0),g.push(73),g.push(69),g.push(78),g.push(68),g.push(174),g.push(66),g.push(96),g.push(130),"data:image/png;base64,"+n(g)},numeric._dim=function(t){var n=[];while(typeof t=="object")n.push(t.length),t=t[0];return n},numeric.dim=function(t){var n,r;if(typeof t=="object")return n=t[0],typeof n=="object"?(r=n[0],typeof r=="object"?numeric._dim(t):[t.length,n.length]):[t.length];return[]},numeric.mapreduce=function(t,n){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+n+";\n"+'if(typeof x === "number") { var xi = x; '+t+"; return accum; }\n"+'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+'if(typeof _k === "undefined") _k = 0;\n'+"var _n = _s[_k];\n"+"var i,xi;\n"+"if(_k < _s.length-1) {\n"+" for(i=_n-1;i>=0;i--) {\n"+" accum = arguments.callee(x[i],accum,_s,_k+1);\n"+" }"+" return accum;\n"+"}\n"+"for(i=_n-1;i>=1;i-=2) { \n"+" xi = x[i];\n"+" "+t+";\n"+" xi = x[i-1];\n"+" "+t+";\n"+"}\n"+"if(i === 0) {\n"+" xi = x[i];\n"+" "+t+"\n"+"}\n"+"return accum;")},numeric.mapreduce2=function(t,n){return Function("x","var n = x.length;\nvar i,xi;\n"+n+";\n"+"for(i=n-1;i!==-1;--i) { \n"+" xi = x[i];\n"+" "+t+";\n"+"}\n"+"return accum;")},numeric.same=function same(e,t){var n,r;if(e instanceof Array&&t instanceof Array){r=e.length;if(r!==t.length)return!1;for(n=0;n=0;o-=2)s[o+1]=n,s[o]=n;return o===-1&&(s[0]=n),s}for(o=i-1;o>=0;o--)s[o]=numeric.rep(t,n,r+1);return s},numeric.dotMMsmall=function(t,n){var r,i,s,o,u,a,f,l,c,h,p,d,v,m;o=t.length,u=n.length,a=n[0].length,f=Array(o);for(r=o-1;r>=0;r--){l=Array(a),c=t[r];for(s=a-1;s>=0;s--){h=c[u-1]*n[u-1][s];for(i=u-2;i>=1;i-=2)p=i-1,h+=c[i]*n[i][s]+c[p]*n[p][s];i===0&&(h+=c[0]*n[0][s]),l[s]=h}f[r]=l}return f},numeric._getCol=function(t,n,r){var i=t.length,s;for(s=i-1;s>0;--s)r[s]=t[s][n],--s,r[s]=t[s][n];s===0&&(r[0]=t[0][n])},numeric.dotMMbig=function(t,n){var r=numeric._getCol,i=n.length,s=Array(i),o=t.length,u=n[0].length,a=new Array(o),f,l=numeric.dotVV,c,h,p,d;--i,--o;for(c=o;c!==-1;--c)a[c]=Array(u);--u;for(c=u;c!==-1;--c){r(n,c,s);for(h=o;h!==-1;--h)d=0,f=t[h],a[h][c]=l(f,s)}return a},numeric.dotMV=function(t,n){var r=t.length,i=n.length,s,o=Array(r),u=numeric.dotVV;for(s=r-1;s>=0;s--)o[s]=u(t[s],n);return o},numeric.dotVM=function(t,n){var r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E;o=t.length,u=n[0].length,f=Array(u);for(s=u-1;s>=0;s--){h=t[o-1]*n[o-1][s];for(i=o-2;i>=1;i-=2)p=i-1,h+=t[i]*n[i][s]+t[p]*n[p][s];i===0&&(h+=t[0]*n[0][s]),f[s]=h}return f},numeric.dotVV=function(t,n){var r,i=t.length,s,o=t[i-1]*n[i-1];for(r=i-2;r>=1;r-=2)s=r-1,o+=t[r]*n[r]+t[s]*n[s];return r===0&&(o+=t[0]*n[0]),o},numeric.dot=function(t,n){var r=numeric.dim;switch(r(t).length*1e3+r(n).length){case 2002:return n.length<10?numeric.dotMMsmall(t,n):numeric.dotMMbig(t,n);case 2001:return numeric.dotMV(t,n);case 1002:return numeric.dotVM(t,n);case 1001:return numeric.dotVV(t,n);case 1e3:return numeric.mulVS(t,n);case 1:return numeric.mulSV(t,n);case 0:return t*n;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(t){var n,r,i,s=t.length,o=Array(s),u;for(n=s-1;n>=0;n--){u=Array(s),r=n+2;for(i=s-1;i>=r;i-=2)u[i]=0,u[i-1]=0;i>n&&(u[i]=0),u[n]=t[n];for(i=n-1;i>=1;i-=2)u[i]=0,u[i-1]=0;i===0&&(u[0]=0),o[n]=u}return o},numeric.getDiag=function(e){var t=Math.min(e.length,e[0].length),n,r=Array(t);for(n=t-1;n>=1;--n)r[n]=e[n][n],--n,r[n]=e[n][n];return n===0&&(r[0]=e[0][0]),r},numeric.identity=function(t){return numeric.diag(numeric.rep([t],1))},numeric.pointwise=function(t,n,r){typeof r=="undefined"&&(r="");var i=[],s,o=/\[i\]$/,u,a="",f=!1;for(s=0;s=0;i--) ret[i] = arguments.callee("+t.join(",")+",_s,_k+1);\n"+" return ret;\n"+"}\n"+r+"\n"+"for(i=_n-1;i!==-1;--i) {\n"+" "+n+"\n"+"}\n"+"return ret;",Function.apply(null,i)},numeric.pointwise2=function(t,n,r){typeof r=="undefined"&&(r="");var i=[],s,o=/\[i\]$/,u,a="",f=!1;for(s=0;s=0;s--)_biforeach(typeof e=="object"?e[s]:e,typeof t=="object"?t[s]:t,n,r+1,i)},numeric._biforeach2=function _biforeach2(e,t,n,r,i){if(r===n.length-1)return i(e,t);var s,o=n[r],u=Array(o);for(s=o-1;s>=0;--s)u[s]=_biforeach2(typeof e=="object"?e[s]:e,typeof t=="object"?t[s]:t,n,r+1,i);return u},numeric._foreach=function _foreach(e,t,n,r){if(n===t.length-1){r(e);return}var i,s=t[n];for(i=s-1;i>=0;i--)_foreach(e[i],t,n+1,r)},numeric._foreach2=function _foreach2(e,t,n,r){if(n===t.length-1)return r(e);var i,s=t[n],o=Array(s);for(i=s-1;i>=0;i--)o[i]=_foreach2(e[i],t,n+1,r);return o},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;em&&(v=h,m=d);a=o[v],o[v]=o[p],o[p]=a,c=f[v],f[v]=f[p],f[p]=c,t=a[p];for(d=p;d!==s;++d)a[d]/=t;for(d=s-1;d!==-1;--d)c[d]/=t;for(h=i-1;h!==-1;--h)if(h!==p){u=o[h],l=f[h],t=u[p];for(d=p+1;d!==s;++d)u[d]-=a[d]*t;for(d=s-1;d>0;--d)l[d]-=c[d]*t,--d,l[d]-=c[d]*t;d===0&&(l[0]-=c[0]*t)}}return f},numeric.det=function(t){var n=numeric.dim(t);if(n.length!==2||n[0]!==n[1])throw new Error("numeric: det() only works on square matrices");var r=n[0],i=1,s,o,u,a=numeric.clone(t),f,l,c,h,p,d,v;for(o=0;oMath.abs(a[u][o])&&(u=s);u!==o&&(h=a[u],a[u]=a[o],a[o]=h,i*=-1),f=a[o];for(s=o+1;s=1;n-=2){a=t[n],u=t[n-1];for(r=s-1;r>=1;--r)f=o[r],f[n]=a[r],f[n-1]=u[r],--r,f=o[r],f[n]=a[r],f[n-1]=u[r];r===0&&(f=o[0],f[n]=a[0],f[n-1]=u[0])}if(n===0){u=t[0];for(r=s-1;r>=1;--r)o[r][0]=u[r],--r,o[r][0]=u[r];r===0&&(o[0][0]=u[0])}return o},numeric.negtranspose=function(t){var n,r,i=t.length,s=t[0].length,o=Array(s),u,a,f;for(r=0;r=1;n-=2){a=t[n],u=t[n-1];for(r=s-1;r>=1;--r)f=o[r],f[n]=-a[r],f[n-1]=-u[r],--r,f=o[r],f[n]=-a[r],f[n-1]=-u[r];r===0&&(f=o[0],f[n]=-a[0],f[n-1]=-u[0])}if(n===0){u=t[0];for(r=s-1;r>=1;--r)o[r][0]=-u[r],--r,o[r][0]=-u[r];r===0&&(o[0][0]=-u[0])}return o},numeric._random=function _random(e,t){var n,r=e[t],i=Array(r),s;if(t===e.length-1){s=Math.random;for(n=r-1;n>=1;n-=2)i[n]=s(),i[n-1]=s();return n===0&&(i[0]=s()),i}for(n=r-1;n>=0;n--)i[n]=_random(e,t+1);return i},numeric.random=function(t){return numeric._random(t,0)},numeric.norm2=function(t){return Math.sqrt(numeric.norm2Squared(t))},numeric.linspace=function(t,n,r){typeof r=="undefined"&&(r=Math.max(Math.round(n-t)+1,1));if(r<2)return r===1?[t]:[];var i,s=Array(r);r--;for(i=r;i>=0;i--)s[i]=(i*n+(r-i)*t)/r;return s},numeric.getBlock=function(t,n,r){function s(e,t){var o,u=n[t],a=r[t]-u,f=Array(a);if(t===i.length-1){for(o=a;o>=0;o--)f[o]=e[o+u];return f}for(o=a;o>=0;o--)f[o]=s(e[o+u],t+1);return f}var i=numeric.dim(t);return s(t,0)},numeric.setBlock=function(t,n,r,i){function o(e,t,i){var u,a=n[i],f=r[i]-a;if(i===s.length-1)for(u=f;u>=0;u--)e[u+a]=t[u];for(u=f;u>=0;u--)o(e[u+a],t[u],i+1)}var s=numeric.dim(t);return o(t,i,0),t},numeric.getRange=function(t,n,r){var i=n.length,s=r.length,o,u,a=Array(i),f,l;for(o=i-1;o!==-1;--o){a[o]=Array(s),f=a[o],l=t[n[o]];for(u=s-1;u!==-1;--u)f[u]=l[r[u]]}return a},numeric.blockMatrix=function(t){var n=numeric.dim(t);if(n.length<4)return numeric.blockMatrix([t]);var r=n[0],i=n[1],s,o,u,a,f;s=0,o=0;for(u=0;u=0;f--){a=Array(o),c=t[f];for(l=o-1;l>=3;--l)a[l]=c*n[l],--l,a[l]=c*n[l],--l,a[l]=c*n[l],--l,a[l]=c*n[l];while(l>=0)a[l]=c*n[l],--l;u[f]=a}return u},numeric.T=function(t,n){this.x=t,this.y=n},numeric.t=function(t,n){return new numeric.T(t,n)},numeric.Tbinop=function(t,n,r,i,s){var o=numeric.indexOf;if(typeof s!="string"){var u;s="";for(u in numeric)numeric.hasOwnProperty(u)&&(t.indexOf(u)>=0||n.indexOf(u)>=0||r.indexOf(u)>=0||i.indexOf(u)>=0)&&u.length>1&&(s+="var "+u+" = numeric."+u+";\n")}return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+s+"\n"+"if(x.y) {"+" if(y.y) {"+" return new numeric.T("+i+");\n"+" }\n"+" return new numeric.T("+r+");\n"+"}\n"+"if(y.y) {\n"+" return new numeric.T("+n+");\n"+"}\n"+"return new numeric.T("+t+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var t=numeric.mul,n=numeric.div;if(this.y){var r=numeric.add(t(this.x,this.x),t(this.y,this.y));return new numeric.T(n(this.x,r),n(numeric.neg(this.y),r))}return new T(n(1,this.x))},numeric.T.prototype.div=function div(e){e instanceof numeric.T||(e=new numeric.T(e));if(e.y)return this.mul(e.reciprocal());var div=numeric.div;return this.y?new numeric.T(div(this.x,e.x),div(this.y,e.x)):new numeric.T(div(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var t=numeric.transpose,n=this.x,r=this.y;return r?new numeric.T(t(n),t(r)):new numeric.T(t(n))},numeric.T.prototype.transjugate=function(){var t=numeric.transpose,n=this.x,r=this.y;return r?new numeric.T(t(n),numeric.negtranspose(r)):new numeric.T(t(n))},numeric.Tunop=function(t,n,r){return typeof r!="string"&&(r=""),Function("var x = this;\n"+r+"\n"+"if(x.y) {"+" "+n+";\n"+"}\n"+t+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var t=this;if(typeof t.y=="undefined")return new numeric.T(numeric.inv(t.x));var n=t.x.length,r,i,s,o=numeric.identity(n),u=numeric.rep([n,n],0),a=numeric.clone(t.x),f=numeric.clone(t.y),l,c,h,p,d,v,m,g,r,i,s,y,b,w,E,S,x,T;for(r=0;ry&&(s=i,y=b);s!==r&&(T=a[r],a[r]=a[s],a[s]=T,T=f[r],f[r]=f[s],f[s]=T,T=o[r],o[r]=o[s],o[s]=T,T=u[r],u[r]=u[s],u[s]=T),l=a[r],c=f[r],d=o[r],v=u[r],w=l[r],E=c[r];for(i=r+1;i0;r--){d=o[r],v=u[r];for(i=r-1;i>=0;i--){m=o[i],g=u[i],w=a[i][r],E=f[i][r];for(s=n-1;s>=0;s--)S=d[s],x=v[s],m[s]-=w*S-E*x,g[s]-=w*x+E*S}}return new numeric.T(o,u)},numeric.T.prototype.get=function(t){var n=this.x,r=this.y,i=0,s,o=t.length;if(r){while(i=0?1:-1,i=r*numeric.norm2(t);n[0]+=i;var s=numeric.norm2(n);if(s===0)throw new Error("eig: internal error");return numeric.div(n,s)},numeric.toUpperHessenberg=function(t){var n=numeric.dim(t);if(n.length!==2||n[0]!==n[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var r=n[0],i,s,o,u,a,f=numeric.clone(t),l,c,h,p,d=numeric.identity(r),v;for(s=0;s0){a=numeric.house(u),l=numeric.getBlock(f,[s+1,s],[r-1,r-1]),c=numeric.tensor(a,numeric.dot(a,l));for(i=s+1;i=4*c){var k,L;k=.5*(h+Math.sqrt(h*h-4*c)),L=.5*(h-Math.sqrt(h*h-4*c)),p=numeric.add(numeric.sub(numeric.dot(p,p),numeric.mul(p,k+L)),numeric.diag(numeric.rep([3],k*L)))}else p=numeric.add(numeric.sub(numeric.dot(p,p),numeric.mul(p,h)),numeric.diag(numeric.rep([3],c)));s=[p[0][0],p[1][0],p[2][0]],o=numeric.house(s),g=[e[0],e[1],e[2]],y=numeric.tensor(o,numeric.dot(o,g));for(w=0;w<3;w++){m=e[w],b=y[w];for(S=0;S=0?(w<0?x=-0.5*(w-A(S)):x=-0.5*(w+A(S)),k=(m-x)*(m-x)+g*g,L=y*y+(b-x)*(b-x),k>L?(k=A(k),N=(m-x)/k,C=g/k):(L=A(L),N=y/L,C=(b-x)/L),p=new s([[C,-N],[N,C]]),h.setRows(u,v,p.dot(h.getRows(u,v)))):(x=-0.5*w,T=.5*A(-S),k=(m-x)*(m-x)+g*g,L=y*y+(b-x)*(b-x),k>L?(k=A(k+T*T),N=(m-x)/k,C=g/k,x=0,T/=k):(L=A(L+T*T),N=y/L,C=(b-x)/L,x=T/L,T=0),p=new s([[C,-N],[N,C]],[[x, +T],[T,-x]]),h.setRows(u,v,p.dot(h.getRows(u,v))))}}var O=h.dot(t).dot(h.transjugate()),o=t.length,M=numeric.T.identity(o);for(v=0;v0)for(a=v-1;a>=0;a--){var _=O.get([a,a]),D=O.get([v,v]);if(!numeric.neq(_.x,D.x)&&!numeric.neq(_.y,D.y)){M.setRow(v,M.getRow(a));continue}x=O.getRow(a).getBlock([a],[v-1]),T=M.getRow(v).getBlock([a],[v-1]),M.set([v,a],O.get([a,v]).neg().sub(x.dot(T)).div(_.sub(D)))}for(v=0;v=u.length)u[u.length]=0;i[o]!==0&&u[o]++}}var r=u.length,a=Array(r+1);a[0]=0;for(s=0;s=d){s[f]=h[u];if(u===0)return;++f,--u,p=l[u],d=c[u]}else a=o[r[p]],i[a]===0?(i[a]=1,l[u]=p,++u,h[u]=a,p=n[a],c[u]=d=n[a+1]):++p},numeric.ccsLPSolve=function(t,n,r,i,s,o,u){var a=t[0],f=t[1],l=t[2],c=a.length-1,h=0,p=n[0],d=n[1],v=n[2],m,g,y,b,w,E,S,x,T,N,C,k;g=p[s],y=p[s+1],i.length=0;for(m=g;mb&&(w=m,b=E)}C(h[d])=v){s[l]=o[p[a]];if(a===0)return;++l,--a,d=c[a],v=h[a]}else f=r[d],i[f]===0?(i[f]=1,c[a]=d,++a,p[a]=f,f=o[f],d=n[f],h[a]=v=n[f+1]):++d}},numeric.ccsLPSolve0=function(t,n,r,i,s,o,u,a){var f=t[0],l=t[1],c=t[2],h=f.length-1,p=0,d=n[0],v=n[1],m=n[2],g,y,b,w,E,S,x,T,N,C,k,L;y=d[s],b=d[s+1],i.length=0;for(g=y;gb&&(w=m,b=E)}C(h[k[d]])t[n]&&(t[n]=e.length);var r;for(r in e)e.hasOwnProperty(r)&&dim(e[r],t,n+1);return t},numeric.sclone=function clone(e,t,n){typeof t=="undefined"&&(t=0),typeof n=="undefined"&&(n=numeric.sdim(e).length);var r,i=Array(e.length);if(t===n-1){for(r in e)e.hasOwnProperty(r)&&(i[r]=e[r]);return i}for(r in e)e.hasOwnProperty(r)&&(i[r]=clone(e[r],t+1,n));return i},numeric.sdiag=function(t){var n=t.length,r,i=Array(n),s,o,u;for(r=n-1;r>=1;r-=2)s=r-1,i[r]=[],i[r][r]=t[r],i[s]=[],i[s][s]=t[s];return r===0&&(i[0]=[],i[0][0]=t[r]),i},numeric.sidentity=function(t){return numeric.sdiag(numeric.rep([t],1))},numeric.stranspose=function(t){var n=[],r=t.length,i,s,o;for(i in t){if(!t.hasOwnProperty(i))continue;o=t[i];for(s in o){if(!o.hasOwnProperty(s))continue;typeof n[s]!="object"&&(n[s]=[]),n[s][i]=o[s]}}return n},numeric.sLUP=function(t,n){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(t,n){var r=t.length,i=n.length,s=numeric.stranspose(n),o=s.length,u,a,f,l,c,h,p=Array(r),d;for(f=r-1;f>=0;f--){d=[],u=t[f];for(c=o-1;c>=0;c--){h=0,a=s[c];for(l in u){if(!u.hasOwnProperty(l))continue;l in a&&(h+=u[l]*a[l])}h&&(d[c]=h)}p[f]=d}return p},numeric.sdotMV=function(t,n){var r=t.length,i,s,o,u=Array(r),a;for(s=r-1;s>=0;s--){i=t[s],a=0;for(o in i){if(!i.hasOwnProperty(o))continue;n[o]&&(a+=i[o]*n[o])}a&&(u[s]=a)}return u},numeric.sdotVM=function(t,n){var r,i,s,o,u=[],a;for(r in t){if(!t.hasOwnProperty(r))continue;s=n[r],o=t[r];for(i in s){if(!s.hasOwnProperty(i))continue;u[i]||(u[i]=0),u[i]+=o*s[i]}}return u},numeric.sdotVV=function(t,n){var r,i=0;for(r in t)t[r]&&n[r]&&(i+=t[r]*n[r]);return i},numeric.sdot=function(t,n){var r=numeric.sdim(t).length,i=numeric.sdim(n).length,s=r*1e3+i;switch(s){case 0:return t*n;case 1001:return numeric.sdotVV(t,n);case 2001:return numeric.sdotMV(t,n);case 1002:return numeric.sdotVM(t,n);case 2002:return numeric.sdotMM(t,n);default:throw new Error("numeric.sdot not implemented for tensors of order "+r+" and "+i)}},numeric.sscatter=function(t){var n=t[0].length,r,i,s,o=t.length,u=[],a;for(i=n-1;i>=0;--i){if(!t[o-1][i])continue;a=u;for(s=0;s=0;--i)t[i]=[];for(i=r;i>=0;--i)t[i].push(n[i]);t[r+1].push(s)}}else gather(s,t,n)}return n.length>r&&n.pop(),t},numeric.cLU=function(t){var n=t[0],r=t[1],i=t[2],s=n.length,o=0,u,a,f,l,c,h;for(u=0;uo&&(o=n[u]);o++;var p=Array(o),d=Array(o),v=numeric.rep([o],Infinity),m=numeric.rep([o],-Infinity),g,y,b;for(f=0;fm[u]&&(m[u]=a);for(u=0;um[u+1]&&(m[u+1]=m[u]);for(u=o-1;u>=1;u--)v[u]=0;v--){while(l[g]>v)s[v]-=c[g]*s[l[g]],g--;s[v]/=c[g],g--}return s},numeric.cgrid=function(t,n){typeof t=="number"&&(t=[t,t]);var r=numeric.rep(t,-1),i,s,o;if(typeof n!="function")switch(n){case"L":n=function(e,n){return e>=t[0]/2||nf&&(f=i[u]);f++,r=numeric.rep([f],0);for(u=0;u1)o=u((i+s)/2),n[o]<=t?i=o:s=o;return this._at(t,i)}var r=t.length,c,h=Array(r);for(c=r-1;c!==-1;--c)h[c]=this.at(t[c]);return h},numeric.Spline.prototype.diff=function(){var t=this.x,n=this.yl,r=this.yr,i=this.kl,s=this.kr,o=n.length,u,a,f,l=i,c=s,h=Array(o),p=Array(o),d=numeric.add,v=numeric.mul,m=numeric.div,g=numeric.sub;for(u=o-1;u!==-1;--u)a=t[u+1]-t[u],f=g(r[u+1],n[u]),h[u]=m(d(v(f,6),v(i[u],-4*a),v(s[u+1],-2*a)),a*a),p[u+1]=m(d(v(f,-6),v(i[u],2*a),v(s[u+1],4*a)),a*a);return new numeric.Spline(t,l,c,h,p)},numeric.Spline.prototype.roots=function(){function t(e){return e*e}function n(e,t,n,r,i){var s=n*2-(t-e),o=-r*2+(t-e),u=(i+1)*.5,a=u*(1-u);return(1-u)*e+u*t+s*a*(1-u)+o*a*u}var r=[],i=this.x,s=this.yl,o=this.yr,u=this.kl,a=this.kr;typeof s[0]=="number"&&(s=[s],o=[o],u=[u],a=[a]);var f=s.length,l=i.length-1,c,h,p,d,v,m,g,y,b,w,r=Array(f),E,S,x,T,N,C,k,L,A,O,M,_,D,P,H,B,j,F=Math.sqrt;for(c=0;c!==f;++c){g=s[c],y=o[c],b=u[c],w=a[c],E=[];for(h=0;h!==l;h++){h>0&&y[h]*g[h]<0&&E.push(i[h]),A=i[h+1]-i[h],O=i[h],T=g[h],N=y[h+1],S=b[h]/A,x=w[h+1]/A,L=t(S-x+3*(T-N))+12*x*T,C=x+3*T+2*S-3*N,k=3*(x+S+2*(T-N)),L<=0?(_=C/k,_>i[h]&&_i[h]&&_i[h]&&D0){H=B,_=D;continue}var I=0;for(;;){j=(_*B-D*H)/(_-D);if(j<=H||j>=B)break;P=this._at(j,h);if(P*D>0)B=j,D=P,I===-1&&(_*=.5),I=-1;else{if(!(P*_>0))break;H=j,_=P,I===1&&(D*=.5),I=1}}E.push(j),H=M[p+1],_=this._at(H,h)}D===0&&E.push(B)}r[c]=E}return typeof this.yl[0]=="number"?r[0]:r},numeric.spline=function(t,n,r,i){var s=t.length,o=[],u=[],a=[],f,l=numeric.sub,c=numeric.mul,h=numeric.add;for(f=s-2;f>=0;f--)u[f]=t[f+1]-t[f],a[f]=l(n[f+1],n[f]);if(typeof r=="string"||typeof i=="string")r=i="periodic";var p=[[],[],[]];switch(typeof r){case"undefined":o[0]=c(3/(u[0]*u[0]),a[0]),p[0].push(0,0),p[1].push(0,1),p[2].push(2/u[0],1/u[0]);break;case"string":o[0]=h(c(3/(u[s-2]*u[s-2]),a[s-2]),c(3/(u[0]*u[0]),a[0])),p[0].push(0,0,0),p[1].push(s-2,0,1),p[2].push(1/u[s-2],2/u[s-2]+2/u[0],1/u[0]);break;default:o[0]=r,p[0].push(0),p[1].push(0),p[2].push(1)}for(f=1;f20)throw new Error("Numerical gradient fails");u[o]=n[o]+N,a=t(u),u[o]=n[o]-N,f=t(u),u[o]=n[o];if(isNaN(a)||isNaN(f)){N/=16;continue}l[o]=(a-f)/(2*N),y=n[o]-N,b=n[o],w=n[o]+N,S=(a-i)/N,x=(i-f)/N,T=s(m(l[o]),m(i),m(a),m(f),m(y),m(b),m(w),1e-8),p=g(s(m(S-l[o]),m(x-l[o]),m(S-x))/T,N/T);if(!(p>v))break;N/=16}}return l},numeric.uncmin=function(t,n,r,i,s,o,u){var a=numeric.gradient;typeof u=="undefined"&&(u={}),typeof r=="undefined"&&(r=1e-8),typeof i=="undefined"&&(i=function(e){return a(t,e)}),typeof s=="undefined"&&(s=1e3),n=numeric.clone(n);var f=n.length,l=t(n),c,h;if(isNaN(l))throw new Error("uncmin: f(x0) is a NaN!");var p=Math.max,d=numeric.norm2;r=p(r,numeric.epsilon);var v,m,g,y=u.Hinv||numeric.identity(f),b=numeric.dot,w=numeric.inv,E=numeric.sub,S=numeric.add,x=numeric.tensor,T=numeric.div,N=numeric.mul,C=numeric.all,k=numeric.isFinite,L=numeric.neg,A=0,O,M,_,D,P,H,B,j,F,I,q,R,U="";m=i(n);while(A=.1*F*h||isNaN(c)){F*=.5,++A;continue}break}if(F*I1)i=s(.5*(n+r)),a[i]<=t?n=i:r=i;return this._at(t,n)},numeric.dopri=function(t,n,r,i,s,o,u){typeof s=="undefined"&&(s=1e-6),typeof o=="undefined"&&(o=1e3);var a=[t],f=[r],l=[i(t,r)],c,h,p,d,v,m,g=[],y=.2,b=[.075,.225],w=[44/45,-56/15,32/9],E=[19372/6561,-25360/2187,64448/6561,-212/729],S=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],x=[35/384,0,500/1113,125/192,-2187/6784,11/84],T=[.10013431883002395,0,.3918321794184259,-0.02982460176594817,.05893268337240795,-0.04497888809104361,.023904308236133973],N=[.2,.3,.8,8/9,1,1],C=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,.025],k=0,L,A,O=(n-t)/10,M=0,_=numeric.add,D=numeric.mul,P,H,B=Math.max,j=Math.min,F=Math.abs,I=numeric.norminf,q=Math.pow,R=numeric.any,U=numeric.lt,z=numeric.and,W=numeric.sub,X,V,$,J=new numeric.Dopri(a,f,l,g,-1,"");typeof u=="function"&&(X=u(t,r));while(tn&&(O=n-t),c=i(t+N[0]*O,_(r,D(y*O,l[k]))),h=i(t+N[1]*O,_(_(r,D(b[0]*O,l[k])),D(b[1]*O,c))),p=i(t+N[2]*O,_(_(_(r,D(w[0]*O,l[k])),D(w[1]*O,c)),D(w[2]*O,h))),d=i(t+N[3]*O,_(_(_(_(r,D(E[0]*O,l[k])),D(E[1]*O,c)),D(E[2]*O,h)),D(E[3]*O,p))),v=i(t+N[4]*O,_(_(_(_(_(r,D(S[0]*O,l[k])),D(S[1]*O,c)),D(S[2]*O,h)),D(S[3]*O,p)),D(S[4]*O,d))),P=_(_(_(_(_(r,D(l[k],O*x[0])),D(h,O*x[2])),D(p,O*x[3])),D(d,O*x[4])),D(v,O*x[5])),m=i(t+O,P),L=_(_(_(_(_(D(l[k],O*C[0]),D(h,O*C[2])),D(p,O*C[3])),D(d,O*C[4])),D(v,O*C[5])),D(m,O*C[6])),typeof L=="number"?H=F(L):H=I(L);if(H>s){O=.2*O*q(s/H,.25);if(t+O===t){J.msg="Step size became too small";break}continue}g[k]=_(_(_(_(_(_(r,D(l[k],O*T[0])),D(h,O*T[2])),D(p,O*T[3])),D(d,O*T[4])),D(v,O*T[5])),D(m,O*T[6])),++k,a[k]=t+O,f[k]=P,l[k]=m;if(typeof u=="function"){var K,Q=t,G=t+.5*O,Y;V=u(G,g[k-1]),$=z(U(X,0),U(0,V)),R($)||(Q=G,G=t+O,X=V,V=u(G,P),$=z(U(X,0),U(0,V)));if(R($)){var Z,et,tt,nt,rt=0,it=1,st=1;for(;;){if(typeof X=="number")Y=(st*V*Q-it*X*G)/(st*V-it*X);else{Y=G;for(A=X.length-1;A!==-1;--A)X[A]<0&&V[A]>0&&(Y=j(Y,(st*V[A]*Q-it*X[A]*G)/(st*V[A]-it*X[A])))}if(Y<=Q||Y>=G)break;K=J._at(Y,k-1),nt=u(Y,K),tt=z(U(X,0),U(0,nt)),R(tt)?(G=Y,V=nt,$=tt,st=1,rt===-1?it*=.5:it=1,rt=-1):(Q=Y,X=nt,it=1,rt===1?st*=.5:st=1,rt=1)}return P=J._at(.5*(t+Y),k-1),J.f[k]=i(Y,K),J.x[k]=Y,J.y[k]=K,J.ymid[k-1]=P,J.events=$,J.iterations=M,J}}t+=O,r=P,X=V,O=j(.8*O*q(s/H,.25),4*O)}return J.iterations=M,J},numeric.LU=function(e,t){t=t||!1;var n=Math.abs,r,i,s,o,u,a,f,l,c,h=e.length,p=h-1,d=new Array(h);t||(e=numeric.clone(e));for(s=0;s=0;--r){l=s[r];for(i=r+1;iK)E=K;W=d(t,l(E,B)),I=h(J,j);for(X=v-1;X!==-1;--X)I[X][X]+=1;$=q(I,p(W,E),!0);var Q=p(R,h(n,$)),G=1;for(X=m-1;X!==-1;--X)Q[X]<0&&(G=D(G,-0.999*Q[X]));g=c(o,l($,G)),R=c(r,h(n,g));if(!P(H(R,0)))return{solution:o,message:"",iterations:U};o=g;if(E=0?y=!1:y=!0;if(y)return{solution:g,message:"Unbounded",iterations:U}}return{solution:o,message:"maximum iteration count exceeded",iterations:U}},numeric._solveLP=function(t,n,r,i,s){var o=t.length,u=r.length,a,f=numeric.sum,l=numeric.log,c=numeric.mul,h=numeric.sub,p=numeric.dot,d=numeric.div,v=numeric.add,m=numeric.rep([o],0).concat([1]),g=numeric.rep([u,1],-1),y=numeric.blockMatrix([[n,g]]),b=r,a=numeric.rep([o],0).concat(Math.max(0,numeric.sup(numeric.neg(r)))+1),w=numeric.__solveLP(m,y,b,i,s,a,!1),E=numeric.clone(w.solution);E.length=o;var S=numeric.inf(h(r,p(n,E)));if(S<0)return{solution:NaN,message:"Infeasible",iterations:w.iterations};var x=numeric.__solveLP(t,n,r,i,s-w.iterations,E,!0);return x.iterations+=w.iterations,x},numeric.solveLP=function(t,n,r,i,s,o,u){typeof u=="undefined"&&(u=1e3),typeof o=="undefined"&&(o=numeric.epsilon);if(typeof i=="undefined")return numeric._solveLP(t,n,r,o,u);var a=i.length,f=i[0].length,l=n.length,c=numeric.echelonize(i),h=numeric.rep([f],0),p=c.P,d=[],v;for(v=p.length-1;v!==-1;--v)h[p[v]]=1;for(v=f-1;v!==-1;--v)h[v]===0&&d.push(v);var m=numeric.getRange,g=numeric.linspace(0,a-1),y=numeric.linspace(0,l-1),b=m(i,g,d),w=m(n,y,p),E=m(n,y,d),S=numeric.dot,x=numeric.sub,T=S(w,c.I),N=x(E,S(T,b)),C=x(r,S(T,s)),k=Array(p.length),L=Array(d.length);for(v=p.length-1;v!==-1;--v)k[v]=t[p[v]];for(v=d.length-1;v!==-1;--v)L[v]=t[d[v]];var A=x(L,S(k,S(c.I,b))),O=numeric._solveLP(A,N,C,o,u),M=O.solution;if(M!==M)return O;var _=S(c.I,x(s,S(b,M))),D=Array(t.length);for(v=p.length-1;v!==-1;--v)D[p[v]]=_[v];for(v=d.length-1;v!==-1;--v)D[d[v]]=M[v];return{solution:D,message:O.message,iterations:O.iterations}},numeric.MPStoLP=function(t){function y(e){throw new Error("MPStoLP: "+e+"\nLine "+s+": "+t[s]+"\nCurrent state: "+r[n]+"\n")}t instanceof String&&t.split("\n");var n=0,r=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],i=t.length,s,o,u,a=0,f={},l=[],c=0,h={},p=0,d,v=[],m=[],g=[];for(s=0;s=s)t/=2,u/=2,a>>>=1;return(t+a)/u},c},o=t.pow(n,r),i=t.pow(2,i),s=i*2,f(t.random(),e)}([],numeric.seedrandom,256,6,52),function(e){function t(e){if(typeof e!="object")return e;var n=[],r,i=e.length;for(r=0;rp)g[E]=P;else{g[E]=-Math.abs(P);if(P>0){for(w=1;w<=o;w+=1)f[w][b]=-f[w][b];l[b]=-l[b]}}}for(b=1;b<=v;b+=1)g[L+d[b]]=0;O=0,D=0;for(b=1;b<=h;b+=1)g[L+b]=1;b-=1){P=g[b],E=k+b*(b+3)/2,S=E-b;for(w=b+1;w<=v;w+=1)P-=g[E]*g[C+w],E+=w;P/=g[S],g[C+b]=P;if(d[b]p)g[L+O]=P;else{g[L+O]=-Math.abs(P);if(P>0){for(w=1;w<=o;w+=1)f[w][O]=-f[w][O];l[O]=-l[O]}}return 700}v+=1,d[v]=O,E=k+(v-1)*v/2+1;for(b=1;b<=v-1;b+=1)g[E]=g[b],E+=1;if(v===o)g[E]=g[o];else{for(b=o;b>=v+1;b-=1){if(g[b]===0)break;j=Math.max(Math.abs(g[b-1]),Math.abs(g[b])),F=Math.min(Math.abs(g[b-1]),Math.abs(g[b])),g[b-1]>=0?D=Math.abs(j*Math.sqrt(1+F*F/(j*j))):D=-Math.abs(j*Math.sqrt(1+F*F/(j*j))),j=g[b-1]/D,F=g[b]/D;if(j===1)break;if(j===0){g[b-1]=F*D;for(w=1;w<=o;w+=1)D=e[w][b-1],e[w][b-1]=e[w][b],e[w][b]=D}else{g[b-1]=D,I=F/(1+j);for(w=1;w<=o;w+=1)D=j*e[w][b-1]+F*e[w][b],e[w][b]=I*(e[w][b-1]+D)-e[w][b],e[w][b-1]=D}}g[E]=g[v]}return 0}function J(){E=k+T*(T+1)/2+1,S=E+T;if(g[S]===0)return 798;j=Math.max(Math.abs(g[S-1]),Math.abs(g[S])),F=Math.min(Math.abs(g[S-1]),Math.abs(g[S])),g[S-1]>=0?D=Math.abs(j*Math.sqrt(1+F*F/(j*j))):D=-Math.abs(j*Math.sqrt(1+F*F/(j*j))),j=g[S-1]/D,F=g[S]/D;if(j===1)return 798;if(j===0){for(b=T+1;b<=v;b+=1)D=g[S-1],g[S-1]=g[S],g[S]=D,S+=b;for(b=1;b<=o;b+=1)D=e[b][T],e[b][T]=e[b][T+1],e[b][T+1]=D}else{I=F/(1+j);for(b=T+1;b<=v;b+=1)D=j*g[S-1]+F*g[S],g[S]=I*(g[S-1]+D)-g[S],g[S-1]=D,S+=b;for(b=1;b<=o;b+=1)D=j*e[b][T]+F*e[b][T+1],e[b][T+1]=I*(e[b][T]+D)-e[b][T+1],e[b][T]=D}return 0}function K(){S=E-T;for(b=1;b<=T;b+=1)g[S]=g[E],E+=1,S+=1;return g[A+T]=g[A+T+1],d[T]=d[T+1],T+=1,Tt?e*Math.sqrt(1+t*t/e/e):t==0?e:t*Math.sqrt(1+e*e/t/t)}var n,r=numeric.epsilon,i=1e-64/r,s=50,o=0,u=0,a=0,f=0,l=0,c=numeric.clone(t),h=c.length,p=c[0].length;if(h=0&&(b=-b),w=y*b-T,c[u][u]=y-b;for(a=l;a=0&&(b=-b),w=y*b-T,c[u][u+1]=y-b;for(a=l;aE&&(E=S)}for(u=p-1;u!=-1;u+=-1){if(b!=0){w=b*c[u][u+1];for(a=l;a=s-1)throw"Error: no convergence.";E=v[l],S=v[f-1],b=d[f-1],w=d[f],y=((S-x)*(S+x)+(b-w)*(b+w))/(2*w*S),b=g(y,1),y<0?y=((E-x)*(E+x)+w*(S/(y-b)-w))/E:y=((E-x)*(E+x)+w*(S/(y+b)-w))/E,o=1,T=1;for(u=l+1;u=0;a--)if(v[a]Math.abs(e))c.rotate(o,0,0,-t*i*Math.PI*p.rotateSpeed/window.innerWidth);else{var s=p.zoomSpeed*a*e/window.innerHeight*(o-c.lastT())/100;c.pan(o,0,0,f*(Math.exp(s)-1))}},!0),p};var n=t("right-now"),i=t("3d-view"),a=t("mouse-change"),o=t("mouse-wheel"),s=t("mouse-event-offset"),l=t("has-passive-events")},{"3d-view":40,"has-passive-events":256,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427,"right-now":489}],40:[function(t,e,r){"use strict";e.exports=function(t){var e=(t=t||{}).eye||[0,0,1],r=t.center||[0,0,0],s=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],c=t.mode||"turntable",u=n(),f=i(),h=a();return u.setDistanceLimits(l[0],l[1]),u.lookAt(0,e,r,s),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,s),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,s),new o({turntable:u,orbit:f,matrix:h},c)};var n=t("turntable-camera-controller"),i=t("orbit-camera-controller"),a=t("matrix-camera-controller");function o(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}var s=o.prototype;[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]].forEach(function(t){for(var e=t[0],r=[],n=0;n0;--t)d(c*=.99),p(),h(c),p();function h(t){function r(t){return u(t.source)*t.value}i.forEach(function(n){n.forEach(function(n){if(n.targetLinks.length){var i=e.sum(n.targetLinks,r)/e.sum(n.targetLinks,f);n.y+=(i-u(n))*t}})})}function d(t){function r(t){return u(t.target)*t.value}i.slice().reverse().forEach(function(n){n.forEach(function(n){if(n.sourceLinks.length){var i=e.sum(n.sourceLinks,r)/e.sum(n.sourceLinks,f);n.y+=(i-u(n))*t}})})}function p(){i.forEach(function(t){var e,r,n,i=0,s=t.length;for(t.sort(m),n=0;n0&&(e.y+=r),i=e.y+e.dy+a;if((r=i-a-o[1])>0)for(i=e.y-=r,n=s-2;n>=0;--n)e=t[n],(r=e.y+e.dy+a-i)>0&&(e.y-=r),i=e.y})}function m(t,e){return t.y-e.y}}(n),c(),t},t.relayout=function(){return c(),t},t.link=function(){var t=.5;function e(e){var r=e.source.x+e.source.dx,i=e.target.x,a=n.interpolateNumber(r,i),o=a(t),s=a(1-t),l=e.source.y+e.sy,c=l+e.dy,u=e.target.y+e.ty,f=u+e.dy;return"M"+r+","+l+"C"+o+","+l+" "+s+","+u+" "+i+","+u+"L"+i+","+f+"C"+s+","+f+" "+o+","+c+" "+r+","+c+"Z"}return e.curvature=function(r){return arguments.length?(t=+r,e):t},e},t},Object.defineProperty(t,"__esModule",{value:!0})},"object"==typeof r&&void 0!==e?i(r,t("d3-array"),t("d3-collection"),t("d3-interpolate")):i(n.d3=n.d3||{},n.d3,n.d3,n.d3)},{"d3-array":120,"d3-collection":121,"d3-interpolate":125}],42:[function(t,e,r){"use strict";var n="undefined"==typeof WeakMap?t("weak-map"):WeakMap,i=t("gl-buffer"),a=t("gl-vao"),o=new n;e.exports=function(t){var e=o.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=i(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=a(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,o.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}},{"gl-buffer":165,"gl-vao":237,"weak-map":553}],43:[function(t,e,r){e.exports=function(t){var e=0,r=0,n=0,i=0;return t.map(function(t){var a=(t=t.slice())[0],o=a.toUpperCase();if(a!=o)switch(t[0]=o,a){case"a":t[6]+=n,t[7]+=i;break;case"v":t[1]+=i;break;case"h":t[1]+=n;break;default:for(var s=1;si&&(i=t[o]),t[o]=0;c--)if(u[c]!==f[c])return!1;for(c=u.length-1;c>=0;c--)if(l=u[c],!y(t[l],e[l],r,n))return!1;return!0}(t,e,r,o))}return r?t===e:t==e}function b(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function x(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function _(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&v(i,r,"Missing expected exception"+n);var o="string"==typeof n,s=!t&&a.isError(i),l=!t&&i&&!r;if((s&&o&&x(i,r)||l)&&v(i,r,"Got unwanted exception"+n),t&&i&&r&&!x(i,r)||!t&&i)throw i}f.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=p(m((e=this).actual),128)+" "+e.operator+" "+p(m(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||v;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,a=d(r),o=i.indexOf("\n"+a);if(o>=0){var s=i.indexOf("\n",o+1);i=i.substring(s+1)}this.stack=i}}},a.inherits(f.AssertionError,Error),f.fail=v,f.ok=g,f.equal=function(t,e,r){t!=e&&v(t,e,r,"==",f.equal)},f.notEqual=function(t,e,r){t==e&&v(t,e,r,"!=",f.notEqual)},f.deepEqual=function(t,e,r){y(t,e,!1)||v(t,e,r,"deepEqual",f.deepEqual)},f.deepStrictEqual=function(t,e,r){y(t,e,!0)||v(t,e,r,"deepStrictEqual",f.deepStrictEqual)},f.notDeepEqual=function(t,e,r){y(t,e,!1)&&v(t,e,r,"notDeepEqual",f.notDeepEqual)},f.notDeepStrictEqual=function t(e,r,n){y(e,r,!0)&&v(e,r,n,"notDeepStrictEqual",t)},f.strictEqual=function(t,e,r){t!==e&&v(t,e,r,"===",f.strictEqual)},f.notStrictEqual=function(t,e,r){t===e&&v(t,e,r,"!==",f.notStrictEqual)},f.throws=function(t,e,r){_(!0,t,e,r)},f.doesNotThrow=function(t,e,r){_(!1,t,e,r)},f.ifError=function(t){if(t)throw t};var w=Object.keys||function(t){var e=[];for(var r in t)o.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":543}],52:[function(t,e,r){e.exports=function(t){return atob(t)}},{}],53:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=e.length,a=new Array(r+1),o=0;o0?u=u.ushln(c):c<0&&(f=f.ushln(-c));return s(u,f)}},{"./div":56,"./is-rat":58,"./lib/is-bn":62,"./lib/num-to-bn":63,"./lib/rationalize":64,"./lib/str-to-bn":65}],58:[function(t,e,r){"use strict";var n=t("./lib/is-bn");e.exports=function(t){return Array.isArray(t)&&2===t.length&&n(t[0])&&n(t[1])}},{"./lib/is-bn":62}],59:[function(t,e,r){"use strict";var n=t("bn.js");e.exports=function(t){return t.cmp(new n(0))}},{"bn.js":73}],60:[function(t,e,r){"use strict";var n=t("./bn-sign");e.exports=function(t){var e=t.length,r=t.words,i=0;if(1===e)i=r[0];else if(2===e)i=r[0]+67108864*r[1];else for(var a=0;a20)return 52;return r+32}},{"bit-twiddle":71,"double-bits":131}],62:[function(t,e,r){"use strict";t("bn.js");e.exports=function(t){return t&&"object"==typeof t&&Boolean(t.words)}},{"bn.js":73}],63:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("double-bits");e.exports=function(t){var e=i.exponent(t);return e<52?new n(t):new n(t*Math.pow(2,52-e)).ushln(e-52)}},{"bn.js":73,"double-bits":131}],64:[function(t,e,r){"use strict";var n=t("./num-to-bn"),i=t("./bn-sign");e.exports=function(t,e){var r=i(t),a=i(e);if(0===r)return[n(0),n(1)];if(0===a)return[n(0),n(0)];a<0&&(t=t.neg(),e=e.neg());var o=t.gcd(e);if(o.cmpn(1))return[t.div(o),e.div(o)];return[t,e]}},{"./bn-sign":59,"./num-to-bn":63}],65:[function(t,e,r){"use strict";var n=t("bn.js");e.exports=function(t){return new n(t)}},{"bn.js":73}],66:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[0]),t[1].mul(e[1]))}},{"./lib/rationalize":64}],67:[function(t,e,r){"use strict";var n=t("./lib/bn-sign");e.exports=function(t){return n(t[0])*n(t[1])}},{"./lib/bn-sign":59}],68:[function(t,e,r){"use strict";var n=t("./lib/rationalize");e.exports=function(t,e){return n(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}},{"./lib/rationalize":64}],69:[function(t,e,r){"use strict";var n=t("./lib/bn-to-num"),i=t("./lib/ctz");e.exports=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var a=e.abs().divmod(r.abs()),o=a.div,s=n(o),l=a.mod,c=e.negative!==r.negative?-1:1;if(0===l.cmpn(0))return c*s;if(s){var u=i(s)+4,f=n(l.ushln(u).divRound(r));return c*(s+f*Math.pow(2,-u))}var h=r.bitLength()-l.bitLength()+53,f=n(l.ushln(h).divRound(r));return h<1023?c*f*Math.pow(2,-h):(f*=Math.pow(2,-1023),c*f*Math.pow(2,1023-h))}},{"./lib/bn-to-num":60,"./lib/ctz":61}],70:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){return new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""))()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],71:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return(t&=-t)&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}r.INT_BITS=32,r.INT_MAX=2147483647,r.INT_MIN=-1<<31,r.sign=function(t){return(t>0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},r.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},r.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],72:[function(t,e,r){"use strict";var n=t("clamp");e.exports=function(t,e){e||(e={});var r,o,s,l,c,u,f,h,d,p,m,v=null==e.cutoff?.25:e.cutoff,g=null==e.radius?8:e.radius,y=e.channel||0;if(ArrayBuffer.isView(t)||Array.isArray(t)){if(!e.width||!e.height)throw Error("For raw data width and height should be provided by options");r=e.width,o=e.height,l=t,u=e.stride?e.stride:Math.floor(t.length/r/o)}else window.HTMLCanvasElement&&t instanceof window.HTMLCanvasElement?(f=(h=t).getContext("2d"),r=h.width,o=h.height,d=f.getImageData(0,0,r,o),l=d.data,u=4):window.CanvasRenderingContext2D&&t instanceof window.CanvasRenderingContext2D?(h=t.canvas,f=t,r=h.width,o=h.height,d=f.getImageData(0,0,r,o),l=d.data,u=4):window.ImageData&&t instanceof window.ImageData&&(d=t,r=t.width,o=t.height,l=d.data,u=4);if(s=Math.max(r,o),window.Uint8ClampedArray&&l instanceof window.Uint8ClampedArray||window.Uint8Array&&l instanceof window.Uint8Array)for(c=l,l=Array(r*o),p=0,m=c.length;p=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function l(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o=49?s-49+10:s>=17?s-17+10:s}return i}a.isBN=function(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor.wordSize===a.wordSize&&Array.isArray(t.words)},a.max=function(t,e){return t.cmp(e)>0?t:e},a.min=function(t,e){return t.cmp(e)<0?t:e},a.prototype._init=function(t,e,r){if("number"==typeof t)return this._initNumber(t,e,r);if("object"==typeof t)return this._initArray(t,e,r);"hex"===e&&(e=16),n(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),e,r)},a.prototype._initNumber=function(t,e,r){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(n(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),e,r)},a.prototype._initArray=function(t,e,r){if(n("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===r)for(i=0,a=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},a.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=s(t,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=s(t,e,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},a.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,s=Math.min(a,a-o)+r,c=0,u=r;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var c=1;c>>26,f=67108863&l,h=Math.min(c,e.length-1),d=Math.max(0,c-t.length+1);d<=h;d++){var p=c-d|0;u+=(o=(i=0|t.words[p])*(a=0|e.words[d])+f)/67108864|0,f=67108863&o}r.words[c]=0|f,l=0|u}return 0!==l?r.words[c]=0|l:r.length--,r.strip()}a.prototype.toString=function(t,e){var r;if(t=t||10,e=0|e||1,16===t||"hex"===t){r="";for(var i=0,a=0,o=0;o>>24-i&16777215)||o!==this.length-1?c[6-l.length]+l+r:l+r,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(r=a.toString(16)+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(t===(0|t)&&t>=2&&t<=36){var h=u[t],d=f[t];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var m=p.modn(d).toString(t);r=(p=p.idivn(d)).isZero()?m+r:c[h-m.length]+m+r}for(this.isZero()&&(r="0"+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(t,e){return n(void 0!==o),this.toArrayLike(o,t,e)},a.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},a.prototype.toArrayLike=function(t,e,r){var i=this.byteLength(),a=r||Math.max(1,i);n(i<=a,"byte array longer than desired length"),n(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,c=new t(a),u=this.clone();if(l){for(s=0;!u.isZero();s++)o=u.andln(255),u.iushrn(8),c[s]=o;for(;s=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},a.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},a.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},a.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},a.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},a.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},a.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},a.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},a.prototype.inotn=function(t){n("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),r=t%26;this._expand(e),r>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},a.prototype.notn=function(t){return this.clone().inotn(t)},a.prototype.setn=function(t,e){n("number"==typeof t&&t>=0);var r=t/26|0,i=t%26;return this._expand(r+1),this.words[r]=e?this.words[r]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},a.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==a&&o>26,this.words[o]=67108863&e;if(0===a&&o>>13,d=0|o[1],p=8191&d,m=d>>>13,v=0|o[2],g=8191&v,y=v>>>13,b=0|o[3],x=8191&b,_=b>>>13,w=0|o[4],M=8191&w,k=w>>>13,A=0|o[5],T=8191&A,E=A>>>13,S=0|o[6],L=8191&S,C=S>>>13,P=0|o[7],z=8191&P,O=P>>>13,D=0|o[8],I=8191&D,R=D>>>13,N=0|o[9],F=8191&N,j=N>>>13,B=0|s[0],U=8191&B,V=B>>>13,q=0|s[1],H=8191&q,G=q>>>13,Y=0|s[2],W=8191&Y,X=Y>>>13,Z=0|s[3],J=8191&Z,K=Z>>>13,Q=0|s[4],$=8191&Q,tt=Q>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ct=st>>>13,ut=0|s[8],ft=8191&ut,ht=ut>>>13,dt=0|s[9],pt=8191&dt,mt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(c+(n=Math.imul(f,U))|0)+((8191&(i=(i=Math.imul(f,V))+Math.imul(h,U)|0))<<13)|0;c=((a=Math.imul(h,V))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,V))+Math.imul(m,U)|0,a=Math.imul(m,V);var gt=(c+(n=n+Math.imul(f,H)|0)|0)+((8191&(i=(i=i+Math.imul(f,G)|0)+Math.imul(h,H)|0))<<13)|0;c=((a=a+Math.imul(h,G)|0)+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(g,U),i=(i=Math.imul(g,V))+Math.imul(y,U)|0,a=Math.imul(y,V),n=n+Math.imul(p,H)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(m,H)|0,a=a+Math.imul(m,G)|0;var yt=(c+(n=n+Math.imul(f,W)|0)|0)+((8191&(i=(i=i+Math.imul(f,X)|0)+Math.imul(h,W)|0))<<13)|0;c=((a=a+Math.imul(h,X)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,V))+Math.imul(_,U)|0,a=Math.imul(_,V),n=n+Math.imul(g,H)|0,i=(i=i+Math.imul(g,G)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,X)|0)+Math.imul(m,W)|0,a=a+Math.imul(m,X)|0;var bt=(c+(n=n+Math.imul(f,J)|0)|0)+((8191&(i=(i=i+Math.imul(f,K)|0)+Math.imul(h,J)|0))<<13)|0;c=((a=a+Math.imul(h,K)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(M,U),i=(i=Math.imul(M,V))+Math.imul(k,U)|0,a=Math.imul(k,V),n=n+Math.imul(x,H)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(g,W)|0,i=(i=i+Math.imul(g,X)|0)+Math.imul(y,W)|0,a=a+Math.imul(y,X)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,K)|0)+Math.imul(m,J)|0,a=a+Math.imul(m,K)|0;var xt=(c+(n=n+Math.imul(f,$)|0)|0)+((8191&(i=(i=i+Math.imul(f,tt)|0)+Math.imul(h,$)|0))<<13)|0;c=((a=a+Math.imul(h,tt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(T,U),i=(i=Math.imul(T,V))+Math.imul(E,U)|0,a=Math.imul(E,V),n=n+Math.imul(M,H)|0,i=(i=i+Math.imul(M,G)|0)+Math.imul(k,H)|0,a=a+Math.imul(k,G)|0,n=n+Math.imul(x,W)|0,i=(i=i+Math.imul(x,X)|0)+Math.imul(_,W)|0,a=a+Math.imul(_,X)|0,n=n+Math.imul(g,J)|0,i=(i=i+Math.imul(g,K)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,K)|0,n=n+Math.imul(p,$)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(m,$)|0,a=a+Math.imul(m,tt)|0;var _t=(c+(n=n+Math.imul(f,rt)|0)|0)+((8191&(i=(i=i+Math.imul(f,nt)|0)+Math.imul(h,rt)|0))<<13)|0;c=((a=a+Math.imul(h,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(L,U),i=(i=Math.imul(L,V))+Math.imul(C,U)|0,a=Math.imul(C,V),n=n+Math.imul(T,H)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(E,H)|0,a=a+Math.imul(E,G)|0,n=n+Math.imul(M,W)|0,i=(i=i+Math.imul(M,X)|0)+Math.imul(k,W)|0,a=a+Math.imul(k,X)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,K)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,K)|0,n=n+Math.imul(g,$)|0,i=(i=i+Math.imul(g,tt)|0)+Math.imul(y,$)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(p,rt)|0,i=(i=i+Math.imul(p,nt)|0)+Math.imul(m,rt)|0,a=a+Math.imul(m,nt)|0;var wt=(c+(n=n+Math.imul(f,at)|0)|0)+((8191&(i=(i=i+Math.imul(f,ot)|0)+Math.imul(h,at)|0))<<13)|0;c=((a=a+Math.imul(h,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(z,U),i=(i=Math.imul(z,V))+Math.imul(O,U)|0,a=Math.imul(O,V),n=n+Math.imul(L,H)|0,i=(i=i+Math.imul(L,G)|0)+Math.imul(C,H)|0,a=a+Math.imul(C,G)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(E,W)|0,a=a+Math.imul(E,X)|0,n=n+Math.imul(M,J)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(k,J)|0,a=a+Math.imul(k,K)|0,n=n+Math.imul(x,$)|0,i=(i=i+Math.imul(x,tt)|0)+Math.imul(_,$)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(g,rt)|0,i=(i=i+Math.imul(g,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(p,at)|0,i=(i=i+Math.imul(p,ot)|0)+Math.imul(m,at)|0,a=a+Math.imul(m,ot)|0;var Mt=(c+(n=n+Math.imul(f,lt)|0)|0)+((8191&(i=(i=i+Math.imul(f,ct)|0)+Math.imul(h,lt)|0))<<13)|0;c=((a=a+Math.imul(h,ct)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(I,U),i=(i=Math.imul(I,V))+Math.imul(R,U)|0,a=Math.imul(R,V),n=n+Math.imul(z,H)|0,i=(i=i+Math.imul(z,G)|0)+Math.imul(O,H)|0,a=a+Math.imul(O,G)|0,n=n+Math.imul(L,W)|0,i=(i=i+Math.imul(L,X)|0)+Math.imul(C,W)|0,a=a+Math.imul(C,X)|0,n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,K)|0)+Math.imul(E,J)|0,a=a+Math.imul(E,K)|0,n=n+Math.imul(M,$)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(k,$)|0,a=a+Math.imul(k,tt)|0,n=n+Math.imul(x,rt)|0,i=(i=i+Math.imul(x,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(g,at)|0,i=(i=i+Math.imul(g,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(p,lt)|0,i=(i=i+Math.imul(p,ct)|0)+Math.imul(m,lt)|0,a=a+Math.imul(m,ct)|0;var kt=(c+(n=n+Math.imul(f,ft)|0)|0)+((8191&(i=(i=i+Math.imul(f,ht)|0)+Math.imul(h,ft)|0))<<13)|0;c=((a=a+Math.imul(h,ht)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(F,U),i=(i=Math.imul(F,V))+Math.imul(j,U)|0,a=Math.imul(j,V),n=n+Math.imul(I,H)|0,i=(i=i+Math.imul(I,G)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,G)|0,n=n+Math.imul(z,W)|0,i=(i=i+Math.imul(z,X)|0)+Math.imul(O,W)|0,a=a+Math.imul(O,X)|0,n=n+Math.imul(L,J)|0,i=(i=i+Math.imul(L,K)|0)+Math.imul(C,J)|0,a=a+Math.imul(C,K)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(E,$)|0,a=a+Math.imul(E,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(k,rt)|0,a=a+Math.imul(k,nt)|0,n=n+Math.imul(x,at)|0,i=(i=i+Math.imul(x,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(g,lt)|0,i=(i=i+Math.imul(g,ct)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ct)|0,n=n+Math.imul(p,ft)|0,i=(i=i+Math.imul(p,ht)|0)+Math.imul(m,ft)|0,a=a+Math.imul(m,ht)|0;var At=(c+(n=n+Math.imul(f,pt)|0)|0)+((8191&(i=(i=i+Math.imul(f,mt)|0)+Math.imul(h,pt)|0))<<13)|0;c=((a=a+Math.imul(h,mt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(F,H),i=(i=Math.imul(F,G))+Math.imul(j,H)|0,a=Math.imul(j,G),n=n+Math.imul(I,W)|0,i=(i=i+Math.imul(I,X)|0)+Math.imul(R,W)|0,a=a+Math.imul(R,X)|0,n=n+Math.imul(z,J)|0,i=(i=i+Math.imul(z,K)|0)+Math.imul(O,J)|0,a=a+Math.imul(O,K)|0,n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(C,$)|0,a=a+Math.imul(C,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(E,rt)|0,a=a+Math.imul(E,nt)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ot)|0)+Math.imul(k,at)|0,a=a+Math.imul(k,ot)|0,n=n+Math.imul(x,lt)|0,i=(i=i+Math.imul(x,ct)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ct)|0,n=n+Math.imul(g,ft)|0,i=(i=i+Math.imul(g,ht)|0)+Math.imul(y,ft)|0,a=a+Math.imul(y,ht)|0;var Tt=(c+(n=n+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,mt)|0)+Math.imul(m,pt)|0))<<13)|0;c=((a=a+Math.imul(m,mt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(F,W),i=(i=Math.imul(F,X))+Math.imul(j,W)|0,a=Math.imul(j,X),n=n+Math.imul(I,J)|0,i=(i=i+Math.imul(I,K)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,K)|0,n=n+Math.imul(z,$)|0,i=(i=i+Math.imul(z,tt)|0)+Math.imul(O,$)|0,a=a+Math.imul(O,tt)|0,n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(C,rt)|0,a=a+Math.imul(C,nt)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ot)|0)+Math.imul(E,at)|0,a=a+Math.imul(E,ot)|0,n=n+Math.imul(M,lt)|0,i=(i=i+Math.imul(M,ct)|0)+Math.imul(k,lt)|0,a=a+Math.imul(k,ct)|0,n=n+Math.imul(x,ft)|0,i=(i=i+Math.imul(x,ht)|0)+Math.imul(_,ft)|0,a=a+Math.imul(_,ht)|0;var Et=(c+(n=n+Math.imul(g,pt)|0)|0)+((8191&(i=(i=i+Math.imul(g,mt)|0)+Math.imul(y,pt)|0))<<13)|0;c=((a=a+Math.imul(y,mt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(F,J),i=(i=Math.imul(F,K))+Math.imul(j,J)|0,a=Math.imul(j,K),n=n+Math.imul(I,$)|0,i=(i=i+Math.imul(I,tt)|0)+Math.imul(R,$)|0,a=a+Math.imul(R,tt)|0,n=n+Math.imul(z,rt)|0,i=(i=i+Math.imul(z,nt)|0)+Math.imul(O,rt)|0,a=a+Math.imul(O,nt)|0,n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ot)|0)+Math.imul(C,at)|0,a=a+Math.imul(C,ot)|0,n=n+Math.imul(T,lt)|0,i=(i=i+Math.imul(T,ct)|0)+Math.imul(E,lt)|0,a=a+Math.imul(E,ct)|0,n=n+Math.imul(M,ft)|0,i=(i=i+Math.imul(M,ht)|0)+Math.imul(k,ft)|0,a=a+Math.imul(k,ht)|0;var St=(c+(n=n+Math.imul(x,pt)|0)|0)+((8191&(i=(i=i+Math.imul(x,mt)|0)+Math.imul(_,pt)|0))<<13)|0;c=((a=a+Math.imul(_,mt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(F,$),i=(i=Math.imul(F,tt))+Math.imul(j,$)|0,a=Math.imul(j,tt),n=n+Math.imul(I,rt)|0,i=(i=i+Math.imul(I,nt)|0)+Math.imul(R,rt)|0,a=a+Math.imul(R,nt)|0,n=n+Math.imul(z,at)|0,i=(i=i+Math.imul(z,ot)|0)+Math.imul(O,at)|0,a=a+Math.imul(O,ot)|0,n=n+Math.imul(L,lt)|0,i=(i=i+Math.imul(L,ct)|0)+Math.imul(C,lt)|0,a=a+Math.imul(C,ct)|0,n=n+Math.imul(T,ft)|0,i=(i=i+Math.imul(T,ht)|0)+Math.imul(E,ft)|0,a=a+Math.imul(E,ht)|0;var Lt=(c+(n=n+Math.imul(M,pt)|0)|0)+((8191&(i=(i=i+Math.imul(M,mt)|0)+Math.imul(k,pt)|0))<<13)|0;c=((a=a+Math.imul(k,mt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(F,rt),i=(i=Math.imul(F,nt))+Math.imul(j,rt)|0,a=Math.imul(j,nt),n=n+Math.imul(I,at)|0,i=(i=i+Math.imul(I,ot)|0)+Math.imul(R,at)|0,a=a+Math.imul(R,ot)|0,n=n+Math.imul(z,lt)|0,i=(i=i+Math.imul(z,ct)|0)+Math.imul(O,lt)|0,a=a+Math.imul(O,ct)|0,n=n+Math.imul(L,ft)|0,i=(i=i+Math.imul(L,ht)|0)+Math.imul(C,ft)|0,a=a+Math.imul(C,ht)|0;var Ct=(c+(n=n+Math.imul(T,pt)|0)|0)+((8191&(i=(i=i+Math.imul(T,mt)|0)+Math.imul(E,pt)|0))<<13)|0;c=((a=a+Math.imul(E,mt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(F,at),i=(i=Math.imul(F,ot))+Math.imul(j,at)|0,a=Math.imul(j,ot),n=n+Math.imul(I,lt)|0,i=(i=i+Math.imul(I,ct)|0)+Math.imul(R,lt)|0,a=a+Math.imul(R,ct)|0,n=n+Math.imul(z,ft)|0,i=(i=i+Math.imul(z,ht)|0)+Math.imul(O,ft)|0,a=a+Math.imul(O,ht)|0;var Pt=(c+(n=n+Math.imul(L,pt)|0)|0)+((8191&(i=(i=i+Math.imul(L,mt)|0)+Math.imul(C,pt)|0))<<13)|0;c=((a=a+Math.imul(C,mt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(F,lt),i=(i=Math.imul(F,ct))+Math.imul(j,lt)|0,a=Math.imul(j,ct),n=n+Math.imul(I,ft)|0,i=(i=i+Math.imul(I,ht)|0)+Math.imul(R,ft)|0,a=a+Math.imul(R,ht)|0;var zt=(c+(n=n+Math.imul(z,pt)|0)|0)+((8191&(i=(i=i+Math.imul(z,mt)|0)+Math.imul(O,pt)|0))<<13)|0;c=((a=a+Math.imul(O,mt)|0)+(i>>>13)|0)+(zt>>>26)|0,zt&=67108863,n=Math.imul(F,ft),i=(i=Math.imul(F,ht))+Math.imul(j,ft)|0,a=Math.imul(j,ht);var Ot=(c+(n=n+Math.imul(I,pt)|0)|0)+((8191&(i=(i=i+Math.imul(I,mt)|0)+Math.imul(R,pt)|0))<<13)|0;c=((a=a+Math.imul(R,mt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863;var Dt=(c+(n=Math.imul(F,pt))|0)+((8191&(i=(i=Math.imul(F,mt))+Math.imul(j,pt)|0))<<13)|0;return c=((a=Math.imul(j,mt))+(i>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,l[0]=vt,l[1]=gt,l[2]=yt,l[3]=bt,l[4]=xt,l[5]=_t,l[6]=wt,l[7]=Mt,l[8]=kt,l[9]=At,l[10]=Tt,l[11]=Et,l[12]=St,l[13]=Lt,l[14]=Ct,l[15]=Pt,l[16]=zt,l[17]=Ot,l[18]=Dt,0!==c&&(l[19]=c,r.length++),r};function p(t,e,r){return(new m).mulp(t,e,r)}function m(t,e){this.x=t,this.y=e}Math.imul||(d=h),a.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?d(this,t,e):r<63?h(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):p(this,t,e)},m.prototype.makeRBT=function(t){for(var e=new Array(t),r=a.prototype._countBits(t)-1,n=0;n>=1;return n},m.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o>>=1)i++;return 1<>>=13,r[2*o+1]=8191&a,a>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=a>>>26,this.words[r]=67108863&a}return 0!==e&&(this.words[r]=e,this.length++),this},a.prototype.muln=function(t){return this.clone().imuln(t)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new a(1);for(var r=this,n=0;n=0);var e,r=t%26,i=(t-r)/26,a=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(e=0;e>>26-r}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<o)for(this.length-=o,c=0;c=0&&(0!==u||c>=i);c--){var f=0|this.words[c];this.words[c]=u<<26-a|f>>>a,u=f&s}return l&&0!==u&&(l.words[l.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(t,e,r){return n(0===this.negative),this.iushrn(t,e,r)},a.prototype.shln=function(t){return this.clone().ishln(t)},a.prototype.ushln=function(t){return this.clone().iushln(t)},a.prototype.shrn=function(t){return this.clone().ishrn(t)},a.prototype.ushrn=function(t){return this.clone().iushrn(t)},a.prototype.testn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26,i=1<=0);var e=t%26,r=(t-e)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},a.prototype.isubn=function(t){if(n("number"==typeof t),n(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(l/67108864|0),this.words[i+r]=67108863&a}for(;i>26,this.words[i+r]=67108863&a;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},a.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!==(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var s,l=n.length-i.length;if("mod"!==e){(s=new a(null)).length=l+1,s.words=new Array(s.length);for(var c=0;c=0;f--){var h=67108864*(0|n.words[i.length+f])+(0|n.words[i.length+f-1]);for(h=Math.min(h/o|0,67108863),n._ishlnsubmul(i,h,f);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(i,1,f),n.isZero()||(n.negative^=1);s&&(s.words[f]=h)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},a.prototype.divmod=function(t,e,r){return n(!t.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(i=s.div.neg()),"div"!==e&&(o=s.mod.neg(),r&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),r&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new a(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new a(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new a(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,o,s},a.prototype.div=function(t){return this.divmod(t,"div",!1).div},a.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},a.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},a.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},a.prototype.modn=function(t){n(t<=67108863);for(var e=(1<<26)%t,r=0,i=this.length-1;i>=0;i--)r=(e*r+(0|this.words[i]))%t;return r},a.prototype.idivn=function(t){n(t<=67108863);for(var e=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*e;this.words[r]=i/t|0,e=i%t}return this.strip()},a.prototype.divn=function(t){return this.clone().idivn(t)},a.prototype.egcd=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new a(1),o=new a(0),s=new a(0),l=new a(1),c=0;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++c;for(var u=r.clone(),f=e.clone();!e.isZero();){for(var h=0,d=1;0==(e.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(e.iushrn(h);h-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(u),o.isub(f)),i.iushrn(1),o.iushrn(1);for(var p=0,m=1;0==(r.words[0]&m)&&p<26;++p,m<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(u),l.isub(f)),s.iushrn(1),l.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(s),o.isub(l)):(r.isub(e),s.isub(i),l.isub(o))}return{a:s,b:l,gcd:r.iushln(c)}},a.prototype._invmp=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new a(1),s=new a(0),l=r.clone();e.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,u=1;0==(e.words[0]&u)&&c<26;++c,u<<=1);if(c>0)for(e.iushrn(c);c-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var f=0,h=1;0==(r.words[0]&h)&&f<26;++f,h<<=1);if(f>0)for(r.iushrn(f);f-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(r)>=0?(e.isub(r),o.isub(s)):(r.isub(e),s.isub(o))}return(i=0===e.cmpn(1)?o:s).cmpn(0)<0&&i.iadd(t),i},a.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},a.prototype.invm=function(t){return this.egcd(t).a.umod(t)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(t){return this.words[0]&t},a.prototype.bincn=function(t){n("number"==typeof t);var e=t%26,r=(t-e)/26,i=1<>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(t){var e,r=t<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)e=1;else{r&&(t=-t),n(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},a.prototype.gtn=function(t){return 1===this.cmpn(t)},a.prototype.gt=function(t){return 1===this.cmp(t)},a.prototype.gten=function(t){return this.cmpn(t)>=0},a.prototype.gte=function(t){return this.cmp(t)>=0},a.prototype.ltn=function(t){return-1===this.cmpn(t)},a.prototype.lt=function(t){return-1===this.cmp(t)},a.prototype.lten=function(t){return this.cmpn(t)<=0},a.prototype.lte=function(t){return this.cmp(t)<=0},a.prototype.eqn=function(t){return 0===this.cmpn(t)},a.prototype.eq=function(t){return 0===this.cmp(t)},a.red=function(t){return new w(t)},a.prototype.toRed=function(t){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},a.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(t){return this.red=t,this},a.prototype.forceRed=function(t){return n(!this.red,"Already a number in reduction context"),this._forceRed(t)},a.prototype.redAdd=function(t){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},a.prototype.redIAdd=function(t){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},a.prototype.redSub=function(t){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},a.prototype.redISub=function(t){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},a.prototype.redShl=function(t){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},a.prototype.redMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},a.prototype.redIMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},a.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(t){return n(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var v={k256:null,p224:null,p192:null,p25519:null};function g(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function y(){g.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){g.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){g.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){g.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function w(t){if("string"==typeof t){var e=a._prime(t);this.m=e.p,this.prime=e}else n(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function M(t){w.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}g.prototype._tmp=function(){var t=new a(null);return t.words=new Array(Math.ceil(this.n/13)),t},g.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},g.prototype.split=function(t,e){t.iushrn(this.n,0,e)},g.prototype.imulK=function(t){return t.imul(this.k)},i(y,g),y.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},y.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},a._prime=function(t){if(v[t])return v[t];var e;if("k256"===t)e=new y;else if("p224"===t)e=new b;else if("p192"===t)e=new x;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return v[t]=e,e},w.prototype._verify1=function(t){n(0===t.negative,"red works only with positives"),n(t.red,"red works only with red numbers")},w.prototype._verify2=function(t,e){n(0==(t.negative|e.negative),"red works only with positives"),n(t.red&&t.red===e.red,"red works only with red numbers")},w.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},w.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},w.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},w.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},w.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},w.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},w.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},w.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},w.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},w.prototype.isqr=function(t){return this.imul(t,t.clone())},w.prototype.sqr=function(t){return this.mul(t,t)},w.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(n(e%2==1),3===e){var r=this.m.add(new a(1)).iushrn(2);return this.pow(t,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var s=new a(1).toRed(this),l=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new a(2*u*u).toRed(this);0!==this.pow(u,c).cmp(l);)u.redIAdd(l);for(var f=this.pow(u,i),h=this.pow(t,i.addn(1).iushrn(1)),d=this.pow(t,i),p=o;0!==d.cmp(s);){for(var m=d,v=0;0!==m.cmp(s);v++)m=m.redSqr();n(v=0;n--){for(var c=e.words[n],u=l-1;u>=0;u--){var f=c>>u&1;i!==r[0]&&(i=this.sqr(i)),0!==f||0!==o?(o<<=1,o|=f,(4===++s||0===n&&0===u)&&(i=this.mul(i,r[o]),s=0,o=0)):s=0}l=26}return i},w.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},w.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},a.mont=function(t){return new M(t)},i(M,w),M.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},M.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},M.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},M.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new a(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},M.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===e||e,this)},{buffer:82}],74:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i=t.length,a=0;for(e=0;e>>1;if(!(u<=0)){var f,h=i.mallocDouble(2*u*s),d=i.mallocInt32(s);if((s=l(t,u,h,d))>0){if(1===u&&n)a.init(s),f=a.sweepComplete(u,r,0,s,h,d,0,s,h,d);else{var p=i.mallocDouble(2*u*c),m=i.mallocInt32(c);(c=l(e,u,p,m))>0&&(a.init(s+c),f=1===u?a.sweepBipartite(u,r,0,s,h,d,0,c,p,m):o(u,r,n,s,h,d,c,p,m),i.free(p),i.free(m))}i.free(h),i.free(d)}return f}}}function u(t,e){n.push([t,e])}},{"./lib/intersect":77,"./lib/sweep":81,"typedarray-pool":534}],76:[function(t,e,r){"use strict";var n="d",i="ax",a="vv",o="fp",s="es",l="rs",c="re",u="rb",f="ri",h="rp",d="bs",p="be",m="bb",v="bi",g="bp",y="rv",b="Q",x=[n,i,a,l,c,u,f,d,p,m,v];function _(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],_=x.slice();t||_.splice(3,0,o);var w=["function "+e+"("+_.join()+"){"];function M(e,o){var _=function(t,e,r){var o="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),_=["function ",o,"(",x.join(),"){","var ",s,"=2*",n,";"],w="for(var i="+l+","+h+"="+s+"*"+l+";i<"+c+";++i,"+h+"+="+s+"){var x0="+u+"["+i+"+"+h+"],x1="+u+"["+i+"+"+h+"+"+n+"],xi="+f+"[i];",M="for(var j="+d+","+g+"="+s+"*"+d+";j<"+p+";++j,"+g+"+="+s+"){var y0="+m+"["+i+"+"+g+"],"+(r?"y1="+m+"["+i+"+"+g+"+"+n+"],":"")+"yi="+v+"[j];";return t?_.push(w,b,":",M):_.push(M,b,":",w),r?_.push("if(y1"+p+"-"+d+"){"),t?(M(!0,!1),w.push("}else{"),M(!1,!1)):(w.push("if("+o+"){"),M(!0,!0),w.push("}else{"),M(!0,!1),w.push("}}else{if("+o+"){"),M(!1,!0),w.push("}else{"),M(!1,!1),w.push("}")),w.push("}}return "+e);var k=r.join("")+w.join("");return new Function(k)()}r.partial=_(!1),r.full=_(!0)},{}],77:[function(t,e,r){"use strict";e.exports=function(t,e,r,a,u,E,S,L,C){!function(t,e){var r=8*i.log2(e+1)*(t+1)|0,a=i.nextPow2(x*r);w.length0;){var D=(z-=1)*x,I=w[D],R=w[D+1],N=w[D+2],F=w[D+3],j=w[D+4],B=w[D+5],U=z*_,V=M[U],q=M[U+1],H=1&B,G=!!(16&B),Y=u,W=E,X=L,Z=C;if(H&&(Y=L,W=C,X=u,Z=E),!(2&B&&(N=v(t,I,R,N,Y,W,q),R>=N)||4&B&&(R=g(t,I,R,N,Y,W,V))>=N)){var J=N-R,K=j-F;if(G){if(t*J*(J+K)=p0)&&!(p1>=hi)",["p0","p1"]),m=u("lo===p0",["p0"]),v=u("lo>>1,h=2*t,d=f,p=s[h*f+e];for(;c=b?(d=y,p=b):g>=_?(d=v,p=g):(d=x,p=_):b>=_?(d=y,p=b):_>=g?(d=v,p=g):(d=x,p=_);for(var w=h*(u-1),M=h*d,k=0;kr&&i[f+e]>c;--u,f-=o){for(var h=f,d=f+o,p=0;p=0&&i.push("lo=e[k+n]");t.indexOf("hi")>=0&&i.push("hi=e[k+o]");return r.push(n.replace("_",i.join()).replace("$",t)),Function.apply(void 0,r)};var n="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],80:[function(t,e,r){"use strict";e.exports=function(t,e){e<=4*n?i(0,e-1,t):function t(e,r,f){var h=(r-e+1)/6|0,d=e+h,p=r-h,m=e+r>>1,v=m-h,g=m+h,y=d,b=v,x=m,_=g,w=p,M=e+1,k=r-1,A=0;c(y,b,f)&&(A=y,y=b,b=A);c(_,w,f)&&(A=_,_=w,w=A);c(y,x,f)&&(A=y,y=x,x=A);c(b,x,f)&&(A=b,b=x,x=A);c(y,_,f)&&(A=y,y=_,_=A);c(x,_,f)&&(A=x,x=_,_=A);c(b,w,f)&&(A=b,b=w,w=A);c(b,x,f)&&(A=b,b=x,x=A);c(_,w,f)&&(A=_,_=w,w=A);var T=f[2*b];var E=f[2*b+1];var S=f[2*_];var L=f[2*_+1];var C=2*y;var P=2*x;var z=2*w;var O=2*d;var D=2*m;var I=2*p;for(var R=0;R<2;++R){var N=f[C+R],F=f[P+R],j=f[z+R];f[O+R]=N,f[D+R]=F,f[I+R]=j}o(v,e,f);o(g,r,f);for(var B=M;B<=k;++B)if(u(B,T,E,f))B!==M&&a(B,M,f),++M;else if(!u(B,S,L,f))for(;;){if(u(k,S,L,f)){u(k,T,E,f)?(s(B,M,k,f),++M,--k):(a(B,k,f),--k);break}if(--kt;){var c=r[l-2],u=r[l-1];if(cr[e+1])}function u(t,e,r,n){var i=n[t*=2];return i>>1;a(d,E);for(var S=0,L=0,M=0;M=o)p(c,u,L--,C=C-o|0);else if(C>=0)p(s,l,S--,C);else if(C<=-o){C=-C-o|0;for(var P=0;P>>1;a(d,S);for(var L=0,C=0,P=0,k=0;k>1==d[2*k+3]>>1&&(O=2,k+=1),z<0){for(var D=-(z>>1)-1,I=0;I>1)-1;0===O?p(s,l,L--,D):1===O?p(c,u,C--,D):2===O&&p(f,h,P--,D)}}},scanBipartite:function(t,e,r,n,i,c,u,f,h,v,g,y){var b=0,x=2*t,_=e,w=e+t,M=1,k=1;n?k=o:M=o;for(var A=i;A>>1;a(d,L);for(var C=0,A=0;A=o?(z=!n,T-=o):(z=!!n,T-=1),z)m(s,l,C++,T);else{var O=y[T],D=x*T,I=g[D+e+1],R=g[D+e+1+t];t:for(var N=0;N>>1;a(d,M);for(var k=0,b=0;b=o)s[k++]=x-o;else{var T=p[x-=1],E=v*x,S=h[E+e+1],L=h[E+e+1+t];t:for(var C=0;C=0;--C)if(s[C]===x){for(var D=C+1;Da)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return u(t)}return l(t,e,r)}function l(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return B(t)?function(t,e,r){if(e<0||t.byteLength=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|t}function d(t,e){if(s.isBuffer(t))return t.length;if(U(t)||B(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return F(t).length;default:if(n)return N(t).length;e=(""+e).toLowerCase(),n=!0}}function p(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),V(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:v(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):v(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function c(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var u=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){for(var f=!0,h=0;hi&&(n=i):n=i;var a=e.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function M(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function k(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:c>223?3:c>191?2:1;if(i+f<=r)switch(f){case 1:c<128&&(u=c);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&c)<<6|63&a)>127&&(u=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&c)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&c)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,f=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=f}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return S(this,e,r);case"utf8":case"utf-8":return k(this,e,r);case"ascii":return T(this,e,r);case"latin1":case"binary":return E(this,e,r);case"base64":return M(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},s.prototype.compare=function(t,e,r,n,i){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,o=r-e,l=Math.min(a,o),c=this.slice(n,i),u=t.slice(e,r),f=0;f>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return g(this,t,e,r);case"utf8":case"utf-8":return y(this,t,e,r);case"ascii":return b(this,t,e,r);case"latin1":case"binary":return x(this,t,e,r);case"base64":return _(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function T(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",a=e;ar)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,r,n,i,a){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function z(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O(t,e,r,n,a){return e=+e,r>>>=0,a||z(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,a){return e=+e,r>>>=0,a||z(t,0,r,8),i.write(t,e,r,n,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||C(t,e,this.length);for(var n=this[t],i=1,a=0;++a>>=0,e>>>=0,r||C(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||C(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);for(var n=this[t],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||C(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},s.prototype.readInt8=function(t,e){return t>>>=0,e||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||C(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||C(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||C(t,4,this.length),i.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||C(t,4,this.length),i.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||C(t,8,this.length),i.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||C(t,8,this.length),i.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return O(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return O(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(a<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function F(t){return n.toByteArray(function(t){if((t=t.trim().replace(I,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function j(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function B(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function U(t){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)}function V(t){return t!=t}},{"base64-js":84,ieee754:257}],84:[function(t,e,r){"use strict";r.byteLength=function(t){return 3*t.length/4-c(t)},r.toByteArray=function(t){var e,r,n,o,s,l=t.length;o=c(t),s=new a(3*l/4-o),r=o>0?l-4:l;var u=0;for(e=0;e>16&255,s[u++]=n>>8&255,s[u++]=255&n;2===o?(n=i[t.charCodeAt(e)]<<2|i[t.charCodeAt(e+1)]>>4,s[u++]=255&n):1===o&&(n=i[t.charCodeAt(e)]<<10|i[t.charCodeAt(e+1)]<<4|i[t.charCodeAt(e+2)]>>2,s[u++]=n>>8&255,s[u++]=255&n);return s},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,a="",o=[],s=0,l=r-i;sl?l:s+16383));1===i?(e=t[r-1],a+=n[e>>2],a+=n[e<<4&63],a+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],a+=n[e>>10],a+=n[e>>4&63],a+=n[e<<2&63],a+="=");return o.push(a),o.join("")};for(var n=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,l=o.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function u(t,e,r){for(var i,a,o=[],s=e;s>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],85:[function(t,e,r){"use strict";var n=t("./lib/monotone"),i=t("./lib/triangulation"),a=t("./lib/delaunay"),o=t("./lib/filter");function s(t){return[Math.min(t[0],t[1]),Math.max(t[0],t[1])]}function l(t,e){return t[0]-e[0]||t[1]-e[1]}function c(t,e,r){return e in t?t[e]:r}e.exports=function(t,e,r){Array.isArray(e)?(r=r||{},e=e||[]):(r=e||{},e=[]);var u=!!c(r,"delaunay",!0),f=!!c(r,"interior",!0),h=!!c(r,"exterior",!0),d=!!c(r,"infinity",!1);if(!f&&!h||0===t.length)return[];var p=n(t,e);if(u||f!==h||d){for(var m=i(t.length,function(t){return t.map(s).sort(l)}(e)),v=0;v0;){for(var u=r.pop(),s=r.pop(),f=-1,h=-1,l=o[s],p=1;p=0||(e.flip(s,u),i(t,e,r,f,s,h),i(t,e,r,s,h,f),i(t,e,r,h,u,f),i(t,e,r,u,f,h)))}}},{"binary-search-bounds":90,"robust-in-sphere":493}],87:[function(t,e,r){"use strict";var n,i=t("binary-search-bounds");function a(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function o(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}e.exports=function(t,e,r){var n=function(t,e){for(var r=t.cells(),n=r.length,i=0;i0||l.length>0;){for(;s.length>0;){var d=s.pop();if(c[d]!==-i){c[d]=i;u[d];for(var p=0;p<3;++p){var m=h[3*d+p];m>=0&&0===c[m]&&(f[3*d+p]?l.push(m):(s.push(m),c[m]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var g=function(t,e,r){for(var n=0,i=0;i1&&i(r[h[d-2]],r[h[d-1]],a)>0;)t.push([h[d-1],h[d-2],o]),d-=1;h.length=d,h.push(o);var p=u.upperIds;for(d=p.length;d>1&&i(r[p[d-2]],r[p[d-1]],a)<0;)t.push([p[d-2],p[d-1],o]),d-=1;p.length=d,p.push(o)}}function d(t,e){var r;return(r=t.a[0]g[0]&&i.push(new c(g,v,s,f),new c(v,g,o,f))}i.sort(u);for(var y=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),b=[new l([y,1],[y,0],-1,[],[],[],[])],x=[],f=0,_=i.length;f<_;++f){var w=i[f],M=w.type;M===a?h(x,b,t,w.a,w.idx):M===s?p(b,t,w):m(b,t,w)}return x}},{"binary-search-bounds":90,"robust-orientation":495}],89:[function(t,e,r){"use strict";var n=t("binary-search-bounds");function i(t,e){this.stars=t,this.edges=e}e.exports=function(t,e){for(var r=new Array(t),n=0;n=0}}(),a.removeTriangle=function(t,e,r){var n=this.stars;o(n[t],e,r),o(n[e],r,t),o(n[r],t,e)},a.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},a.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){return new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],91:[function(t,e,r){"use strict";e.exports=function(t){for(var e=1,r=1;rr?r:t:te?e:t}},{}],95:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n;if(r){n=e;for(var i=new Array(e.length),a=0;ae[2]?1:0)}function g(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--a){var b=e[u=(E=n[a])[0]],x=b[0],_=b[1],w=t[x],M=t[_];if((w[0]-M[0]||w[1]-M[1])<0){var k=x;x=_,_=k}b[0]=x;var A,T=b[1]=E[1];for(i&&(A=b[2]);a>0&&n[a-1][0]===u;){var E,S=(E=n[--a])[1];i?e.push([T,S,A]):e.push([T,S]),T=S}i?e.push([T,_,A]):e.push([T,_])}return h}(t,e,h,v,r));return g(e,y,r),!!y||(h.length>0||v.length>0)}},{"./lib/rat-seg-intersect":96,"big-rat":57,"big-rat/cmp":55,"big-rat/to-float":69,"box-intersect":75,nextafter:440,"rat-vec":477,"robust-segment-intersect":498,"union-find":535}],96:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var a=s(e,t),f=s(n,r),h=u(a,f);if(0===o(h))return null;var d=s(t,r),p=u(f,d),m=i(p,h),v=c(a,m);return l(t,v)};var n=t("big-rat/mul"),i=t("big-rat/div"),a=t("big-rat/sub"),o=t("big-rat/sign"),s=t("rat-vec/sub"),l=t("rat-vec/add"),c=t("rat-vec/muls");function u(t,e){return a(n(t[0],e[1]),n(t[1],e[0]))}},{"big-rat/div":56,"big-rat/mul":66,"big-rat/sign":67,"big-rat/sub":68,"rat-vec/add":476,"rat-vec/muls":478,"rat-vec/sub":479}],97:[function(t,e,r){"use strict";var n=t("clamp");function i(t,e){null==e&&(e=!0);var r=t[0],i=t[1],a=t[2],o=t[3];return null==o&&(o=e?1:255),e&&(r*=255,i*=255,a*=255,o*=255),16777216*(r=255&n(r,0,255))+((i=255&n(i,0,255))<<16)+((a=255&n(a,0,255))<<8)+(o=255&n(o,0,255))}e.exports=i,e.exports.to=i,e.exports.from=function(t,e){var r=(t=+t)>>>24,n=(16711680&t)>>>16,i=(65280&t)>>>8,a=255&t;return!1===e?[r,n,i,a]:[r/255,n/255,i/255,a/255]}},{clamp:94}],98:[function(t,e,r){"use strict";e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},{}],99:[function(t,e,r){"use strict";var n=t("color-rgba"),i=t("clamp"),a=t("dtype");e.exports=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=a(e),o=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(o.set(t),o);var s="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=null!=t[3]?t[3]:255,s&&(o[0]/=255,o[1]/=255,o[2]/=255,o[3]/=255),o):(t.length&&"string"!=typeof t||((t=n(t))[0]/=255,t[1]/=255,t[2]/=255),s?(o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=null!=t[3]?t[3]:1):(o[0]=i(Math.round(255*t[0]),0,255),o[1]=i(Math.round(255*t[1]),0,255),o[2]=i(Math.round(255*t[2]),0,255),o[3]=null==t[3]?255:i(Math.floor(255*t[3]),0,255)),o)}},{clamp:94,"color-rgba":101,dtype:133}],100:[function(t,e,r){(function(r){"use strict";var n=t("color-name"),i=t("is-plain-obj"),a=t("defined");e.exports=function(t){var e,s,l=[],c=1;if("string"==typeof t)if(n[t])l=n[t].slice(),s="rgb";else if("transparent"===t)c=0,s="rgb",l=[0,0,0];else if(/^#[A-Fa-f0-9]+$/.test(t)){var u=t.slice(1),f=u.length,h=f<=4;c=1,h?(l=[parseInt(u[0]+u[0],16),parseInt(u[1]+u[1],16),parseInt(u[2]+u[2],16)],4===f&&(c=parseInt(u[3]+u[3],16)/255)):(l=[parseInt(u[0]+u[1],16),parseInt(u[2]+u[3],16),parseInt(u[4]+u[5],16)],8===f&&(c=parseInt(u[6]+u[7],16)/255)),l[0]||(l[0]=0),l[1]||(l[1]=0),l[2]||(l[2]=0),s="rgb"}else if(e=/^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(t)){var d=e[1],u=d.replace(/a$/,"");s=u;var f="cmyk"===u?4:"gray"===u?1:3;l=e[2].trim().split(/\s*,\s*/).map(function(t,e){if(/%$/.test(t))return e===f?parseFloat(t)/100:"rgb"===u?255*parseFloat(t)/100:parseFloat(t);if("h"===u[e]){if(/deg$/.test(t))return parseFloat(t);if(void 0!==o[t])return o[t]}return parseFloat(t)}),d===u&&l.push(1),c=void 0===l[f]?1:l[f],l=l.slice(0,f)}else t.length>10&&/[0-9](?:\s|\/)/.test(t)&&(l=t.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),s=t.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof t)s="rgb",l=[t>>>16,(65280&t)>>>8,255&t];else if(i(t)){var p=a(t.r,t.red,t.R,null);null!==p?(s="rgb",l=[p,a(t.g,t.green,t.G),a(t.b,t.blue,t.B)]):(s="hsl",l=[a(t.h,t.hue,t.H),a(t.s,t.saturation,t.S),a(t.l,t.lightness,t.L,t.b,t.brightness)]),c=a(t.a,t.alpha,t.opacity,1),null!=t.opacity&&(c/=100)}else(Array.isArray(t)||r.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(t))&&(l=[t[0],t[1],t[2]],s="rgb",c=4===t.length?t[3]:1);return{space:s,values:l,alpha:c}};var o={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"color-name":98,defined:129,"is-plain-obj":266}],101:[function(t,e,r){"use strict";var n=t("color-parse"),i=t("color-space/hsl"),a=t("clamp");e.exports=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=n(t);return r.space?((e=Array(3))[0]=a(r.values[0],0,255),e[1]=a(r.values[1],0,255),e[2]=a(r.values[2],0,255),"h"===r.space[0]&&(e=i.rgb(e)),e.push(a(r.alpha,0,1)),e):[]}},{clamp:94,"color-parse":100,"color-space/hsl":102}],102:[function(t,e,r){"use strict";var n=t("./rgb");e.exports={name:"hsl",min:[0,0,0],max:[360,100,100],channel:["hue","saturation","lightness"],alias:["HSL"],rgb:function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var c=0;c<3;c++)(n=o+1/3*-(c-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[c]=255*a;return i}},n.hsl=function(t){var e,r,n=t[0]/255,i=t[1]/255,a=t[2]/255,o=Math.min(n,i,a),s=Math.max(n,i,a),l=s-o;return s===o?e=0:n===s?e=(i-a)/l:i===s?e=2+(a-n)/l:a===s&&(e=4+(n-i)/l),(e=Math.min(60*e,360))<0&&(e+=360),r=(o+s)/2,[e,100*(s===o?0:r<=.5?l/(s+o):l/(2-s-o)),100*r]}},{"./rgb":103}],103:[function(t,e,r){"use strict";e.exports={name:"rgb",min:[0,0,0],max:[255,255,255],channel:["red","green","blue"],alias:["RGB"]}},{}],104:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]}},{}],105:[function(t,e,r){"use strict";var n=t("./colorScale"),i=t("lerp");function a(t){return[t[0]/255,t[1]/255,t[2]/255,t[3]]}function o(t){for(var e,r="#",n=0;n<3;++n)r+=("00"+(e=(e=t[n]).toString(16))).substr(e.length);return r}function s(t){return"rgba("+t.join(",")+")"}e.exports=function(t){var e,r,l,c,u,f,h,d,p,m;t||(t={});d=(t.nshades||72)-1,h=t.format||"hex",(f=t.colormap)||(f="jet");if("string"==typeof f){if(f=f.toLowerCase(),!n[f])throw Error(f+" not a supported colorscale");u=n[f]}else{if(!Array.isArray(f))throw Error("unsupported colormap option",f);u=f.slice()}if(u.length>d)throw new Error(f+" map requires nshades to be at least size "+u.length);p=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=u.map(function(t){return Math.round(t.index*d)}),p[0]=Math.min(Math.max(p[0],0),1),p[1]=Math.min(Math.max(p[1],0),1);var v=u.map(function(t,e){var r=u[e].index,n=u[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=p[0]+(p[1]-p[0])*r,n)}),g=[];for(m=0;m0?-1:l(t,e,a)?-1:1:0===s?c>0?1:l(t,e,r)?1:-1:i(c-s)}var h=n(t,e,r);if(h>0)return o>0&&n(t,e,a)>0?1:-1;if(h<0)return o>0||n(t,e,a)>0?1:-1;var d=n(t,e,a);return d>0?1:l(t,e,r)?1:-1};var n=t("robust-orientation"),i=t("signum"),a=t("two-sum"),o=t("robust-product"),s=t("robust-sum");function l(t,e,r){var n=a(t[0],-e[0]),i=a(t[1],-e[1]),l=a(r[0],-e[0]),c=a(r[1],-e[1]),u=s(o(n,l),o(i,c));return u[u.length-1]>=0}},{"robust-orientation":495,"robust-product":496,"robust-sum":500,signum:502,"two-sum":533}],107:[function(t,e,r){e.exports=function(t,e){var r=t.length,a=t.length-e.length;if(a)return a;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:return t[0]+t[1]-e[0]-e[1]||n(t[0],t[1])-n(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=n(t[0],t[1]),c=n(e[0],e[1]);return n(l,t[2])-n(c,e[2])||n(l+t[2],o)-n(c+e[2],s);case 4:var u=t[0],f=t[1],h=t[2],d=t[3],p=e[0],m=e[1],v=e[2],g=e[3];return u+f+h+d-(p+m+v+g)||n(u,f,h,d)-n(p,m,v,g,p)||n(u+f,u+h,u+d,f+h,f+d,h+d)-n(p+m,p+v,p+g,m+v,m+g,v+g)||n(u+f+h,u+f+d,u+h+d,f+h+d)-n(p+m+v,p+m+g,p+v+g,m+v+g);default:for(var y=t.slice().sort(i),b=e.slice().sort(i),x=0;xt[r][0]&&(r=n);return er?[[r],[e]]:[[e]]}},{}],111:[function(t,e,r){"use strict";e.exports=function(t){var e=n(t),r=e.length;if(r<=2)return[];for(var i=new Array(r),a=e[r-1],o=0;o=e[l]&&(s+=1);a[o]=s}}return t}(o,r)}};var n=t("incremental-convex-hull"),i=t("affine-hull")},{"affine-hull":45,"incremental-convex-hull":258}],113:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",CPV:"verde",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai)(?!.*\\brep).*china|^(?=.*peo)(?=.*rep).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COG:"^(?!.*\\bdem)(?!.*\\bd[\\.]?r)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CSK:"czechoslovakia",CZE:"^(?=.*rep).*czech|czechia|bohemia",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bd[\\.]?r|\\bd[\\.]?r.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"(^ireland)|(^republic.*ireland)",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat|people|north|d.*p.*.r).*\\bkorea|dprk|korea.*(d.*p.*r)",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"fed.*micronesia|micronesia.*fed",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",KOR:"^(?!.*d.*p.*r)(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea(?!.*d.*p.*r)",MDA:"moldov|b(a|e)ssarabia",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra",SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"south.africa|s\\\\..?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa|^(?!.*peo)(?=.*rep).*china",TJK:"tajik",THA:"thailand|\\bsiam",MKD:"macedonia|fyrom",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",TZA:"tanzania",USA:"united.?states\\b(?!.*islands)|\\bu\\.?s\\.?a\\.?\\b|^\\s*u\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],114:[function(t,e,r){var n={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function i(t){return(t=Math.round(t))<0?0:t>255?255:t}function a(t){return t<0?0:t>1?1:t}function o(t){return"%"===t[t.length-1]?i(parseFloat(t)/100*255):i(parseInt(t))}function s(t){return"%"===t[t.length-1]?a(parseFloat(t)/100):a(parseFloat(t))}function l(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{r.parseCSSColor=function(t){var e,r=t.replace(/ /g,"").toLowerCase();if(r in n)return n[r].slice();if("#"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var a=r.indexOf("("),c=r.indexOf(")");if(-1!==a&&c+1===r.length){var u=r.substr(0,a),f=r.substr(a+1,c-(a+1)).split(","),h=1;switch(u){case"rgba":if(4!==f.length)return null;h=s(f.pop());case"rgb":return 3!==f.length?null:[o(f[0]),o(f[1]),o(f[2]),h];case"hsla":if(4!==f.length)return null;h=s(f.pop());case"hsl":if(3!==f.length)return null;var d=(parseFloat(f[0])%360+360)%360/360,p=s(f[1]),m=s(f[2]),v=m<=.5?m*(p+1):m+p-m*p,g=2*m-v;return[i(255*l(g,v,d+1/3)),i(255*l(g,v,d)),i(255*l(g,v,d-1/3)),h];default:return null}}return null}}catch(t){}},{}],115:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,c=(1+2*i)*l,u=i*l,f=s*(3-2*i),h=s*o;if(t.length){a||(a=new Array(t.length));for(var d=t.length-1;d>=0;--d)a[d]=c*t[d]+u*e[d]+f*r[d]+h*n[d];return a}return c*t+u*e+f*r+h*n},e.exports.derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,c=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var u=t.length-1;u>=0;--u)a[u]=o*t[u]+s*e[u]+l*r[u]+c*n[u];return a}return o*t+s*e+l*r[u]+c*n}},{}],116:[function(t,e,r){"use strict";var n=t("./lib/thunk.js");e.exports=function(t){var e=new function(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1};e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i0)throw new Error("cwise: pre() block may not reference array args");if(i0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===a)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===a){if(e.indexArgs.push(i),i0)throw new Error("cwise: pre() block may not reference array index");if(i0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===a){if(e.shapeArgs.push(i),ir.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,n(e)}},{"./lib/thunk.js":118}],117:[function(t,e,r){"use strict";var n=t("uniq");function i(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],c=[],u=0,f=0;for(n=0;n0&&l.push("var "+c.join(",")),n=a-1;n>=0;--n)u=t[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",u,"]"].join(""))),l.push("}")}return l.join("\n")}function a(t,e,r){for(var n=t.body,i=[],a=[],o=0;o0&&y.push("shape=SS.slice(0)"),t.indexArgs.length>0){var b=new Array(r);for(l=0;l0&&g.push("var "+y.join(",")),l=0;l3&&g.push(a(t.pre,t,s));var M=a(t.body,t,s),k=function(t){for(var e=0,r=t[0].length;e0,c=[],u=0;u0;){"].join("")),c.push(["if(j",u,"<",s,"){"].join("")),c.push(["s",e[u],"=j",u].join("")),c.push(["j",u,"=0"].join("")),c.push(["}else{s",e[u],"=",s].join("")),c.push(["j",u,"-=",s,"}"].join("")),l&&c.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&g.push(a(t.post,t,s)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+g.join("\n")+"\n----------");var A=[t.funcName||"unnamed","_cwise_loop_",o[0].join("s"),"m",k,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(s)].join("");return new Function(["function ",A,"(",v.join(","),"){",g.join("\n"),"} return ",A].join(""))()}},{uniq:536}],118:[function(t,e,r){"use strict";var n=t("./compile.js");e.exports=function(t){var e=["'use strict'","var CACHED={}"],r=[],i=t.funcName+"_cwise_thunk";e.push(["return function ",i,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],c=[],u=0;u0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),c.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;ue?1:t>=e?0:NaN},r=function(t){var r;return 1===t.length&&(r=t,t=function(t,n){return e(r(t),n)}),{left:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}};var n=r(e),i=n.right,a=n.left;function o(t,e){return[t,e]}var s=function(t){return null===t?NaN:+t},l=function(t,e){var r,n,i=t.length,a=0,o=-1,l=0,c=0;if(null==e)for(;++o1)return c/(a-1)},c=function(t,e){var r=l(t,e);return r?Math.sqrt(r):r},u=function(t,e){var r,n,i,a=t.length,o=-1;if(null==e){for(;++o=r)for(n=i=r;++or&&(n=r),i=r)for(n=i=r;++or&&(n=r),i=0?(a>=g?10:a>=y?5:a>=b?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=g?10:a>=y?5:a>=b?2:1)}function _(t,e,r){var n=Math.abs(e-t)/Math.max(0,r),i=Math.pow(10,Math.floor(Math.log(n)/Math.LN10)),a=n/i;return a>=g?i*=10:a>=y?i*=5:a>=b&&(i*=2),e=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,a=Math.floor(i),o=+r(t[a],a,t);return o+(+r(t[a+1],a+1,t)-o)*(i-a)}},k=function(t,e){var r,n,i=t.length,a=-1;if(null==e){for(;++a=r)for(n=r;++ar&&(n=r)}else for(;++a=r)for(n=r;++ar&&(n=r);return n},A=function(t){if(!(i=t.length))return[];for(var e=-1,r=k(t,T),n=new Array(r);++et?1:e>=t?0:NaN},t.deviation=c,t.extent=u,t.histogram=function(){var t=m,e=u,r=w;function n(n){var a,o,s=n.length,l=new Array(s);for(a=0;af;)h.pop(),--d;var p,m=new Array(d+1);for(a=0;a<=d;++a)(p=m[a]=[]).x0=a>0?h[a-1]:u,p.x1=a=r)for(n=r;++an&&(n=r)}else for(;++a=r)for(n=r;++an&&(n=r);return n},t.mean=function(t,e){var r,n=t.length,i=n,a=-1,o=0;if(null==e)for(;++a=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r},t.min=k,t.pairs=function(t,e){null==e&&(e=o);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r0)return[t];if((n=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++s=l.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,c,f,h=-1,d=n.length,p=l[i++],m=r(),v=a();++hl.length)return r;var i,a=c[n-1];return null!=e&&n>=l.length?i=r.entries():(i=[],r.each(function(e,r){i.push({key:r,values:t(e,n)})})),null!=a?i.sort(function(t,e){return a(t.key,e.key)}):i}(u(t,0,a,o),0)},key:function(t){return l.push(t),s},sortKeys:function(t){return c[l.length-1]=t,s},sortValues:function(e){return t=e,s},rollup:function(t){return e=t,s}}},t.set=c,t.map=r,t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.d3=n.d3||{})},{}],122:[function(t,e,r){var n;n=this,function(t){"use strict";var e=function(t,e,r){t.prototype=e.prototype=r,r.constructor=t};function r(t,e){var r=Object.create(t.prototype);for(var n in e)r[n]=e[n];return r}function n(){}var i="\\s*([+-]?\\d+)\\s*",a="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",o="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",s=/^#([0-9a-f]{3})$/,l=/^#([0-9a-f]{6})$/,c=new RegExp("^rgb\\("+[i,i,i]+"\\)$"),u=new RegExp("^rgb\\("+[o,o,o]+"\\)$"),f=new RegExp("^rgba\\("+[i,i,i,a]+"\\)$"),h=new RegExp("^rgba\\("+[o,o,o,a]+"\\)$"),d=new RegExp("^hsl\\("+[a,o,o]+"\\)$"),p=new RegExp("^hsla\\("+[a,o,o,a]+"\\)$"),m={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};function v(t){var e;return t=(t+"").trim().toLowerCase(),(e=s.exec(t))?new _((e=parseInt(e[1],16))>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):(e=l.exec(t))?g(parseInt(e[1],16)):(e=c.exec(t))?new _(e[1],e[2],e[3],1):(e=u.exec(t))?new _(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=f.exec(t))?y(e[1],e[2],e[3],e[4]):(e=h.exec(t))?y(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=d.exec(t))?w(e[1],e[2]/100,e[3]/100,1):(e=p.exec(t))?w(e[1],e[2]/100,e[3]/100,e[4]):m.hasOwnProperty(t)?g(m[t]):"transparent"===t?new _(NaN,NaN,NaN,0):null}function g(t){return new _(t>>16&255,t>>8&255,255&t,1)}function y(t,e,r,n){return n<=0&&(t=e=r=NaN),new _(t,e,r,n)}function b(t){return t instanceof n||(t=v(t)),t?new _((t=t.rgb()).r,t.g,t.b,t.opacity):new _}function x(t,e,r,n){return 1===arguments.length?b(t):new _(t,e,r,null==n?1:n)}function _(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function w(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new k(t,e,r,n)}function M(t,e,r,i){return 1===arguments.length?function(t){if(t instanceof k)return new k(t.h,t.s,t.l,t.opacity);if(t instanceof n||(t=v(t)),!t)return new k;if(t instanceof k)return t;var e=(t=t.rgb()).r/255,r=t.g/255,i=t.b/255,a=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,l=o-a,c=(o+a)/2;return l?(s=e===o?(r-i)/l+6*(r0&&c<1?0:s,new k(s,l,c,t.opacity)}(t):new k(t,e,r,null==i?1:i)}function k(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function A(t,e,r){return 255*(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)}e(n,v,{displayable:function(){return this.rgb().displayable()},toString:function(){return this.rgb()+""}}),e(_,x,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return 0<=this.r&&this.r<=255&&0<=this.g&&this.g<=255&&0<=this.b&&this.b<=255&&0<=this.opacity&&this.opacity<=1},toString:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}})),e(k,M,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new k(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new k(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new _(A(t>=240?t-240:t+120,i,n),A(t,i,n),A(t<120?t+240:t-120,i,n),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1}}));var T=Math.PI/180,E=180/Math.PI,S=.95047,L=1,C=1.08883,P=4/29,z=6/29,O=3*z*z,D=z*z*z;function I(t){if(t instanceof N)return new N(t.l,t.a,t.b,t.opacity);if(t instanceof q){var e=t.h*T;return new N(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}t instanceof _||(t=b(t));var r=U(t.r),n=U(t.g),i=U(t.b),a=F((.4124564*r+.3575761*n+.1804375*i)/S),o=F((.2126729*r+.7151522*n+.072175*i)/L);return new N(116*o-16,500*(a-o),200*(o-F((.0193339*r+.119192*n+.9503041*i)/C)),t.opacity)}function R(t,e,r,n){return 1===arguments.length?I(t):new N(t,e,r,null==n?1:n)}function N(t,e,r,n){this.l=+t,this.a=+e,this.b=+r,this.opacity=+n}function F(t){return t>D?Math.pow(t,1/3):t/O+P}function j(t){return t>z?t*t*t:O*(t-P)}function B(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function U(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function V(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof q)return new q(t.h,t.c,t.l,t.opacity);t instanceof N||(t=I(t));var e=Math.atan2(t.b,t.a)*E;return new q(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}(t):new q(t,e,r,null==n?1:n)}function q(t,e,r,n){this.h=+t,this.c=+e,this.l=+r,this.opacity=+n}e(N,R,r(n,{brighter:function(t){return new N(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new N(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return t=L*j(t),new _(B(3.2404542*(e=S*j(e))-1.5371385*t-.4985314*(r=C*j(r))),B(-.969266*e+1.8760108*t+.041556*r),B(.0556434*e-.2040259*t+1.0572252*r),this.opacity)}})),e(q,V,r(n,{brighter:function(t){return new q(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new q(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return I(this).rgb()}}));var H=-.14861,G=1.78277,Y=-.29227,W=-.90649,X=1.97294,Z=X*W,J=X*G,K=G*Y-W*H;function Q(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof $)return new $(t.h,t.s,t.l,t.opacity);t instanceof _||(t=b(t));var e=t.r/255,r=t.g/255,n=t.b/255,i=(K*n+Z*e-J*r)/(K+Z-J),a=n-i,o=(X*(r-i)-Y*a)/W,s=Math.sqrt(o*o+a*a)/(X*i*(1-i)),l=s?Math.atan2(o,a)*E-120:NaN;return new $(l<0?l+360:l,s,i,t.opacity)}(t):new $(t,e,r,null==n?1:n)}function $(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}e($,Q,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new $(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new $(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*T,e=+this.l,r=isNaN(this.s)?0:this.s*e*(1-e),n=Math.cos(t),i=Math.sin(t);return new _(255*(e+r*(H*n+G*i)),255*(e+r*(Y*n+W*i)),255*(e+r*(X*n)),this.opacity)}})),t.color=v,t.rgb=x,t.hsl=M,t.lab=R,t.hcl=V,t.cubehelix=Q,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.d3=n.d3||{})},{}],123:[function(t,e,r){var n;n=this,function(t){"use strict";var e={value:function(){}};function r(){for(var t,e=0,r=arguments.length,i={};e=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})),l=-1,c=s.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++l0)for(var r,n,i=new Array(r),a=0;ah+c||nd+c||au.index){var f=h-s.x-s.vx,v=d-s.y-s.vy,g=f*f+v*v;gt.r&&(t.r=t[e].r)}function h(){if(r){var e,i,a=r.length;for(n=new Array(a),e=0;e=c)){(t.data!==r||t.next)&&(0===f&&(p+=(f=o())*f),0===h&&(p+=(h=o())*h),p1?(null==r?u.remove(t):u.set(t,y(r)),e):u.get(t)},find:function(e,r,n){var i,a,o,s,l,c=0,u=t.length;for(null==n?n=1/0:n*=n,c=0;c1?(h.on(t,r),e):h.on(t)}}},t.forceX=function(t){var e,r,n,i=a(.1);function o(t){for(var i,a=0,o=e.length;a=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],s=i>0?t[i-1]:2*a-o,l=i180||r<-180?r-360*Math.round(r/360):r):a(isNaN(t)?e:t)}function l(t){return 1==(t=+t)?c:function(e,r){return r-e?function(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}(e,r,t):a(isNaN(e)?r:e)}}function c(t,e){var r=e-t;return r?o(t,r):a(isNaN(t)?e:t)}var u=function t(r){var n=l(r);function i(t,r){var i=n((t=e.rgb(t)).r,(r=e.rgb(r)).r),a=n(t.g,r.g),o=n(t.b,r.b),s=c(t.opacity,r.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=o(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function f(t){return function(r){var n,i,a=r.length,o=new Array(a),s=new Array(a),l=new Array(a);for(n=0;na&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:v(r,n)})),a=b.lastIndex;return a180?e+=360:e-t>180&&(t+=360),a.push({i:r.push(i(r)+"rotate(",null,n)-2,x:v(t,e)})):e&&r.push(i(r)+"rotate("+e+n)}(a.rotate,o.rotate,s,l),function(t,e,r,a){t!==e?a.push({i:r.push(i(r)+"skewX(",null,n)-2,x:v(t,e)}):e&&r.push(i(r)+"skewX("+e+n)}(a.skewX,o.skewX,s,l),function(t,e,r,n,a,o){if(t!==r||e!==n){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:v(t,r)},{i:s-2,x:v(e,n)})}else 1===r&&1===n||a.push(i(a)+"scale("+r+","+n+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,l),a=o=null,function(t){for(var e,r=-1,n=l.length;++r=(a=(m+g)/2))?m=a:g=a,(u=r>=(o=(v+y)/2))?v=o:y=o,i=d,!(d=d[f=u<<1|c]))return i[f]=p,t;if(s=+t._x.call(null,d.data),l=+t._y.call(null,d.data),e===s&&r===l)return p.next=d,i?i[f]=p:t._root=p,t;do{i=i?i[f]=new Array(4):t._root=new Array(4),(c=e>=(a=(m+g)/2))?m=a:g=a,(u=r>=(o=(v+y)/2))?v=o:y=o}while((f=u<<1|c)==(h=(l>=o)<<1|s>=a));return i[h]=d,i[f]=p,t}var r=function(t,e,r,n,i){this.node=t,this.x0=e,this.y0=r,this.x1=n,this.y1=i};function n(t){return t[0]}function i(t){return t[1]}function a(t,e,r){var a=new o(null==e?n:e,null==r?i:r,NaN,NaN,NaN,NaN);return null==t?a:a.addAll(t)}function o(t,e,r,n,i,a){this._x=t,this._y=e,this._x0=r,this._y0=n,this._x1=i,this._y1=a,this._root=void 0}function s(t){for(var e={data:t.data},r=e;t=t.next;)r=r.next={data:t.data};return e}var l=a.prototype=o.prototype;l.copy=function(){var t,e,r=new o(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root;if(!n)return r;if(!n.length)return r._root=s(n),r;for(t=[{source:n,target:r._root=new Array(4)}];n=t.pop();)for(var i=0;i<4;++i)(e=n.source[i])&&(e.length?t.push({source:e,target:n.target[i]=new Array(4)}):n.target[i]=s(e));return r},l.add=function(t){var r=+this._x.call(null,t),n=+this._y.call(null,t);return e(this.cover(r,n),r,n,t)},l.addAll=function(t){var r,n,i,a,o=t.length,s=new Array(o),l=new Array(o),c=1/0,u=1/0,f=-1/0,h=-1/0;for(n=0;nf&&(f=i),ah&&(h=a));for(ft||t>i||n>e||e>a))return this;var o,s,l=i-r,c=this._root;switch(s=(e<(n+a)/2)<<1|t<(r+i)/2){case 0:do{(o=new Array(4))[s]=c,c=o}while(a=n+(l*=2),t>(i=r+l)||e>a);break;case 1:do{(o=new Array(4))[s]=c,c=o}while(a=n+(l*=2),(r=i-l)>t||e>a);break;case 2:do{(o=new Array(4))[s]=c,c=o}while(n=a-(l*=2),t>(i=r+l)||n>e);break;case 3:do{(o=new Array(4))[s]=c,c=o}while(n=a-(l*=2),(r=i-l)>t||n>e)}this._root&&this._root.length&&(this._root=c)}return this._x0=r,this._y0=n,this._x1=i,this._y1=a,this},l.data=function(){var t=[];return this.visit(function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)}),t},l.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},l.find=function(t,e,n){var i,a,o,s,l,c,u,f=this._x0,h=this._y0,d=this._x1,p=this._y1,m=[],v=this._root;for(v&&m.push(new r(v,f,h,d,p)),null==n?n=1/0:(f=t-n,h=e-n,d=t+n,p=e+n,n*=n);c=m.pop();)if(!(!(v=c.node)||(a=c.x0)>d||(o=c.y0)>p||(s=c.x1)=y)<<1|t>=g)&&(c=m[m.length-1],m[m.length-1]=m[m.length-1-u],m[m.length-1-u]=c)}else{var b=t-+this._x.call(null,v.data),x=e-+this._y.call(null,v.data),_=b*b+x*x;if(_=(s=(p+v)/2))?p=s:v=s,(u=o>=(l=(m+g)/2))?m=l:g=l,e=d,!(d=d[f=u<<1|c]))return this;if(!d.length)break;(e[f+1&3]||e[f+2&3]||e[f+3&3])&&(r=e,h=f)}for(;d.data!==t;)if(n=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,n?(i?n.next=i:delete n.next,this):e?(i?e[f]=i:delete e[f],(d=e[0]||e[1]||e[2]||e[3])&&d===(e[3]||e[2]||e[1]||e[0])&&!d.length&&(r?r[h]=d:this._root=d),this):(this._root=i,this)},l.removeAll=function(t){for(var e=0,r=t.length;e=0&&r._call.call(null,t),r=r._next;--n}function g(){l=(s=u.now())+c,n=i=0;try{v()}finally{n=0,function(){var t,n,i=e,a=1/0;for(;i;)i._call?(a>i._time&&(a=i._time),t=i,i=i._next):(n=i._next,i._next=null,i=t?t._next=n:e=n);r=t,b(a)}(),l=0}}function y(){var t=u.now(),e=t-s;e>o&&(c-=e,s=t)}function b(t){n||(i&&(i=clearTimeout(i)),t-l>24?(t<1/0&&(i=setTimeout(g,t-u.now()-c)),a&&(a=clearInterval(a))):(a||(s=u.now(),a=setInterval(y,o)),n=1,f(g)))}p.prototype=m.prototype={constructor:p,restart:function(t,n,i){if("function"!=typeof t)throw new TypeError("callback is not a function");i=(null==i?h():+i)+(null==n?0:+n),this._next||r===this||(r?r._next=this:e=this,r=this),this._call=t,this._time=i,b()},stop:function(){this._call&&(this._call=null,this._time=1/0,b())}};t.now=h,t.timer=m,t.timerFlush=v,t.timeout=function(t,e,r){var n=new p;return e=null==e?0:+e,n.restart(function(r){n.stop(),t(r+e)},e,r),n},t.interval=function(t,e,r){var n=new p,i=e;return null==e?(n.restart(t,e,r),n):(e=+e,r=null==r?h():+r,n.restart(function a(o){o+=i,n.restart(a,i+=e,r),t(o)},e,r),n)},Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.d3=n.d3||{})},{}],128:[function(t,e,r){!function(){var t={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},i=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(i)try{n(i.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),i)try{i.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,c=s.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){c.call(this,t,e,r+"")},u.setProperty=function(t,e,r){f.call(this,t,e+"",r)}}function h(t,e){return te?1:t>=e?0:NaN}function d(t){return null===t?NaN:+t}function p(t){return!isNaN(t)}function m(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}t.ascending=h,t.descending=function(t,e){return et?1:e>=t?0:NaN},t.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},t.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},t.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=m(h);function g(t){return t.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(t){return m(1===t.length?function(e,r){return h(t(e),r)}:t)},t.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function b(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function x(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):e?a.sort(e):a;for(var l,c,u,f,h=-1,d=a.length,p=i[s++],m=new x;++h=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new C;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(U,"\\$&")};var U=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,V={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function q(t){return V(t,W),t}var H=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},Y=function(t,e){var r=t.matches||t[O(t,"matchesSelector")];return(Y=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(H=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(i.documentElement)};var W=t.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return H(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}W.select=function(t){var e,r,n,i,a=[];t=X(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},W.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each(Q(r,e[r]));return this}return this.each(Q(e,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=h);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(e=e.slice(0,o));var l=pt.get(e);function c(){var t=this[a];t&&(this.removeEventListener(e,t,t.$),delete this[a])}return l&&(e=l,s=vt),o?r?function(){var t=s(r,n(arguments));c.call(this),this.addEventListener(e,this[a]=t,t.$=i),t._=r}:c:r?I:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}t.selection.enter=ft,t.selection.enter.prototype=ht,ht.append=W.append,ht.empty=W.empty,ht.node=W.node,ht.call=W.call,ht.size=W.size,ht.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function zt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Ot(t){return t>1?0:t<-1?At:Math.acos(t)}function Dt(t){return t>1?St:t<-1?-St:Math.asin(t)}function It(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Nt=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],c=e[2],u=s-i,f=l-a,h=u*u+f*f;if(h0&&(e=e.transition().duration(m)),e.call(w.event)}function E(){c&&c.domain(l.range().map(function(t){return(t-h.x)/h.k}).map(l.invert)),f&&f.domain(u.range().map(function(t){return(t-h.y)/h.k}).map(u.invert))}function S(t){v++||t({type:"zoomstart"})}function L(t){E(),t({type:"zoom",scale:h.k,translate:[h.x,h.y]})}function C(t){--v||(t({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,i=t.select(o(e)).on(y,function(){n=1,A(t.mouse(e),a),L(r)}).on(b,function(){i.on(y,null).on(b,null),s(n),C(r)}),a=M(t.mouse(e)),s=bt(e);ss.call(e),S(r)}function z(){var e,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+t.event.changedTouches[0].identifier,l="touchmove"+o,c="touchend"+o,u=[],f=t.select(r),d=bt(r);function p(){var n=t.touches(r);return e=h.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=M(t))}),n}function m(){var e=t.event.target;t.select(e).on(l,v).on(c,y),u.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o1){g=d[0];var b=d[1],x=g[0]-b[0],_=g[1]-b[1];a=x*x+_*_}}function v(){var o,l,c,u,f=t.touches(r);ss.call(r);for(var h=0,d=f.length;h360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Xt?e.l:(e=he((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}qt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,this.l/t)},qt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,t*this.l)},qt.rgb=function(){return Ht(this.h,this.s,this.l)},t.hcl=Gt;var Yt=Gt.prototype=new Ut;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=Lt)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Gt?Wt(t.h,t.c,t.l):he((t=ae(t)).r,t.g,t.b):new Xt(t,e,r)}Yt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Yt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Yt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},t.lab=Xt;var Zt=18,Jt=.95047,Kt=1,Qt=1.08883,$t=Xt.prototype=new Ut;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Jt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*Qt)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Ct,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ue(""+t,ae,Ht):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}$t.brighter=function(t){return new Xt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},$t.darker=function(t){return new Xt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},$t.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ae;var le=ae.prototype=new Ut;function ce(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ue(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(pe(i[0]),pe(i[1]),pe(i[2]))}return(a=me.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function fe(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new Vt(n,i,l)}function he(t,e,r){var n=ne((.4124564*(t=de(t))+.3575761*(e=de(e))+.1804375*(r=de(r)))/Jt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/Qt)))}function de(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,c)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var r=t.event;t.event=e;try{s.progress.call(o,c)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(u=t,o):u},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(t,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),c.open(t,e,!0),null==r||"accept"in l||(l.accept=r+",*/*"),c.setRequestHeader)for(var a in l)c.setRequestHeader(a,l[a]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}me.forEach(function(t,e){me.set(t,oe(e))}),t.functor=ve,t.xhr=ge(P),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,c=0,u=0;function f(){if(c>=l)return o;if(i)return i=!1,a;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Ae,e)),_e=0):(_e=1,Me(Ae))}function Te(){for(var t=Date.now(),e=be;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Ee(){for(var t,e=be,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Se(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Le[8+n/3]};var Ce=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Se(e,r))).toFixed(Math.max(0,Math.min(20,Se(e*(1+1e-15),r))))}});function ze(t){return t+""}var Oe=t.time={},De=Date;function Ie(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ie.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(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Ne(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Qe(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function $e(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ve(n,"0",2)+Ve(i,"0",2)}function ar(t,e,r){Ue.lastIndex=0;var n=Ue.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:P;return function(e){var n=Ce.exec(e),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",c=n[4]||"",u=n[5],f=+n[6],h=n[7],d=n[8],p=n[9],m=1,v="",g="",y=!1,b=!0;switch(d&&(d=+d.substring(1)),(u||"0"===i&&"="===s)&&(u=i="0",s="="),p){case"n":h=!0,p="g";break;case"%":m=100,g="%",p="f";break;case"p":m=100,g="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":b=!1;case"d":y=!0,d=0;break;case"s":m=-1,p="r"}"$"===c&&(v=a[0],g=a[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=Pe.get(p)||ze;var x=u&&h;return function(e){var n=g;if(y&&e%1)return"";var a=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===l?"":l;if(m<0){var c=t.formatPrefix(e,d);e=c.scale(e),n=c.symbol+g}else e*=m;var _,w,M=(e=p(e,d)).lastIndexOf(".");if(M<0){var k=b?e.lastIndexOf("e"):-1;k<0?(_=e,w=""):(_=e.substring(0,k),w=e.substring(k))}else _=e.substring(0,M),w=r+e.substring(M+1);!u&&h&&(_=o(_,1/0));var A=v.length+_.length+w.length+(x?0:a.length),T=A"===s?T+a+e:"^"===s?T.substring(0,A>>=1)+a+e+T.substring(A):a+(x?e:T+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,i=e.time,a=e.periods,o=e.days,s=e.shortDays,l=e.months,c=e.shortMonths;function u(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=c)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in je?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}u.utc=function(t){var e=u(t);function r(t){try{var r=new(De=Ie);return r._=t,e(r)}finally{De=Date}}return r.parse=function(t){try{De=Ie;var r=e.parse(t);return r&&r._}finally{De=Date}},r.toString=e.toString,r},u.multi=u.utc.multi=or;var h=t.map(),d=qe(o),p=He(o),m=qe(s),v=He(s),g=qe(l),y=He(l),b=qe(c),x=He(c);a.forEach(function(t,e){h.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:u(r),d:function(t,e){return Ve(t.getDate(),e,2)},e:function(t,e){return Ve(t.getDate(),e,2)},H:function(t,e){return Ve(t.getHours(),e,2)},I:function(t,e){return Ve(t.getHours()%12||12,e,2)},j:function(t,e){return Ve(1+Oe.dayOfYear(t),e,3)},L:function(t,e){return Ve(t.getMilliseconds(),e,3)},m:function(t,e){return Ve(t.getMonth()+1,e,2)},M:function(t,e){return Ve(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ve(t.getSeconds(),e,2)},U:function(t,e){return Ve(Oe.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ve(Oe.mondayOfYear(t),e,2)},x:u(n),X:u(i),y:function(t,e){return Ve(t.getFullYear()%100,e,2)},Y:function(t,e){return Ve(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){d.lastIndex=0;var n=d.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){b.lastIndex=0;var n=b.exec(e.slice(r));return n?(t.m=x.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return f(t,_.c.toString(),e,r)},d:Qe,e:Qe,H:tr,I:tr,j:$e,L:nr,m:Ke,M:er,p:function(t,e,r){var n=h.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ye,w:Ge,W:We,x:function(t,e,r){return f(t,_.x.toString(),e,r)},X:function(t,e,r){return f(t,_.X.toString(),e,r)},y:Ze,Y:Xe,Z:Je,"%":ar};return u}(e)}};var sr=t.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"]});function lr(){}t.format=sr.numberFormat,t.geo={},lr.prototype={s:0,t:0,add:function(t){ur(t,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new lr;function ur(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function fr(t,e){t&&dr.hasOwnProperty(t.type)&&dr[t.type](t,e)}t.geo.stream=function(t,e){t&&hr.hasOwnProperty(t.type)?hr[t.type](t,e):fr(t,e)};var hr={Feature:function(t,e){fr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),c=Math.sin(e),u=i*c,f=n*l+u*Math.cos(s),h=u*o*Math.sin(s);Sr.add(Math.atan2(h,f)),r=t,n=l,i=c}Lr.point=function(o,s){Lr.point=a,r=(t=o)*Lt,n=Math.cos(s=(e=s)*Lt/2+At/4),i=Math.sin(s)},Lr.lineEnd=function(){a(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function zr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Or(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Dr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Ir(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Nr(t){return[Math.atan2(t[1],t[0]),Dt(t[2])]}function Fr(t,e){return y(t[0]-e[0])Mt?i=90:c<-Mt&&(r=-90),f[0]=e,f[1]=n}};function d(t,a){u.push(f=[e=t,n=t]),ai&&(i=a)}function p(t,o){var s=Pr([t*Lt,o*Lt]);if(l){var c=Or(l,s),u=Or([c[1],-c[0],0],c);Rr(u),u=Nr(u);var f=t-a,h=f>0?1:-1,p=u[0]*Ct*h,m=y(f)>180;if(m^(h*ai&&(i=v);else if(m^(h*a<(p=(p+360)%360-180)&&pi&&(i=o);m?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>a?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else d(t,o);l=s,a=t}function m(){h.point=p}function v(){f[0]=e,f[1]=n,h.point=d,l=null}function g(t,e){if(l){var r=t-a;c+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Lr.point(t,e),p(t,e)}function b(){Lr.lineStart()}function x(){g(o,s),Lr.lineEnd(),y(c)>Mt&&(e=-(n=180)),f[0]=e,f[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function M(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(m[0],m[1])&&(m[1]=d[1]),_(d[0],m[1])>_(m[0],m[1])&&(m[0]=d[0])):s.push(m=d);for(var l,c,d,p=-1/0,m=(o=0,s[c=s.length-1]);o<=c;m=d,++o)d=s[o],(l=_(m[1],d[0]))>p&&(p=l,e=d[0],n=m[1])}return u=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,i]]}}(),t.geo.centroid=function(e){gr=yr=br=xr=_r=wr=Mr=kr=Ar=Tr=Er=0,t.geo.stream(e,jr);var r=Ar,n=Tr,i=Er,a=r*r+n*n+i*i;return a=0;--s)i.point((f=u[s])[0],f[1]);else n(d.x,d.p.x,-1,i);d=d.p}u=(d=d.o).z,p=!p}while(!d.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,M=w*_,k=M>At,A=p*b;if(Sr.add(Math.atan2(A*w*Math.sin(M),m*x+A*Math.cos(M))),a+=k?_+w*Tt:_,k^h>=r^g>=r){var T=Or(Pr(f),Pr(t));Rr(T);var E=Or(i,T);Rr(E);var S=(k^_>=0?-1:1)*Dt(E[2]);(n>S||n===S&&(T[0]||T[1]))&&(o+=k^_>=0?1:-1)}if(!v++)break;h=g,p=b,m=x,f=t}}return(a<-Mt||a0){for(b||(o.polygonStart(),b=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return u}}function Kr(t){return t.length>1}function Qr(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:I,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function $r(t,e){return((t=t.x)[0]<0?t[1]-St-Mt:St-t[1])-((e=e.x)[0]<0?e[1]-St-Mt:St-e[1])}var tn=Jr(Yr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?At:-At,l=y(a-r);y(l-At)0?St:-St),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=At&&(y(r-i)Mt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*St,n.point(-At,i),n.point(0,i),n.point(At,i),n.point(At,0),n.point(At,-i),n.point(0,-i),n.point(-At,-i),n.point(-At,0),n.point(-At,i);else if(y(t[0]-e[0])>Mt){var a=t[0]0)){if(a/=h,h<0){if(a0){if(a>f)return;a>u&&(u=a)}if(a=r-l,h||!(a<0)){if(a/=h,h<0){if(a>f)return;a>u&&(u=a)}else if(h>0){if(a0)){if(a/=d,d<0){if(a0){if(a>f)return;a>u&&(u=a)}if(a=n-c,d||!(a<0)){if(a/=d,d<0){if(a>f)return;a>u&&(u=a)}else if(d>0){if(a0&&(i.a={x:l+u*h,y:c+u*d}),f<1&&(i.b={x:l+f*h,y:c+f*d}),i}}}}}}var rn=1e9;function nn(e,r,n,i){return function(l){var c,u,f,h,d,p,m,v,g,y,b,x=l,_=Qr(),w=en(e,r,n,i),M={point:T,lineStart:function(){M.point=E,u&&u.push(f=[]);y=!0,g=!1,m=v=NaN},lineEnd:function(){c&&(E(h,d),p&&g&&_.rejoin(),c.push(_.buffer()));M.point=T,g&&l.lineEnd()},polygonStart:function(){l=_,c=[],u=[],b=!0},polygonEnd:function(){l=x,c=t.merge(c);var r=function(t){for(var e=0,r=u.length,n=t[1],i=0;in&&zt(c,a,t)>0&&++e:a[1]<=n&&zt(c,a,t)<0&&--e,c=a;return 0!==e}([e,i]),n=b&&r,a=c.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),k(null,null,1,l),l.lineEnd()),a&&Wr(c,o,r,k,l),l.polygonEnd()),c=u=f=null}};function k(t,o,l,c){var u=0,f=0;if(null==t||(u=a(t,l))!==(f=a(o,l))||s(t,o)<0^l>0)do{c.point(0===u||3===u?e:n,u>1?i:r)}while((u=(u+l+4)%4)!==f);else c.point(o[0],o[1])}function A(t,a){return e<=t&&t<=n&&r<=a&&a<=i}function T(t,e){A(t,e)&&l.point(t,e)}function E(t,e){var r=A(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(u&&f.push([t,e]),y)h=t,d=e,p=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&g)l.point(t,e);else{var n={a:{x:m,y:v},b:{x:t,y:e}};w(n)?(g||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),b=!1):r&&(l.lineStart(),l.point(t,e),b=!1)}m=t,v=e,g=r}return M};function a(t,i){return y(t[0]-e)0?0:3:y(t[0]-n)0?2:1:y(t[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=At/3,n=En(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*At/180,r=t[1]*At/180):[e/At*180,r/At*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,Dt((i-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,i,a=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};function c(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}return c.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},c.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),c):a.precision()},c.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),c.translate(a.translate())):a.scale()},c.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),u=+t[0],f=+t[1];return r=a.translate(t).clipExtent([[u-.455*e,f-.238*e],[u+.455*e,f+.238*e]]).stream(l).point,n=o.translate([u-.307*e,f+.201*e]).clipExtent([[u-.425*e+Mt,f+.12*e+Mt],[u-.214*e-Mt,f+.234*e-Mt]]).stream(l).point,i=s.translate([u-.205*e,f+.212*e]).clipExtent([[u-.214*e+Mt,f+.166*e+Mt],[u-.115*e-Mt,f+.234*e-Mt]]).stream(l).point,c},c.scale(1070)};var sn,ln,cn,un,fn,hn,dn={point:I,lineStart:I,lineEnd:I,polygonStart:function(){ln=0,dn.lineStart=pn},polygonEnd:function(){dn.lineStart=dn.lineEnd=dn.point=I,sn+=y(ln/2)}};function pn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}dn.point=function(a,o){dn.point=i,t=r=a,e=n=o},dn.lineEnd=function(){i(t,e)}}var mn={point:function(t,e){tfn&&(fn=t);ehn&&(hn=e)},lineStart:I,lineEnd:I,polygonStart:I,polygonEnd:I};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var gn,yn={point:bn,lineStart:xn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=bn,yn.lineStart=xn,yn.lineEnd=_n}};function bn(t,e){br+=t,xr+=e,++_r}function xn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,Mr+=o*(e+n)/2,kr+=o,bn(t=r,e=n)}yn.point=function(n,i){yn.point=r,bn(t=n,e=i)}}function _n(){yn.point=bn}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,Mr+=o*(n+e)/2,kr+=o,Ar+=(o=n*t-r*e)*(r+t),Tr+=o*(n+e),Er+=3*o,bn(r=t,n=e)}yn.point=function(a,o){yn.point=i,bn(t=r=a,e=n=o)},yn.lineEnd=function(){i(t,e)}}function Mn(t){var e=.5,r=Math.cos(30*Lt),n=16;function i(e){return(n?function(e){var r,i,o,s,l,c,u,f,h,d,p,m,v={point:g,lineStart:y,lineEnd:x,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function g(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){f=NaN,v.point=b,e.lineStart()}function b(r,i){var o=Pr([r,i]),s=t(r,i);a(f,h,u,d,p,m,f=s[0],h=s[1],u=r,d=o[0],p=o[1],m=o[2],n,e),e.point(f,h)}function x(){v.point=g,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=M}function w(t,e){b(r=t,e),i=f,o=h,s=d,l=p,c=m,v.point=b}function M(){a(f,h,u,d,p,m,i,o,r,s,l,c,n,e),v.lineEnd=x,x()}return v}:function(e){return An(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,c,u,f,h,d,p,m,v,g){var b=u-n,x=f-i,_=b*b+x*x;if(_>4*e&&v--){var w=s+d,M=l+p,k=c+m,A=Math.sqrt(w*w+M*M+k*k),T=Math.asin(k/=A),E=y(y(k)-1)e||y((b*P+x*z)/_-.5)>.3||s*d+l*p+c*m0&&16,i):Math.sqrt(e)},i}function kn(t){this.stream=t}function An(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Tn(t){return En(function(){return t})()}function En(e){var r,n,i,a,o,s,l=Mn(function(t,e){return[(t=r(t,e))[0]*c+a,o-t[1]*c]}),c=150,u=480,f=250,h=0,d=0,p=0,m=0,v=0,g=tn,b=P,x=null,_=null;function w(t){return[(t=i(t[0]*Lt,t[1]*Lt))[0]*c+a,o-t[1]*c]}function M(t){return(t=i.invert((t[0]-a)/c,(o-t[1])/c))&&[t[0]*Ct,t[1]*Ct]}function k(){i=Gr(n=Pn(p,m,v),r);var t=r(h,d);return a=u-t[0]*c,o=f+t[1]*c,A()}function A(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Sn(g(n,l(b(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(g=null==t?(x=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>Mt;return Jr(i,function(t){var e,s,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,h){var d,p=[f,h],m=i(f,h),v=r?m?0:o(f,h):m?o(f+(f<0?At:-At),h):0;if(!e&&(c=l=m)&&t.lineStart(),m!==l&&(d=a(e,p),(Fr(e,d)||Fr(p,d))&&(p[0]+=Mt,p[1]+=Mt,m=i(p[0],p[1]))),m!==l)u=0,m?(t.lineStart(),d=a(p,e),t.point(d[0],d[1])):(d=a(e,p),t.point(d[0],d[1]),t.lineEnd()),e=d;else if(n&&e&&r^m){var g;v&s||!(g=a(p,e,!0))||(u=0,r?(t.lineStart(),t.point(g[0][0],g[0][1]),t.point(g[1][0],g[1][1]),t.lineEnd()):(t.point(g[1][0],g[1][1]),t.lineEnd(),t.lineStart(),t.point(g[0][0],g[0][1])))}!m||e&&Fr(e,p)||t.point(p[0],p[1]),e=p,l=m,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return u|(c&&l)<<1}}},In(t,6*Lt),r?[0,-t]:[-At,t-At]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Or(Pr(t),Pr(r)),o=zr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var c=e*o/l,u=-e*s/l,f=Or(i,a),h=Ir(i,c);Dr(h,Ir(a,u));var d=f,p=zr(h,d),m=zr(d,d),v=p*p-m*(zr(h,h)-1);if(!(v<0)){var g=Math.sqrt(v),b=Ir(d,(-p-g)/m);if(Dr(b,h),b=Nr(b),!n)return b;var x,_=t[0],w=r[0],M=t[1],k=r[1];w<_&&(x=_,_=w,w=x);var A=w-_,T=y(A-At)0^b[1]<(y(b[0]-_)At^(_<=b[0]&&b[0]<=w)){var E=Ir(d,(-p+g)/m);return Dr(E,h),[b,Nr(E)]}}}function o(e,n){var i=r?t:At-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((x=+t)*Lt),A()):x},w.clipExtent=function(t){return arguments.length?(_=t,b=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,A()):_},w.scale=function(t){return arguments.length?(c=+t,k()):c},w.translate=function(t){return arguments.length?(u=+t[0],f=+t[1],k()):[u,f]},w.center=function(t){return arguments.length?(h=t[0]%360*Lt,d=t[1]%360*Lt,k()):[h*Ct,d*Ct]},w.rotate=function(t){return arguments.length?(p=t[0]%360*Lt,m=t[1]%360*Lt,v=t.length>2?t[2]%360*Lt:0,k()):[p*Ct,m*Ct,v*Ct]},t.rebind(w,l,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&M,k()}}function Sn(t){return An(t,function(e,r){t.point(e*Lt,r*Lt)})}function Ln(t,e){return[t,e]}function Cn(t,e){return[t>At?t-Tt:t<-At?t+Tt:t,e]}function Pn(t,e,r){return t?e||r?Gr(On(t),Dn(e,r)):On(t):e||r?Dn(e,r):Cn}function zn(t){return function(e,r){return[(e+=t)>At?e-Tt:e<-At?e+Tt:e,r]}}function On(t){var e=zn(t);return e.invert=zn(-t),e}function Dn(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,c=Math.sin(e),u=c*r+s*n;return[Math.atan2(l*i-u*a,s*r-c*n),Dt(u*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,c=Math.sin(e),u=c*i-l*a;return[Math.atan2(l*i+c*a,s*r+u*n),Dt(u*r-s*n)]},o}function In(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Rn(r,i),a=Rn(r,a),(o>0?ia)&&(i+=o*Tt)):(i=t+o*Tt,a=t-.5*l);for(var c,u=i;o>0?u>a:u2?t[2]*Lt:0),e.invert=function(e){return(e=t.invert(e[0]*Lt,e[1]*Lt))[0]*=Ct,e[1]*=Ct,e},e},Cn.invert=Ln,t.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=Pn(-t[0]*Lt,-t[1]*Lt,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Ct,t[1]*=Ct}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=In((t=+r)*Lt,n*Lt),i):t},i.precision=function(r){return arguments.length?(e=In(t*Lt,(n=+r)*Lt),i):n},i.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Lt,i=t[1]*Lt,a=e[1]*Lt,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),c=Math.cos(i),u=Math.sin(a),f=Math.cos(a);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-l*f*s)*r),l*u+c*f*s)},t.geo.graticule=function(){var e,r,n,i,a,o,s,l,c,u,f,h,d=10,p=d,m=90,v=360,g=2.5;function b(){return{type:"MultiLineString",coordinates:x()}}function x(){return t.range(Math.ceil(i/m)*m,n,m).map(f).concat(t.range(Math.ceil(l/v)*v,s,v).map(h)).concat(t.range(Math.ceil(r/d)*d,e,d).filter(function(t){return y(t%m)>Mt}).map(c)).concat(t.range(Math.ceil(o/p)*p,a,p).filter(function(t){return y(t%v)>Mt}).map(u))}return b.lines=function(){return x().map(function(t){return{type:"LineString",coordinates:t}})},b.outline=function(){return{type:"Polygon",coordinates:[f(i).concat(h(s).slice(1),f(n).reverse().slice(1),h(l).reverse().slice(1))]}},b.extent=function(t){return arguments.length?b.majorExtent(t).minorExtent(t):b.minorExtent()},b.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),b.precision(g)):[[i,l],[n,s]]},b.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),o>a&&(t=o,o=a,a=t),b.precision(g)):[[r,o],[e,a]]},b.step=function(t){return arguments.length?b.majorStep(t).minorStep(t):b.minorStep()},b.majorStep=function(t){return arguments.length?(m=+t[0],v=+t[1],b):[m,v]},b.minorStep=function(t){return arguments.length?(d=+t[0],p=+t[1],b):[d,p]},b.precision=function(t){return arguments.length?(g=+t,c=Nn(o,a,90),u=Fn(r,e,g),f=Nn(l,s,90),h=Fn(i,n,g),b):g},b.majorExtent([[-180,-90+Mt],[180,90-Mt]]).minorExtent([[-180,-80-Mt],[180,80+Mt]])},t.geo.greatArc=function(){var e,r,n=jn,i=Bn;function a(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},t.geo.interpolate=function(t,e){return r=t[0]*Lt,n=t[1]*Lt,i=e[0]*Lt,a=e[1]*Lt,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),c=Math.sin(a),u=o*Math.cos(r),f=o*Math.sin(r),h=l*Math.cos(i),d=l*Math.sin(i),p=2*Math.asin(Math.sqrt(Rt(a-n)+o*l*Rt(i-r))),m=1/Math.sin(p),(v=p?function(t){var e=Math.sin(t*=p)*m,r=Math.sin(p-t)*m,n=r*u+e*h,i=r*f+e*d,a=r*s+e*c;return[Math.atan2(i,n)*Ct,Math.atan2(a,Math.sqrt(n*n+i*i))*Ct]}:function(){return[r*Ct,n*Ct]}).distance=p,v;var r,n,i,a,o,s,l,c,u,f,h,d,p,m,v},t.geo.length=function(e){return gn=0,t.geo.stream(e,Un),gn};var Un={sphere:I,point:I,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Lt),o=Math.cos(i),s=y((n*=Lt)-t),l=Math.cos(s);gn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Un.point=function(i,a){t=i*Lt,e=Math.sin(a*=Lt),r=Math.cos(a),Un.point=n},Un.lineEnd=function(){Un.point=Un.lineEnd=I}},lineEnd:I,polygonStart:I,polygonEnd:I};function Vn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var qn=Vn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return Tn(qn)}).raw=qn;var Hn=Vn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(At/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Xn;function o(t,e){a>0?e<-St+Mt&&(e=-St+Mt):e>St-Mt&&(e=St-Mt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=Pt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-St]},o}function Yn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)1&&zt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return Tn(Kn)}).raw=Kn,Qn.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-St]},(t.geo.transverseMercator=function(){var t=Zn(Qn),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=Qn,t.geom={},t.geom.hull=function(t){var e=$n,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)d.push(t[s[c[n]][2]]);for(n=+f;nMt)s=s.L;else{if(!((i=a-bi(s,o))>Mt)){n>-Mt?(e=s.P,r=s):i>-Mt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=pi(t);if(ci.insert(e,l),e||r){if(e===r)return Mi(e),r=pi(e.site),ci.insert(l,r),l.edge=r.edge=Ti(e.site,l.site),wi(e),void wi(r);if(r){Mi(e),Mi(r);var c=e.site,u=c.x,f=c.y,h=t.x-u,d=t.y-f,p=r.site,m=p.x-u,v=p.y-f,g=2*(h*v-d*m),y=h*h+d*d,b=m*m+v*v,x={x:(v*y-d*b)/g+u,y:(h*b-m*y)/g+f};Ei(r.edge,c,p,x),l.edge=Ti(c,t,null,x),r.edge=Ti(t,p,null,x),wi(e),wi(r)}else l.edge=Ti(e.site,l.site)}}function yi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,c=l-e;if(!c)return s;var u=s-n,f=1/a-1/c,h=u/c;return f?(-h+Math.sqrt(h*h-2*f*(u*u/(-2*c)-l+c/2+i-a/2)))/f+n:(n+s)/2}function bi(t,e){var r=t.N;if(r)return yi(r,e);var n=t.site;return n.y===e?n.x:1/0}function xi(t){this.site=t,this.edges=[]}function _i(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,c=n.y-s,u=a.x-o,f=2*(l*(v=a.y-s)-c*u);if(!(f>=-kt)){var h=l*l+c*c,d=u*u+v*v,p=(v*h-c*d)/f,m=(l*d-u*h)/f,v=m+s,g=di.pop()||new function(){Ci(this),this.x=this.y=this.arc=this.site=this.cy=null};g.arc=t,g.site=i,g.x=p+o,g.y=v+Math.sqrt(p*p+m*m),g.cy=v,t.circle=g;for(var y=null,b=fi._;b;)if(g.y=s)return;if(h>p){if(a){if(a.y>=c)return}else a={x:v,y:l};r={x:v,y:c}}else{if(a){if(a.y1)if(h>p){if(a){if(a.y>=c)return}else a={x:(l-i)/n,y:l};r={x:(c-i)/n,y:c}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xMt||y(i-r)>Mt)&&(s.splice(o,0,new Si((g=a.site,b=u,x=y(n-f)Mt?{x:f,y:y(e-f)Mt?{x:y(r-p)Mt?{x:h,y:y(e-h)Mt?{x:y(r-d)=r&&c.x<=i&&c.y>=n&&c.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/Mt)*Mt,y:Math.round(i(t,e)/Mt)*Mt,i:e}})}return o.links=function(t){return Di(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Di(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,c=r.edges.sort(_i),u=-1,f=c.length,h=c[f-1].edge,d=h.l===l?h.r:h.l;++ua&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Ui(r,n)})),a=Hi.lastIndex;return am&&(m=l.x),l.y>v&&(v=l.y),c.push(l.x),u.push(l.y);else for(f=0;fm&&(m=x),_>v&&(v=_),c.push(x),u.push(_)}var w=m-d,M=v-p;function k(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,c=t.y;if(null!=l)if(y(l-r)+y(c-n)<.01)A(t,e,r,n,i,a,o,s);else{var u=t.point;t.x=t.y=t.point=null,A(t,u,l,c,i,a,o,s),A(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else A(t,e,r,n,i,a,o,s)}function A(t,e,r,n,i,a,o,s){var l=.5*(i+o),c=.5*(a+s),u=r>=l,f=n>=c,h=f<<1|u;t.leaf=!1,t=t.nodes[h]||(t.nodes[h]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){k(T,t,+g(t,++f),+b(t,f),d,p,m,v)}}),u?i=l:o=l,f?a=c:s=c,k(t,e,r,n,i,a,o,s)}w>M?v=p+w:m=d+M;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){k(T,t,+g(t,++f),+b(t,f),d,p,m,v)}};if(T.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),c=r.nodes;c[0]&&t(e,c[0],n,i,s,l),c[1]&&t(e,c[1],s,i,a,l),c[2]&&t(e,c[2],n,l,s,o),c[3]&&t(e,c[3],s,l,a,o)}}(t,T,d,p,m,v)},T.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(c,u,f,h,d){if(!(u>a||f>o||h=_)<<1|e>=x,M=w+4;w=0&&!(n=t.interpolators[i](e,r)););return n}function Yi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*St)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Xi.get(i)||Wi,a=Zi.get(a)||P,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,i=e.c,a=e.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,i+s*t,a+l*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,i=e.s,a=e.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ht(n+o*t,i+s*t,a+l*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,i=e.a,a=e.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},t.interpolateRound=aa,t.transform=function(e){var r=i.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ca)})(e)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ca={a:1,b:0,c:0,d:1,e:0,f:0};function ua(t){return t.length?t.pop()+",":""}function fa(e,r){var n=[],i=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ua(r)+"rotate(",null,")")-2,x:Ui(t,e)})):e&&r.push(ua(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ua(r)+"skewX(",null,")")-2,x:Ui(t,e)}):e&&r.push(ua(r)+"skewX("+e+")")}(e.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ua(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ua(r)+"scale("+e+")")}(e.scale,r.scale,n,i),e=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,l.end({type:"end",alpha:n=0})):t>0&&(l.start({type:"start",alpha:n=t}),e=ke(s.tick)),s):n},s.start=function(){var t,e,r,n=g.length,l=y.length,u=c[0],p=c[1];for(t=0;t=0;)r.push(i[n])}function Aa(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(u=c[l]),u.parent=a,u.depth=a.depth+1;r&&(a.value=0),a.children=c}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Aa(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}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&&(ka(t,function(t){t.children&&(t.value=0)}),Aa(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},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var i=e.call(this,t,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,c=-1;for(n=e.value?n/e.value:0;++cs&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function ja(t){return t.reduce(Ba,0)}function Ba(t,e){return t+e[1]}function Ua(t,e){return Va(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Va(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function qa(e){return[t.min(e),t.max(e)]}function Ha(t,e){return t.value-e.value}function Ga(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ya(t,e){t._pack_next=e,e._pack_prev=t}function Wa(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Xa(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,c=1/0,u=-1/0,f=1/0,h=-1/0;if(e.forEach(Za),(r=e[0]).x=-r.r,r.y=0,b(r),l>1&&((n=e[1]).x=n.r,n.y=0,b(n),l>2))for(Ka(r,n,i=e[2]),b(i),Ga(r,i),r._pack_prev=i,Ga(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=f[0]&&l<=f[1]&&((s=c[t.bisect(h,l,1,p)-1]).y+=m,s.push(a[o]));return c}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Va(e,t)}:ve(t),a):i},a.frequency=function(t){return arguments.length?(e=!!t,a):e},a},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Ha),n=0,i=[1,1];function a(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],c=i[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,Aa(s,function(t){t.r=+u(t.value)}),Aa(s,Xa),n){var f=n*(e?1:Math.max(2*s.r/l,2*s.r/c))/2;Aa(s,function(t){t.r+=f}),Aa(s,Xa),Aa(s,function(t){t.r-=f})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++od.x&&(d=t),t.depth>p.depth&&(p=t)});var m=r(h,d)/2-h.x,v=n[0]/(d.x+r(d,h)/2+m),g=n[1]/(p.depth||1);ka(u,function(t){t.x=(t.x+m)*v,t.y=t.depth*g})}return c}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],c=a.m,u=o.m,f=s.m,h=l.m;s=to(s),a=$a(a),s&&a;)l=$a(l),(o=to(o)).a=t,(i=s.z+f-a.z-c+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),c+=i,u+=i),f+=s.m,c+=a.m,h+=l.m,u+=o.m;s&&!to(o)&&(o.t=s,o.m+=f-u),a&&!$a(l)&&(l.t=a,l.m+=c-h,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},Ma(a,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=Qa,n=[1,1],i=!1;function a(a,o){var s,l=e.call(this,a,o),c=l[0],u=0;Aa(c,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=s?u+=r(e,s):0,e.y=0,s=e)});var f=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(c),h=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(c),d=f.x-r(f,h)/2,p=h.x+r(h,f)/2;return Aa(c,i?function(t){t.x=(t.x-c.x)*n[0],t.y=(c.y-t.y)*n[1]}:function(t){t.x=(t.x-d)/(p-d)*n[0],t.y=(1-(c.y?t.y/c.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},Ma(a,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",c=.5*(1+Math.sqrt(5));function u(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=c[i-1]),s.area+=r.area,"squarify"!==l||(n=d(s,m))<=h?(c.pop(),h=n):(s.area-=s.pop().area,p(s,m,a,!1),m=Math.min(a.dx,a.dy),s.length=s.area=0,h=1/0);s.length&&(p(s,m,a,!0),s.length=s.area=0),e.forEach(f)}}function h(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(u(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(p(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(h)}}function d(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*c/n,n/(e*a*c)):1/0}function p(t,e,r,i){var a,o=-1,s=t.length,l=r.x,c=r.y,u=e?n(t.area/e):0;if(e==r.dx){for((i||u>r.dy)&&(u=r.dy);++or.dx)&&(u=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?fo:so,s=i?da:ha;return a=t(e,r,s,n),o=t(r,e,s,Gi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return vo(e,t)};l.tickFormat=function(t,r){return go(e,t,r)};l.nice=function(t){return po(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Gi,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function bo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:_o);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],c=Math.floor(o(r)),u=Math.ceil(o(l)),f=n%1?2:n;if(isFinite(u-c)){if(i){for(;c0;h--)e.push(s(c)*h);for(c=0;e[c]l;u--);e=e.slice(c,u)}return e};l.tickFormat=function(e,r){if(!arguments.length)return xo;arguments.length<2?r=xo:"function"!=typeof r&&(r=t.format(r));var i=Math.max(1,n*e/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],tf?0:1;if(c=Et)return l(c,d)+(s?l(s,1-d):"")+"Z";var p,m,v,g,y,b,x,_,w,M,k,A,T=0,E=0,S=[];if((g=(+o.apply(this,arguments)||0)/2)&&(v=n===So?Math.sqrt(s*s+c*c):+n.apply(this,arguments),d||(E*=-1),c&&(E=Dt(v/c*Math.sin(g))),s&&(T=Dt(v/s*Math.sin(g)))),c){y=c*Math.cos(u+E),b=c*Math.sin(u+E),x=c*Math.cos(f-E),_=c*Math.sin(f-E);var L=Math.abs(f-u-2*E)<=At?0:1;if(E&&Do(y,b,x,_)===d^L){var C=(u+f)/2;y=c*Math.cos(C),b=c*Math.sin(C),x=_=null}}else y=b=0;if(s){w=s*Math.cos(f-T),M=s*Math.sin(f-T),k=s*Math.cos(u+T),A=s*Math.sin(u+T);var P=Math.abs(u-f+2*T)<=At?0:1;if(T&&Do(w,M,k,A)===1-d^P){var z=(u+f)/2;w=s*Math.cos(z),M=s*Math.sin(z),k=A=null}}else w=M=0;if(h>Mt&&(p=Math.min(Math.abs(c-s)/2,+r.apply(this,arguments)))>.001){m=s0?0:1}function Io(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,c=-s*a,u=t[0]+l,f=t[1]+c,h=e[0]+l,d=e[1]+c,p=(u+h)/2,m=(f+d)/2,v=h-u,g=d-f,y=v*v+g*g,b=r-n,x=u*d-h*f,_=(g<0?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*g-v*_)/y,M=(-x*v-g*_)/y,k=(x*g+v*_)/y,A=(-x*v+g*_)/y,T=w-p,E=M-m,S=k-p,L=A-m;return T*T+E*E>S*S+L*L&&(w=k,M=A),[[w-l,M-c],[w*r/b,M*r/b]]}function Ro(t){var e=$n,r=ti,n=Yr,i=Fo,a=i.key,o=.7;function s(a){var s,l=[],c=[],u=-1,f=a.length,h=ve(e),d=ve(r);function p(){l.push("M",i(t(c),o))}for(;++u1&&i.push("H",n[0]);return i.join("")},"step-before":Bo,"step-after":Uo,basis:Ho,"basis-open":function(t){if(t.length<4)return Fo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Go(Xo,a)+","+Go(Xo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Fo(t){return t.length>1?t.join("L"):t+"Z"}function jo(t){return t.join("L")+"Z"}function Bo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var c=2;cAt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},t.svg.diagonal=function(){var t=jn,e=Bn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=ts,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-St;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var is=t.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*Lt);W.transition=function(t){for(var e,r,n=us||++ds,i=vs(t),a=[],o=fs||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)c[--h].call(t,o);if(a>=1)return f.event&&f.event.end.call(t,t.__data__,e),--u.count?delete u[n]:delete t[r],1}f||(a=i.time,o=ke(function(t){var e=f.delay;if(o.t=e+a,e<=t)return h(t-e);o.c=h},0,a),f=u[n]={tween:new x,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++u.count)}hs.call=W.call,hs.empty=W.empty,hs.node=W.node,hs.size=W.size,t.transition=function(e,r){return e&&e.transition?us?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=hs,hs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=X(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function m(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var f,v,g=this,y=t.select(t.event.target),b=n.of(g,arguments),x=t.select(g),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,M=!/^(e|w)$/.test(_)&&a,k=y.classed("extent"),A=bt(g),T=t.mouse(g),E=t.select(o(g)).on("keydown.brush",function(){32==t.event.keyCode&&(k||(f=null,T[0]-=s[1],T[1]-=l[1],k=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==k&&(T[0]+=s[1],T[1]+=l[1],k=0,F())});if(t.event.changedTouches?E.on("touchmove.brush",C).on("touchend.brush",z):E.on("mousemove.brush",C).on("mouseup.brush",z),x.interrupt().selectAll("*").interrupt(),k)T[0]=s[0]-T[0],T[1]=l[0]-T[1];else if(_){var S=+/w$/.test(_),L=+/^n/.test(_);v=[s[1-S]-T[0],l[1-L]-T[1]],T[0]=s[S],T[1]=l[L]}else t.event.altKey&&(f=T.slice());function C(){var e=t.mouse(g),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),k||(t.event.altKey?(f||(f=[(s[0]+s[1])/2,(l[0]+l[1])/2]),T[0]=s[+(e[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=Ls(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Ls(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Ls(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Ss(e.copy(),r,n)},ho(i,e)}function Ls(t){return new Date(t)}ks.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Es:Ts,Es.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Es.toString=Ts.toString,Oe.second=Ne(function(t){return new De(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Oe.seconds=Oe.second.range,Oe.seconds.utc=Oe.second.utc.range,Oe.minute=Ne(function(t){return new De(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Oe.minutes=Oe.minute.range,Oe.minutes.utc=Oe.minute.utc.range,Oe.hour=Ne(function(t){var e=t.getTimezoneOffset()/60;return new De(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Oe.hours=Oe.hour.range,Oe.hours.utc=Oe.hour.utc.range,Oe.month=Ne(function(t){return(t=Oe.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Oe.months=Oe.month.range,Oe.months.utc=Oe.month.utc.range;var Cs=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ps=[[Oe.second,1],[Oe.second,5],[Oe.second,15],[Oe.second,30],[Oe.minute,1],[Oe.minute,5],[Oe.minute,15],[Oe.minute,30],[Oe.hour,1],[Oe.hour,3],[Oe.hour,6],[Oe.hour,12],[Oe.day,1],[Oe.day,2],[Oe.week,1],[Oe.month,1],[Oe.month,3],[Oe.year,1]],zs=ks.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Yr]]),Os={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Ls)},floor:P,ceil:P};Ps.year=Oe.year,Oe.scale=function(){return Ss(t.scale.linear(),Ps,zs)};var Ds=Ps.map(function(t){return[t[0].utc,t[1]]}),Is=As.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Yr]]);function Rs(t){return JSON.parse(t.responseText)}function Ns(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Ds.year=Oe.year.utc,Oe.scale.utc=function(){return Ss(t.scale.linear(),Ds,Is)},t.text=ge(function(t){return t.responseText}),t.json=function(t,e){return ye(t,"application/json",Rs,e)},t.html=function(t,e){return ye(t,"text/html",Ns,e)},t.xml=ge(function(t){return t.responseXML}),"object"==typeof e&&e.exports?e.exports=t:this.d3=t}()},{}],129:[function(t,e,r){e.exports=function(){for(var t=0;t=2)return!1;t[r]=n}return!0}):_.filter(function(t){for(var e=0;e<=s;++e){var r=g[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&s)for(var u=0;u<_.length;++u){var x=_[u],h=x[0];x[0]=x[1],x[1]=h}return _}},{"incremental-convex-hull":258,uniq:536}],131:[function(t,e,r){(function(t){var r=!1;if("undefined"!=typeof Float64Array){var n=new Float64Array(1),i=new Uint32Array(n.buffer);if(n[0]=1,r=!0,1072693248===i[1]){e.exports=function(t){return n[0]=t,[i[0],i[1]]},e.exports.pack=function(t,e){return i[0]=t,i[1]=e,n[0]},e.exports.lo=function(t){return n[0]=t,i[0]},e.exports.hi=function(t){return n[0]=t,i[1]}}else if(1072693248===i[0]){e.exports=function(t){return n[0]=t,[i[1],i[0]]},e.exports.pack=function(t,e){return i[1]=t,i[0]=e,n[0]},e.exports.lo=function(t){return n[0]=t,i[1]},e.exports.hi=function(t){return n[0]=t,i[0]}}else r=!1}if(!r){var a=new t(8);e.exports=function(t){return a.writeDoubleLE(t,0,!0),[a.readUInt32LE(0,!0),a.readUInt32LE(4,!0)]},e.exports.pack=function(t,e){return a.writeUInt32LE(t,0,!0),a.writeUInt32LE(e,4,!0),a.readDoubleLE(0,!0)},e.exports.lo=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(0,!0)},e.exports.hi=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(4,!0)}}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){return(e.exports.hi(t)<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){return!(2146435072&e.exports.hi(t))}}).call(this,t("buffer").Buffer)},{buffer:83}],132:[function(t,e,r){var n=t("abs-svg-path"),i=t("normalize-svg-path"),a={M:"moveTo",C:"bezierCurveTo"};e.exports=function(t,e){t.beginPath(),i(n(e)).forEach(function(e){var r=e[0],n=e.slice(1);t[a[r]].apply(t,n)}),t.closePath()}},{"abs-svg-path":43,"normalize-svg-path":441}],133:[function(t,e,r){e.exports=function(t){switch(t){case"int8":return Int8Array;case"int16":return Int16Array;case"int32":return Int32Array;case"uint8":return Uint8Array;case"uint16":return Uint16Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;case"array":return Array;case"uint8_clamped":return Uint8ClampedArray}}},{}],134:[function(t,e,r){"use strict";e.exports=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n80*r){n=l=t[0],s=c=t[1];for(var x=r;xl&&(l=u),d>c&&(c=d);m=0!==(m=Math.max(l-n,c-s))?1/m:0}return o(y,b,r,n,s,m),b}function i(t,e,r,n,i){var a,o;if(i===A(t,e,r,n)>0)for(a=e;a=e;a-=n)o=w(a,t[a],t[a+1],o);return o&&y(o,o.next)&&(M(o),o=o.next),o}function a(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!y(n,n.next)&&0!==g(n.prev,n,n.next))n=n.next;else{if(M(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function o(t,e,r,n,i,f,h){if(t){!h&&f&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=d(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,c=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,c*=2}while(o>1)}(i)}(t,n,i,f);for(var p,m,v=t;t.prev!==t.next;)if(p=t.prev,m=t.next,f?l(t,n,i,f):s(t))e.push(p.i/r),e.push(t.i/r),e.push(m.i/r),M(t),t=m.next,v=m.next;else if((t=m)===v){h?1===h?o(t=c(t,e,r),e,r,n,i,f,2):2===h&&u(t,e,r,n,i,f):o(a(t),e,r,n,i,f,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(g(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(m(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&g(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,a=t,o=t.next;if(g(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,f=d(s,l,e,r,n),h=d(c,u,e,r,n),p=t.prevZ,v=t.nextZ;p&&p.z>=f&&v&&v.z<=h;){if(p!==t.prev&&p!==t.next&&m(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&g(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,v!==t.prev&&v!==t.next&&m(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&g(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;p&&p.z>=f;){if(p!==t.prev&&p!==t.next&&m(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&g(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;v&&v.z<=h;){if(v!==t.prev&&v!==t.next&&m(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&g(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function c(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!y(i,a)&&b(i,n,n.next,a)&&x(i,a)&&x(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),M(n),M(n.next),n=t=a),n=n.next}while(n!==t);return n}function u(t,e,r,n,i,s){var l=t;do{for(var c=l.next.next;c!==l.prev;){if(l.i!==c.i&&v(l,c)){var u=_(l,c);return l=a(l,l.next),u=a(u,u.next),o(l,e,r,n,i,s),void o(u,e,r,n,i,s)}c=c.next}l=l.next}while(l!==t)}function f(t,e){return t.x-e.x}function h(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=u&&i!==n.x&&m(ar.x)&&x(n,t)&&(r=n,h=l),n=n.next;return r}(t,e)){var r=_(e,t);a(r,r.next)}}function d(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function p(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&b(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&x(t,e)&&x(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function g(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function b(t,e,r,n){return!!(y(t,e)&&y(r,n)||y(t,n)&&y(r,e))||g(t,e,r)>0!=g(t,e,n)>0&&g(r,n,t)>0!=g(r,n,e)>0}function x(t,e){return g(t.prev,t,t.next)<0?g(t,e,t.next)>=0&&g(t,t.prev,e)>=0:g(t,e,t.prev)<0||g(t,t.next,e)<0}function _(t,e){var r=new k(t.i,t.x,t.y),n=new k(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function w(t,e,r,n){var i=new k(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function M(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function k(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],136:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var i=0;i0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){if(!i(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var r,n,o,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(o=(r=this._events[t]).length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(a(r)){for(s=o;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],139:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]}},{}],140:[function(t,e,r){"use strict";e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1}},{}],141:[function(t,e,r){"use strict";e.exports=function(t){return new Function("f","var p = (f && f.properties || {}); return "+i(t))};var n=["Unknown","Point","LineString","Polygon"];function i(t){if(!t)return"true";var e=t[0];return t.length<=1?"any"===e?"false":"true":"("+("=="===e?o(t[1],t[2],"===",!1):"!="===e?o(t[1],t[2],"!==",!1):"<"===e||">"===e||"<="===e||">="===e?o(t[1],t[2],e,!0):"any"===e?s(t.slice(1),"||"):"all"===e?s(t.slice(1),"&&"):"none"===e?u(s(t.slice(1),"||")):"in"===e?l(t[1],t.slice(2)):"!in"===e?u(l(t[1],t.slice(2))):"has"===e?c(t[1]):"!has"===e?u(c([t[1]])):"true")+")"}function a(t){return"$type"===t?"f.type":"$id"===t?"f.id":"p["+JSON.stringify(t)+"]"}function o(t,e,r,i){var o=a(t),s="$type"===t?n.indexOf(e):JSON.stringify(e);return(i?"typeof "+o+"=== typeof "+s+"&&":"")+o+r+s}function s(t,e){return t.map(i).join(e)}function l(t,e){"$type"===t&&(e=e.map(function(t){return n.indexOf(t)}));var r=JSON.stringify(e.sort(f)),i=a(t);return e.length<=200?r+".indexOf("+i+") !== -1":"function(v, a, i, j) {while (i <= j) { var m = (i + j) >> 1; if (a[m] === v) return true; if (a[m] > v) j = m - 1; else i = m + 1;}return false; }("+i+", "+r+",0,"+(e.length-1)+")"}function c(t){return JSON.stringify(t)+" in p"}function u(t){return"!("+t+")"}function f(t,e){return te?1:0}},{}],142:[function(t,e,r){"use strict";e.exports=function(t,e,r){switch(arguments.length){case 0:return new o([0],[0],0);case 1:if("number"==typeof t){var n=l(t);return new o(n,n,0)}return new o(t,l(t.length),0);case 2:if("number"==typeof e){var n=l(t.length);return new o(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new o(t,e,r)}};var n=t("cubic-hermite"),i=t("binary-search-bounds");function a(t,e,r){return Math.min(e,Math.max(t,r))}function o(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n=r-1){h=l.length-1;var p=t-e[r-1];for(d=0;d=r-1)for(var u=s.length-1,f=(e[r-1],0);f=0;--r)if(t[--e])return!1;return!0},s.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t0;--f)n.push(a(l[f-1],c[f-1],arguments[f])),i.push(0)}},s.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t1e-6?1/s:0;this._time.push(t);for(var h=r;h>0;--h){var d=a(c[h-1],u[h-1],arguments[h]);n.push(d),i.push((d-n[o++])*f)}}},s.set=function(t){var e=this.dimension;if(!(t0;--l)r.push(a(o[l-1],s[l-1],arguments[l])),n.push(0)}},s.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,o=n.length-this.dimension,s=this.bounds,l=s[0],c=s[1],u=t-e,f=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var d=arguments[h];n.push(a(l[h-1],c[h-1],n[o++]+d)),i.push(d*f)}}},s.idle=function(t){var e=this.lastT();if(!(t=0;--f)n.push(a(l[f],c[f],n[o]+u*i[o])),i.push(0),o+=1}}},{"binary-search-bounds":70,"cubic-hermite":115}],143:[function(t,e,r){var n=t("dtype");e.exports=function(t,e,r){if(!t)throw new TypeError("must specify data as first parameter");if(r=0|+(r||0),Array.isArray(t)&&Array.isArray(t[0])){var i=t[0].length,a=t.length*i;e&&"string"!=typeof e||(e=new(n(e||"float32"))(a+r));var o=e.length-r;if(a!==o)throw new Error("source length "+a+" ("+i+"x"+t.length+") does not match destination length "+o);for(var s=0,l=r;s=0;--d){o=u[d];f[d]<=0?u[d]=new a(o._color,o.key,o.value,u[d+1],o.right,o._count+1):u[d]=new a(o._color,o.key,o.value,o.left,u[d+1],o._count+1)}for(d=u.length-1;d>1;--d){var p=u[d-1];o=u[d];if(p._color===i||o._color===i)break;var m=u[d-2];if(m.left===p)if(p.left===o){if(!(v=m.right)||v._color!==n){if(m._color=n,m.left=p.right,p._color=i,p.right=m,u[d-2]=p,u[d-1]=o,l(m),l(p),d>=3)(g=u[d-3]).left===m?g.left=p:g.right=p;break}p._color=i,m.right=s(i,v),m._color=n,d-=1}else{if(!(v=m.right)||v._color!==n){if(p.right=o.left,m._color=n,m.left=o.right,o._color=i,o.left=p,o.right=m,u[d-2]=o,u[d-1]=p,l(m),l(p),l(o),d>=3)(g=u[d-3]).left===m?g.left=o:g.right=o;break}p._color=i,m.right=s(i,v),m._color=n,d-=1}else if(p.right===o){if(!(v=m.left)||v._color!==n){if(m._color=n,m.right=p.left,p._color=i,p.left=m,u[d-2]=p,u[d-1]=o,l(m),l(p),d>=3)(g=u[d-3]).right===m?g.right=p:g.left=p;break}p._color=i,m.left=s(i,v),m._color=n,d-=1}else{var v;if(!(v=m.left)||v._color!==n){var g;if(p.left=o.right,m._color=n,m.right=o.left,o._color=i,o.right=p,o.left=m,u[d-2]=o,u[d-1]=p,l(m),l(p),l(o),d>=3)(g=u[d-3]).right===m?g.right=o:g.left=o;break}p._color=i,m.left=s(i,v),m._color=n,d-=1}}return u[0]._color=i,new c(r,u[0])},u.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(u,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new f(this,t)}}),Object.defineProperty(u,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new f(this,t)}}),u.at=function(t){if(t<0)return new f(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new f(this,[])},u.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new f(this,n)},u.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new f(this,n)},u.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new f(this,n)},u.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new f(this,n)},u.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new f(this,n);r=i<=0?r.left:r.right}return new f(this,[])},u.remove=function(t){var e=this.find(t);return e?e.remove():this},u.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var h=f.prototype;function d(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function p(t,e){return te?1:0}Object.defineProperty(h,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(h,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),h.clone=function(){return new f(this.tree,this._stack.slice())},h.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new a(r._color,r.key,r.value,r.left,r.right,r._count);for(var u=t.length-2;u>=0;--u){(r=t[u]).left===t[u+1]?e[u]=new a(r._color,r.key,r.value,e[u+1],r.right,r._count):e[u]=new a(r._color,r.key,r.value,r.left,e[u+1],r._count)}if((r=e[e.length-1]).left&&r.right){var f=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var h=e[f-1];e.push(new a(r._color,h.key,h.value,r.left,r.right,r._count)),e[f-1].key=r.key,e[f-1].value=r.value;for(u=e.length-2;u>=f;--u)r=e[u],e[u]=new a(r._color,r.key,r.value,r.left,e[u+1],r._count);e[f-1].left=e[f]}if((r=e[e.length-1])._color===n){var p=e[e.length-2];p.left===r?p.left=null:p.right===r&&(p.right=null),e.pop();for(u=0;u=0;--u){if(e=t[u],0===u)return void(e._color=i);if((r=t[u-1]).left===e){if((a=r.right).right&&a.right._color===n)return c=(a=r.right=o(a)).right=o(a.right),r.right=a.left,a.left=r,a.right=c,a._color=r._color,e._color=i,r._color=i,c._color=i,l(r),l(a),u>1&&((f=t[u-2]).left===r?f.left=a:f.right=a),void(t[u-1]=a);if(a.left&&a.left._color===n)return c=(a=r.right=o(a)).left=o(a.left),r.right=c.left,a.left=c.right,c.left=r,c.right=a,c._color=r._color,r._color=i,a._color=i,e._color=i,l(r),l(a),l(c),u>1&&((f=t[u-2]).left===r?f.left=c:f.right=c),void(t[u-1]=c);if(a._color===i){if(r._color===n)return r._color=i,void(r.right=s(n,a));r.right=s(n,a);continue}a=o(a),r.right=a.left,a.left=r,a._color=r._color,r._color=n,l(r),l(a),u>1&&((f=t[u-2]).left===r?f.left=a:f.right=a),t[u-1]=a,t[u]=r,u+11&&((f=t[u-2]).right===r?f.right=a:f.left=a),void(t[u-1]=a);if(a.right&&a.right._color===n)return c=(a=r.left=o(a)).right=o(a.right),r.left=c.right,a.right=c.left,c.right=r,c.left=a,c._color=r._color,r._color=i,a._color=i,e._color=i,l(r),l(a),l(c),u>1&&((f=t[u-2]).right===r?f.right=c:f.left=c),void(t[u-1]=c);if(a._color===i){if(r._color===n)return r._color=i,void(r.left=s(n,a));r.left=s(n,a);continue}var f;a=o(a),r.left=a.right,a.right=r,a._color=r._color,r._color=n,l(r),l(a),u>1&&((f=t[u-2]).right===r?f.right=a:f.left=a),t[u-1]=a,t[u]=r,u+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(h,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(h,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),h.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(h,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),h.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new a(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new a(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new a(n._color,n.key,n.value,n.left,r[i+1],n._count);return new c(this.tree._compare,r[0])},h.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(h,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],145:[function(t,e,r){var n=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],i=607/128,a=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function o(t){if(t<0)return Number("0/0");for(var e=a[0],r=a.length-1;r>0;--r)e+=a[r]/(t+r);var n=t+i+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}e.exports=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(o(e));e-=1;for(var r=n[0],i=1;i<9;i++)r+=n[i]/(e+i);var a=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(a,e+.5)*Math.exp(-a)*r},e.exports.log=o},{}],146:[function(t,e,r){var n=t("wgs84");function i(t){var e=0;if(t&&t.length>0){e+=Math.abs(a(t[0]));for(var r=1;r2){for(var r,i,a=0;a=0}(t)===e?t:t.reverse()}e.exports=function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(i(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){"Polygon"===t.type?t.coordinates=a(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(i(a,e)));return t}(e,r);default:return e}}},{"geojson-area":146}],148:[function(t,e,r){"use strict";e.exports=function(t,e,r,o,s,l,c,u){if(o/=e,c>=(r/=e)&&u<=o)return t;if(c>o||u=r&&p<=o)f.push(m);else if(!(d>o||p=e&&s<=r&&i.push(o)}return i}function a(t,e,r,n,i,a){for(var s=[],l=0;lr?(x.push(i(c,p,e),i(c,p,r)),a||(x=o(s,x,v,g,y))):d>=e&&x.push(i(c,p,e)):h>r?dr&&(x.push(i(c,p,r)),a||(x=o(s,x,v,g,y))));(h=(c=m[b-1])[n])>=e&&h<=r&&x.push(c),f=x[x.length-1],a&&f&&(x[0][0]!==f[0]||x[0][1]!==f[1])&&x.push(x[0]),o(s,x,v,g,y)}return s}function o(t,e,r,n,i){return e.length&&(e.area=r,e.dist=n,void 0!==i&&(e.outer=i),t.push(e)),[]}},{"./feature":150}],149:[function(t,e,r){"use strict";e.exports=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var n=0;n1?1:n,0]}},{"./feature":150,"./simplify":152}],150:[function(t,e,r){"use strict";function n(t,e,r){for(var n,i=0;i1)return!1;var o=a.geometry[0].length;if(5!==o)return!1;for(var s=0;s1&&console.time("creation"),b=this.tiles[y]=s(t,g,r,n,x,e===p.maxZoom),this.tileCoords.push({z:e,x:r,y:n}),m)){m>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,b.numFeatures,b.numPoints,b.numSimplified),console.timeEnd("creation"));var _="z"+e;this.stats[_]=(this.stats[_]||0)+1,this.total++}if(b.source=t,i){if(e===p.maxZoom||e===i)continue;var w=1<1&&console.time("clipping");var M,k,A,T,E,S,L=.5*p.buffer/p.extent,C=.5-L,P=.5+L,z=1+L;M=k=A=T=null,E=a(t,g,r-L,r+P,0,u,b.min[0],b.max[0]),S=a(t,g,r+C,r+z,0,u,b.min[0],b.max[0]),E&&(M=a(E,g,n-L,n+P,1,f,b.min[1],b.max[1]),k=a(E,g,n+C,n+z,1,f,b.min[1],b.max[1])),S&&(A=a(S,g,n-L,n+P,1,f,b.min[1],b.max[1]),T=a(S,g,n+C,n+z,1,f,b.min[1],b.max[1])),m>1&&console.timeEnd("clipping"),t.length&&(d.push(M||[],e+1,2*r,2*n),d.push(k||[],e+1,2*r,2*n+1),d.push(A||[],e+1,2*r+1,2*n),d.push(T||[],e+1,2*r+1,2*n+1))}else i&&(v=e)}return v},l.prototype.getTile=function(t,e,r){var n=this.options,a=n.extent,o=n.debug,s=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var u,f=t,d=e,p=r;!u&&f>0;)f--,d=Math.floor(d/2),p=Math.floor(p/2),u=this.tiles[c(f,d,p)];if(!u||!u.source)return null;if(o>1&&console.log("found parent tile z%d-%d-%d",f,d,p),h(u,a,n.buffer))return i.tile(u,a);o>1&&console.time("drilling down");var m=this.splitTile(u.source,f,d,p,t,e,r);if(o>1&&console.timeEnd("drilling down"),null!==m){var v=1<1?(n=a,i=o):f>0&&(n+=c*f,i+=u*f)}return(c=s-n)*c+(u=l-i)*u}e.exports=function(t,e){var r,i,a,o,s=e*e,l=0,c=t.length-1,u=[];t[l][2]=1,t[c][2]=1;for(;c;){for(i=0,r=l+1;ri&&(o=r,i=a);i>s?(t[o][2]=i,u.push(l),u.push(o),l=o):(c=u.pop(),l=u.pop())}}},{}],153:[function(t,e,r){"use strict";function n(t,e,r,n){var a,o,s,l,c=e.geometry,u=e.type,f=[],h=r*r;if(1===u)for(a=0;ah)&&(d.push(l),t.numSimplified++),t.numPoints++;3===u&&i(d,s.outer),f.push(d)}else t.numPoints+=s.length;if(f.length){var p={geometry:f,type:u,tags:e.tags||null};null!==e.id&&(p.id=e.id),t.features.push(p)}}function i(t,e){(function(t){for(var e,r,n=0,i=0,a=t.length,o=a-1;is.max[0]&&(s.max[0]=u[0]),u[1]>s.max[1]&&(s.max[1]=u[1])}return s}},{}],154:[function(t,e,r){"use strict";function n(t,e,r,n,i){return[Math.round(e*(t[0]*r-n)),Math.round(e*(t[1]*r-i))]}r.tile=function(t,e){if(t.transformed)return t;var r,i,a,o=t.z2,s=t.x,l=t.y;for(r=0;r0?(d[u]=-1,p[u]=0):(d[u]=0,p[u]=1)}}var m=[0,0,0],v={model:l,view:l,projection:l};f.isOpaque=function(){return!0},f.isTransparent=function(){return!1},f.drawTransparent=function(t){};var g=[0,0,0],y=[0,0,0],b=[0,0,0];f.draw=function(t){t=t||v;for(var e=this.gl,r=t.model||l,n=t.view||l,i=t.projection||l,a=this.bounds,s=o(r,n,i,a),u=s.cubeEdges,f=s.axis,h=n[12],x=n[13],_=n[14],w=n[15],M=this.pixelRatio*(i[3]*h+i[7]*x+i[11]*_+i[15]*w)/e.drawingBufferHeight,k=0;k<3;++k)this.lastCubeProps.cubeEdges[k]=u[k],this.lastCubeProps.axis[k]=f[k];var A=d;for(k=0;k<3;++k)p(d[k],k,this.bounds,u,f);e=this.gl;var T=m;for(k=0;k<3;++k)this.backgroundEnable[k]?T[k]=f[k]:T[k]=0;this._background.draw(r,n,i,a,T,this.backgroundColor),this._lines.bind(r,n,i,this);for(k=0;k<3;++k){var E=[0,0,0];f[k]>0?E[k]=a[1][k]:E[k]=a[0][k];for(var S=0;S<2;++S){var L=(k+1+S)%3,C=(k+1+(1^S))%3;this.gridEnable[L]&&this._lines.drawGrid(L,C,this.bounds,E,this.gridColor[L],this.gridWidth[L]*this.pixelRatio)}for(S=0;S<2;++S){L=(k+1+S)%3,C=(k+1+(1^S))%3;this.zeroEnable[C]&&a[0][C]<=0&&a[1][C]>=0&&this._lines.drawZero(L,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(k=0;k<3;++k){this.lineEnable[k]&&this._lines.drawAxisLine(k,this.bounds,A[k].primalOffset,this.lineColor[k],this.lineWidth[k]*this.pixelRatio),this.lineMirror[k]&&this._lines.drawAxisLine(k,this.bounds,A[k].mirrorOffset,this.lineColor[k],this.lineWidth[k]*this.pixelRatio);var P=c(g,A[k].primalMinor),z=c(y,A[k].mirrorMinor),O=this.lineTickLength;for(S=0;S<3;++S){var D=M/r[5*S];P[S]*=O[S]*D,z[S]*=O[S]*D}this.lineTickEnable[k]&&this._lines.drawAxisTicks(k,A[k].primalOffset,P,this.lineTickColor[k],this.lineTickWidth[k]*this.pixelRatio),this.lineTickMirror[k]&&this._lines.drawAxisTicks(k,A[k].mirrorOffset,z,this.lineTickColor[k],this.lineTickWidth[k]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);for(k=0;k<3;++k){var I=A[k].primalMinor,R=c(b,A[k].primalOffset);for(S=0;S<3;++S)this.lineTickEnable[k]&&(R[S]+=M*I[S]*Math.max(this.lineTickLength[S],0)/r[5*S]);if(this.tickEnable[k]){for(S=0;S<3;++S)R[S]+=M*I[S]*this.tickPad[S]/r[5*S];this._text.drawTicks(k,this.tickSize[k],this.tickAngle[k],R,this.tickColor[k])}if(this.labelEnable[k]){for(S=0;S<3;++S)R[S]+=M*I[S]*this.labelPad[S]/r[5*S];R[k]+=.5*(a[0][k]+a[1][k]),this._text.drawLabel(k,this.labelSize[k],this.labelAngle[k],R,this.labelColor[k])}}this._text.unbind()},f.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":158,"./lib/cube.js":159,"./lib/lines.js":160,"./lib/text.js":162,"./lib/ticks.js":163}],158:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=[],s=0,l=0;l<3;++l)for(var c=(l+1)%3,u=(l+2)%3,f=[0,0,0],h=[0,0,0],d=-1;d<=1;d+=2){r.push(s,s+2,s+1,s+1,s+2,s+3),f[l]=d,h[l]=d;for(var p=-1;p<=1;p+=2){f[c]=p;for(var m=-1;m<=1;m+=2)f[u]=m,e.push(f[0],f[1],f[2],h[0],h[1],h[2]),s+=1}var v=c;c=u,u=v}var g=n(t,new Float32Array(e)),y=n(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=i(t,[{buffer:g,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:g,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=a(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new o(t,g,b,x)};var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders").bg;function o(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var s=o.prototype;s.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},s.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":161,"gl-buffer":165,"gl-vao":237}],159:[function(t,e,r){"use strict";e.exports=function(t,e,r,a){i(s,e,t),i(s,r,s);for(var d=0,y=0;y<2;++y){u[2]=a[y][2];for(var b=0;b<2;++b){u[1]=a[b][1];for(var x=0;x<2;++x)u[0]=a[x][0],h(l[d],u,s),d+=1}}for(var _=-1,y=0;y<8;++y){for(var w=l[y][3],M=0;M<3;++M)c[y][M]=l[y][M]/w;w<0&&(_<0?_=y:c[y][2]E&&(_|=1<E&&(_|=1<c[y][1]&&(I=y));for(var R=-1,y=0;y<3;++y){var N=I^1<c[F][0]&&(F=N)}}var j=m;j[0]=j[1]=j[2]=0,j[n.log2(R^I)]=I&R,j[n.log2(I^F)]=I&F;var B=7^F;B===_||B===D?(B=7^R,j[n.log2(F^B)]=B&F):j[n.log2(R^B)]=B&R;for(var U=v,V=_,k=0;k<3;++k)U[k]=V&1< 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]),u=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);r.bg=function(t){return i(t,c,u,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])}},{"gl-shader":220,glslify:253}],162:[function(t,e,r){(function(r){"use strict";e.exports=function(t,e,r,a,s,l){var u=n(t),f=i(t,[{buffer:u,size:3}]),h=o(t);h.attributes.position.location=0;var d=new c(t,h,u,f);return d.update(e,r,a,s,l),d};var n=t("gl-buffer"),i=t("gl-vao"),a=t("vectorize-text"),o=t("./shaders").text,s=window||r.global||{},l=s.__TEXT_CACHE||{};s.__TEXT_CACHE={};function c(t,e,r,n){this.gl=t,this.shader=e,this.buffer=r,this.vao=n,this.tickOffset=this.tickCount=this.labelOffset=this.labelCount=null}var u=c.prototype,f=[0,0];u.bind=function(t,e,r,n){this.vao.bind(),this.shader.bind();var i=this.shader.uniforms;i.model=t,i.view=e,i.projection=r,i.pixelScale=n,f[0]=this.gl.drawingBufferWidth,f[1]=this.gl.drawingBufferHeight,this.shader.uniforms.resolution=f},u.unbind=function(){this.vao.unbind()},u.update=function(t,e,r,n,i){this.gl;var o=[];function s(t,e,r,n){var i=l[r];i||(i=l[r]={});var s=i[e];s||(s=i[e]=function(t,e){try{return a(t,e)}catch(t){return console.warn("error vectorizing text:",t),{cells:[],positions:[]}}}(e,{triangles:!0,font:r,textAlign:"center",textBaseline:"middle"}));for(var c=(n||12)/12,u=s.positions,f=s.cells,h=0,d=f.length;h=0;--m){var v=u[p[m]];o.push(c*v[0],-c*v[1],t)}}for(var c=[0,0,0],u=[0,0,0],f=[0,0,0],h=[0,0,0],d=0;d<3;++d){f[d]=o.length/3|0,s(.5*(t[0][d]+t[1][d]),e[d],r),h[d]=(o.length/3|0)-f[d],c[d]=o.length/3|0;for(var p=0;p=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,c=o%a;o<0?(l=0|-Math.ceil(l),c=0|-c):(l=0|Math.floor(l),c|=0);var u=""+l;if(o<0&&(u="-"+u),i){for(var f=""+c;f.length=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r},r.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;nr)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function u(t,e){for(var r=n.malloc(t.length,e),i=t.length,a=0;a=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=c(this.gl,this.type,this.length,this.usage,t.data,e):this.length=c(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=n.malloc(t.size,r),l=a(s,t.shape);i.assign(l,t),this.length=c(this.gl,this.type,this.length,this.usage,e<0?s:s.subarray(0,t.size),e),n.free(s)}}else if(Array.isArray(t)){var f;f=this.type===this.gl.ELEMENT_ARRAY_BUFFER?u(t,"uint16"):u(t,"float32"),this.length=c(this.gl,this.type,this.length,this.usage,e<0?f:f.subarray(0,t.length),e),n.free(f)}else if("object"==typeof t&&"number"==typeof t.length)this.length=c(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=new s(t,r,t.createBuffer(),0,n);return i.update(e),i}},{ndarray:439,"ndarray-ops":433,"typedarray-pool":534}],166:[function(t,e,r){e.exports={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"}},{}],167:[function(t,e,r){var n=t("./1.0/numbers");e.exports=function(t){return n[t]}},{"./1.0/numbers":166}],168:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=n(e),o=i(e,[{buffer:r,type:e.FLOAT,size:3,offset:0,stride:40},{buffer:r,type:e.FLOAT,size:4,offset:12,stride:40},{buffer:r,type:e.FLOAT,size:3,offset:28,stride:40}]),l=a(e);l.attributes.position.location=0,l.attributes.color.location=1,l.attributes.offset.location=2;var c=new s(e,r,o,l);return c.update(t),c};var n=t("gl-buffer"),i=t("gl-vao"),a=t("./shaders/index"),o=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function s(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}var l=s.prototype;function c(t,e){for(var r=0;r<3;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}l.isOpaque=function(){return this.opacity>=1},l.isTransparent=function(){return this.opacity<1},l.drawTransparent=l.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||o,i=r.projection=t.projection||o;r.model=t.model||o,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],s=n[13],l=n[14],c=n[15],u=this.pixelRatio*(i[3]*a+i[7]*s+i[11]*l+i[15]*c)/e.drawingBufferHeight;this.vao.bind();for(var f=0;f<3;++f)e.lineWidth(this.lineWidth[f]),r.capSize=this.capSize[f]*u,this.lineCount[f]&&e.drawArrays(e.LINES,this.lineOffset[f],this.lineCount[f]);this.vao.unbind()};var u=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function f(t,e,r,n){for(var i=u[n],a=0;a0)(m=u.slice())[s]+=d[1][s],i.push(u[0],u[1],u[2],p[0],p[1],p[2],p[3],0,0,0,m[0],m[1],m[2],p[0],p[1],p[2],p[3],0,0,0),c(this.bounds,m),o+=2+f(i,m,p,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},l.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":170,"gl-buffer":165,"gl-vao":237}],169:[function(t,e,r){e.exports=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;nu||r<0||r>u)throw new Error("gl-fbo: Parameters are too large for FBO");var f=1;if("color"in(n=n||{})){if((f=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(f>1){if(!c)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(f>t.getParameter(c.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+f+" draw buffers")}}var h=t.UNSIGNED_BYTE,d=t.getExtension("OES_texture_float");if(n.float&&f>0){if(!d)throw new Error("gl-fbo: Context does not support floating point textures");h=t.FLOAT}else n.preferFloat&&f>0&&d&&(h=t.FLOAT);var m=!0;"depth"in n&&(m=!!n.depth);var v=!1;"stencil"in n&&(v=!!n.stencil);return new p(t,e,r,h,f,m,v,c)};var i,a,o,s,l=null;function c(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function u(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function f(t){switch(t){case i:throw new Error("gl-fbo: Framebuffer unsupported");case a:throw new Error("gl-fbo: Framebuffer incomplete attachment");case o:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case s:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function h(t,e,r,i,a,o){if(!i)return null;var s=n(t,e,r,a,i);return s.magFilter=t.NEAREST,s.minFilter=t.NEAREST,s.mipSamples=1,s.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.handle,0),s}function d(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function p(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var p=0;p1&&s.drawBuffersWEBGL(l[o]);var y=r.getExtension("WEBGL_depth_texture");y?p?t.depth=h(r,i,a,y.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):m&&(t.depth=h(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):m&&p?t._depth_rb=d(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):m?t._depth_rb=d(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):p&&(t._depth_rb=d(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),g=0;gi||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=c(n),o=0;o>8*d&255;this.pickOffset=r,i.bind();var p=i.uniforms;p.viewTransform=t,p.pickOffset=e,p.shape=this.shape;var m=i.attributes;return this.positionBuffer.bind(),m.position.pointer(),this.weightBuffer.bind(),m.weight.pointer(s.UNSIGNED_BYTE,!1),this.idBuffer.bind(),m.pickId.pointer(s.UNSIGNED_BYTE,!1),s.drawArrays(s.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.shape[0]*this.shape[1];if(r=n+i)return null;var a=r-n,o=this.xData,s=this.yData;return{object:this,pointId:a,dataCoord:[o[a%this.shape[0]],s[a/this.shape[0]|0]]}},f.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||i(e[0]),o=t.y||i(e[1]),s=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=o;var l=t.colorLevels||[0],c=t.colorValues||[0,0,0,1],u=l.length,f=this.bounds,d=f[0]=r[0],p=f[1]=o[0],m=1/((f[2]=r[r.length-1])-d),v=1/((f[3]=o[o.length-1])-p),g=e[0],y=e[1];this.shape=[g,y];var b=(g-1)*(y-1)*(h.length>>>1);this.numVertices=b;for(var x=a.mallocUint8(4*b),_=a.mallocFloat32(2*b),w=a.mallocUint8(2*b),M=a.mallocUint32(b),k=0,A=0;A FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),l=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return i(t,a,o,null,l)},r.createPickShader=function(t){return i(t,a,s,null,l)}},{"gl-shader":220,glslify:253}],177:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl||t.scene&&t.scene.gl,r=u(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var o=f(e);o.attributes.position.location=0,o.attributes.nextPosition.location=1,o.attributes.arcLength.location=2,o.attributes.lineWidth.location=3,o.attributes.color.location=4;for(var s=n(e),c=i(e,[{buffer:s,size:3,offset:0,stride:48},{buffer:s,size:3,offset:12,stride:48},{buffer:s,size:1,offset:24,stride:48},{buffer:s,size:1,offset:28,stride:48},{buffer:s,size:4,offset:32,stride:48}]),h=l(new Array(1024),[256,1,4]),d=0;d<1024;++d)h.data[d]=255;var p=a(e,h);p.wrap=e.REPEAT;var m=new v(e,r,o,s,c,p);return m.update(t),m};var n=t("gl-buffer"),i=t("gl-vao"),a=t("gl-texture2d"),o=t("glsl-read-float"),s=t("binary-search-bounds"),l=t("ndarray"),c=t("./lib/shaders"),u=c.createShader,f=c.createPickShader,h=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function d(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function p(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function m(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function v(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}var g=v.prototype;g.isTransparent=function(){return this.opacity<1},g.isOpaque=function(){return this.opacity>=1},g.pickSlots=1,g.setPickBase=function(t){this.pickId=t},g.drawTransparent=g.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||h,view:t.view||h,projection:t.projection||h,clipBounds:p(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},g.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||h,view:t.view||h,projection:t.projection||h,pickId:this.pickId,clipBounds:p(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},g.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var i=t.position||t.positions;if(i){var a=t.color||t.colors||[0,0,0,1],o=t.lineWidth||1,c=[],u=[],f=[],h=0,p=0,m=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],v=!1;t:for(e=1;e0){for(var w=0;w<24;++w)c.push(c[c.length-12]);p+=2,v=!0}continue t}m[0][r]=Math.min(m[0][r],x[r],_[r]),m[1][r]=Math.max(m[1][r],x[r],_[r])}Array.isArray(a[0])?(g=a[e-1],y=a[e]):g=y=a,3===g.length&&(g=[g[0],g[1],g[2],1]),3===y.length&&(y=[y[0],y[1],y[2],1]),b=Array.isArray(o)?o[e-1]:o;var M=h;if(h+=d(x,_),v){for(r=0;r<2;++r)c.push(x[0],x[1],x[2],_[0],_[1],_[2],M,b,g[0],g[1],g[2],g[3]);p+=2,v=!1}c.push(x[0],x[1],x[2],_[0],_[1],_[2],M,b,g[0],g[1],g[2],g[3],x[0],x[1],x[2],_[0],_[1],_[2],M,-b,g[0],g[1],g[2],g[3],_[0],_[1],_[2],x[0],x[1],x[2],h,-b,y[0],y[1],y[2],y[3],_[0],_[1],_[2],x[0],x[1],x[2],h,b,y[0],y[1],y[2],y[3]),p+=4}if(this.buffer.update(c),u.push(h),f.push(i[i.length-1].slice()),this.bounds=m,this.vertexCount=p,this.points=f,this.arcLength=u,"dashes"in t){var k=t.dashes.slice();for(k.unshift(0),e=1;e1?0:i<-1?Math.PI:Math.acos(i)},e.str=function(t){return"vec3("+t[0]+", "+t[1]+", "+t[2]+")"},e.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]},e.equals=function(t,e){var r=t[0],i=t[1],a=t[2],o=e[0],s=e[1],l=e[2];return Math.abs(r-o)<=n.EPSILON*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(i-s)<=n.EPSILON*Math.max(1,Math.abs(i),Math.abs(s))&&Math.abs(a-l)<=n.EPSILON*Math.max(1,Math.abs(a),Math.abs(l))};var n=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(r(0));function i(){var t=new n.ARRAY_TYPE(3);return t[0]=0,t[1]=0,t[2]=0,t}function a(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}function o(t,e,r){var i=new n.ARRAY_TYPE(3);return i[0]=t,i[1]=e,i[2]=r,i}function s(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function l(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function c(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function u(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.sqrt(r*r+n*n+i*i)}function f(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function h(t){var e=t[0],r=t[1],n=t[2];return e*e+r*r+n*n}function d(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}function p(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}var m;e.sub=s,e.mul=l,e.div=c,e.dist=u,e.sqrDist=f,e.len=a,e.sqrLen=h,e.forEach=(m=i(),function(t,e,r,n,i,a){var o=void 0,s=void 0;for(e||(e=3),r||(r=0),s=n?Math.min(n*e+r,t.length):t.length,o=r;o0&&(o=1/Math.sqrt(o),t[0]=r*o,t[1]=n*o,t[2]=i*o,t[3]=a*o),t}var p;e.sub=a,e.mul=o,e.div=s,e.dist=c,e.sqrDist=u,e.len=f,e.sqrLen=h,e.forEach=(p=i(),function(t,e,r,n,i,a){var o=void 0,s=void 0;for(e||(e=4),r||(r=0),s=n?Math.min(n*e+r,t.length):t.length,o=r;o0?(n=2*Math.sqrt(r+1),t[3]=.25*n,t[0]=(e[6]-e[9])/n,t[1]=(e[8]-e[2])/n,t[2]=(e[1]-e[4])/n):e[0]>e[5]&e[0]>e[10]?(n=2*Math.sqrt(1+e[0]-e[5]-e[10]),t[3]=(e[6]-e[9])/n,t[0]=.25*n,t[1]=(e[1]+e[4])/n,t[2]=(e[8]+e[2])/n):e[5]>e[10]?(n=2*Math.sqrt(1+e[5]-e[0]-e[10]),t[3]=(e[8]-e[2])/n,t[0]=(e[1]+e[4])/n,t[1]=.25*n,t[2]=(e[6]+e[9])/n):(n=2*Math.sqrt(1+e[10]-e[0]-e[5]),t[3]=(e[1]-e[4])/n,t[0]=(e[8]+e[2])/n,t[1]=(e[6]+e[9])/n,t[2]=.25*n);return t},e.fromRotationTranslationScale=function(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],l=i+i,c=a+a,u=o+o,f=i*l,h=i*c,d=i*u,p=a*c,m=a*u,v=o*u,g=s*l,y=s*c,b=s*u,x=n[0],_=n[1],w=n[2];return t[0]=(1-(p+v))*x,t[1]=(h+b)*x,t[2]=(d-y)*x,t[3]=0,t[4]=(h-b)*_,t[5]=(1-(f+v))*_,t[6]=(m+g)*_,t[7]=0,t[8]=(d+y)*w,t[9]=(m-g)*w,t[10]=(1-(f+p))*w,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t},e.fromRotationTranslationScaleOrigin=function(t,e,r,n,i){var a=e[0],o=e[1],s=e[2],l=e[3],c=a+a,u=o+o,f=s+s,h=a*c,d=a*u,p=a*f,m=o*u,v=o*f,g=s*f,y=l*c,b=l*u,x=l*f,_=n[0],w=n[1],M=n[2],k=i[0],A=i[1],T=i[2];return t[0]=(1-(m+g))*_,t[1]=(d+x)*_,t[2]=(p-b)*_,t[3]=0,t[4]=(d-x)*w,t[5]=(1-(h+g))*w,t[6]=(v+y)*w,t[7]=0,t[8]=(p+b)*M,t[9]=(v-y)*M,t[10]=(1-(h+m))*M,t[11]=0,t[12]=r[0]+k-(t[0]*k+t[4]*A+t[8]*T),t[13]=r[1]+A-(t[1]*k+t[5]*A+t[9]*T),t[14]=r[2]+T-(t[2]*k+t[6]*A+t[10]*T),t[15]=1,t},e.fromQuat=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,c=r*o,u=n*o,f=n*s,h=i*o,d=i*s,p=i*l,m=a*o,v=a*s,g=a*l;return t[0]=1-f-p,t[1]=u+g,t[2]=h-v,t[3]=0,t[4]=u-g,t[5]=1-c-p,t[6]=d+m,t[7]=0,t[8]=h+v,t[9]=d-m,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},e.frustum=function(t,e,r,n,i,a,o){var s=1/(r-e),l=1/(i-n),c=1/(a-o);return t[0]=2*a*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*a*l,t[6]=0,t[7]=0,t[8]=(r+e)*s,t[9]=(i+n)*l,t[10]=(o+a)*c,t[11]=-1,t[12]=0,t[13]=0,t[14]=o*a*2*c,t[15]=0,t},e.perspective=function(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t},e.perspectiveFromFieldOfView=function(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),o=Math.tan(e.leftDegrees*Math.PI/180),s=Math.tan(e.rightDegrees*Math.PI/180),l=2/(o+s),c=2/(i+a);return t[0]=l,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=c,t[6]=0,t[7]=0,t[8]=-(o-s)*l*.5,t[9]=(i-a)*c*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t},e.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),l=1/(n-i),c=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*l,t[14]=(o+a)*c,t[15]=1,t},e.lookAt=function(t,e,r,i){var a=void 0,o=void 0,s=void 0,l=void 0,c=void 0,u=void 0,f=void 0,h=void 0,d=void 0,p=void 0,m=e[0],v=e[1],g=e[2],y=i[0],b=i[1],x=i[2],_=r[0],w=r[1],M=r[2];if(Math.abs(m-_)0&&(d=1/Math.sqrt(d),u*=d,f*=d,h*=d);var p=l*h-c*f,m=c*u-s*h,v=s*f-l*u;return t[0]=p,t[1]=m,t[2]=v,t[3]=0,t[4]=f*v-h*m,t[5]=h*p-u*v,t[6]=u*m-f*p,t[7]=0,t[8]=u,t[9]=f,t[10]=h,t[11]=0,t[12]=i,t[13]=a,t[14]=o,t[15]=1,t},e.str=function(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"},e.frob=function(t){return Math.sqrt(Math.pow(t[0],2)+Math.pow(t[1],2)+Math.pow(t[2],2)+Math.pow(t[3],2)+Math.pow(t[4],2)+Math.pow(t[5],2)+Math.pow(t[6],2)+Math.pow(t[7],2)+Math.pow(t[8],2)+Math.pow(t[9],2)+Math.pow(t[10],2)+Math.pow(t[11],2)+Math.pow(t[12],2)+Math.pow(t[13],2)+Math.pow(t[14],2)+Math.pow(t[15],2))},e.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t},e.subtract=a,e.multiplyScalar=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t},e.multiplyScalarAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t},e.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},e.equals=function(t,e){var r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],l=t[5],c=t[6],u=t[7],f=t[8],h=t[9],d=t[10],p=t[11],m=t[12],v=t[13],g=t[14],y=t[15],b=e[0],x=e[1],_=e[2],w=e[3],M=e[4],k=e[5],A=e[6],T=e[7],E=e[8],S=e[9],L=e[10],C=e[11],P=e[12],z=e[13],O=e[14],D=e[15];return Math.abs(r-b)<=n.EPSILON*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(i-x)<=n.EPSILON*Math.max(1,Math.abs(i),Math.abs(x))&&Math.abs(a-_)<=n.EPSILON*Math.max(1,Math.abs(a),Math.abs(_))&&Math.abs(o-w)<=n.EPSILON*Math.max(1,Math.abs(o),Math.abs(w))&&Math.abs(s-M)<=n.EPSILON*Math.max(1,Math.abs(s),Math.abs(M))&&Math.abs(l-k)<=n.EPSILON*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(c-A)<=n.EPSILON*Math.max(1,Math.abs(c),Math.abs(A))&&Math.abs(u-T)<=n.EPSILON*Math.max(1,Math.abs(u),Math.abs(T))&&Math.abs(f-E)<=n.EPSILON*Math.max(1,Math.abs(f),Math.abs(E))&&Math.abs(h-S)<=n.EPSILON*Math.max(1,Math.abs(h),Math.abs(S))&&Math.abs(d-L)<=n.EPSILON*Math.max(1,Math.abs(d),Math.abs(L))&&Math.abs(p-C)<=n.EPSILON*Math.max(1,Math.abs(p),Math.abs(C))&&Math.abs(m-P)<=n.EPSILON*Math.max(1,Math.abs(m),Math.abs(P))&&Math.abs(v-z)<=n.EPSILON*Math.max(1,Math.abs(v),Math.abs(z))&&Math.abs(g-O)<=n.EPSILON*Math.max(1,Math.abs(g),Math.abs(O))&&Math.abs(y-D)<=n.EPSILON*Math.max(1,Math.abs(y),Math.abs(D))};var n=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(r(0));function i(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],f=e[8],h=e[9],d=e[10],p=e[11],m=e[12],v=e[13],g=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*f+w*m,t[1]=b*i+x*l+_*h+w*v,t[2]=b*a+x*c+_*d+w*g,t[3]=b*o+x*u+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*f+w*m,t[5]=b*i+x*l+_*h+w*v,t[6]=b*a+x*c+_*d+w*g,t[7]=b*o+x*u+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*f+w*m,t[9]=b*i+x*l+_*h+w*v,t[10]=b*a+x*c+_*d+w*g,t[11]=b*o+x*u+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*f+w*m,t[13]=b*i+x*l+_*h+w*v,t[14]=b*a+x*c+_*d+w*g,t[15]=b*o+x*u+_*p+w*y,t}function a(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}e.mul=i,e.sub=a},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setAxes=e.sqlerp=e.rotationTo=e.equals=e.exactEquals=e.normalize=e.sqrLen=e.squaredLength=e.len=e.length=e.lerp=e.dot=e.scale=e.mul=e.add=e.set=e.copy=e.fromValues=e.clone=void 0,e.create=l,e.identity=function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t},e.setAxisAngle=c,e.getAxisAngle=function(t,e){var r=2*Math.acos(e[3]),n=Math.sin(r/2);0!=n?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0);return r},e.multiply=u,e.rotateX=function(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),l=Math.cos(r);return t[0]=n*l+o*s,t[1]=i*l+a*s,t[2]=a*l-i*s,t[3]=o*l-n*s,t},e.rotateY=function(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),l=Math.cos(r);return t[0]=n*l-a*s,t[1]=i*l+o*s,t[2]=a*l+n*s,t[3]=o*l-i*s,t},e.rotateZ=function(t,e,r){r*=.5;var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),l=Math.cos(r);return t[0]=n*l+i*s,t[1]=i*l-n*s,t[2]=a*l+o*s,t[3]=o*l-a*s,t},e.calculateW=function(t,e){var r=e[0],n=e[1],i=e[2];return t[0]=r,t[1]=n,t[2]=i,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-i*i)),t},e.slerp=f,e.invert=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*r+n*n+i*i+a*a,s=o?1/o:0;return t[0]=-r*s,t[1]=-n*s,t[2]=-i*s,t[3]=a*s,t},e.conjugate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},e.fromMat3=h,e.fromEuler=function(t,e,r,n){var i=.5*Math.PI/180;e*=i,r*=i,n*=i;var a=Math.sin(e),o=Math.cos(e),s=Math.sin(r),l=Math.cos(r),c=Math.sin(n),u=Math.cos(n);return t[0]=a*l*u-o*s*c,t[1]=o*s*u+a*l*c,t[2]=o*l*c-a*s*u,t[3]=o*l*u+a*s*c,t},e.str=function(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"};var n=s(r(0)),i=s(r(1)),a=s(r(2)),o=s(r(3));function s(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function l(){var t=new n.ARRAY_TYPE(4);return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}function c(t,e,r){r*=.5;var n=Math.sin(r);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(r),t}function u(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=r[0],l=r[1],c=r[2],u=r[3];return t[0]=n*u+o*s+i*c-a*l,t[1]=i*u+o*l+a*s-n*c,t[2]=a*u+o*c+n*l-i*s,t[3]=o*u-n*s-i*l-a*c,t}function f(t,e,r,n){var i=e[0],a=e[1],o=e[2],s=e[3],l=r[0],c=r[1],u=r[2],f=r[3],h=void 0,d=void 0,p=void 0,m=void 0,v=void 0;return(d=i*l+a*c+o*u+s*f)<0&&(d=-d,l=-l,c=-c,u=-u,f=-f),1-d>1e-6?(h=Math.acos(d),p=Math.sin(h),m=Math.sin((1-n)*h)/p,v=Math.sin(n*h)/p):(m=1-n,v=n),t[0]=m*i+v*l,t[1]=m*a+v*c,t[2]=m*o+v*u,t[3]=m*s+v*f,t}function h(t,e){var r=e[0]+e[4]+e[8],n=void 0;if(r>0)n=Math.sqrt(r+1),t[3]=.5*n,n=.5/n,t[0]=(e[5]-e[7])*n,t[1]=(e[6]-e[2])*n,t[2]=(e[1]-e[3])*n;else{var i=0;e[4]>e[0]&&(i=1),e[8]>e[3*i+i]&&(i=2);var a=(i+1)%3,o=(i+2)%3;n=Math.sqrt(e[3*i+i]-e[3*a+a]-e[3*o+o]+1),t[i]=.5*n,n=.5/n,t[3]=(e[3*a+o]-e[3*o+a])*n,t[a]=(e[3*a+i]+e[3*i+a])*n,t[o]=(e[3*o+i]+e[3*i+o])*n}return t}e.clone=o.clone,e.fromValues=o.fromValues,e.copy=o.copy,e.set=o.set,e.add=o.add,e.mul=u,e.scale=o.scale,e.dot=o.dot,e.lerp=o.lerp;var d,p,m,v,g,y,b=e.length=o.length,x=(e.len=b,e.squaredLength=o.squaredLength),_=(e.sqrLen=x,e.normalize=o.normalize);e.exactEquals=o.exactEquals,e.equals=o.equals,e.rotationTo=(d=a.create(),p=a.fromValues(1,0,0),m=a.fromValues(0,1,0),function(t,e,r){var n=a.dot(e,r);return n<-.999999?(a.cross(d,p,e),a.len(d)<1e-6&&a.cross(d,m,e),a.normalize(d,d),c(t,d,Math.PI),t):n>.999999?(t[0]=0,t[1]=0,t[2]=0,t[3]=1,t):(a.cross(d,e,r),t[0]=d[0],t[1]=d[1],t[2]=d[2],t[3]=1+n,_(t,t))}),e.sqlerp=(v=l(),g=l(),function(t,e,r,n,i,a){return f(v,e,i,a),f(g,r,n,a),f(t,v,g,2*a*(1-a)),t}),e.setAxes=(y=i.create(),function(t,e,r,n){return y[0]=r[0],y[3]=r[1],y[6]=r[2],y[1]=n[0],y[4]=n[1],y[7]=n[2],y[2]=-e[0],y[5]=-e[1],y[8]=-e[2],_(t,h(t,y))})},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.forEach=e.sqrLen=e.sqrDist=e.dist=e.div=e.mul=e.sub=e.len=void 0,e.create=i,e.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},e.fromValues=function(t,e){var r=new n.ARRAY_TYPE(2);return r[0]=t,r[1]=e,r},e.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},e.set=function(t,e,r){return t[0]=e,t[1]=r,t},e.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t},e.subtract=a,e.multiply=o,e.divide=s,e.ceil=function(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t},e.floor=function(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t},e.min=function(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t},e.max=function(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t},e.round=function(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t},e.scale=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},e.scaleAndAdd=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t},e.distance=l,e.squaredDistance=c,e.length=u,e.squaredLength=f,e.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},e.inverse=function(t,e){return t[0]=1/e[0],t[1]=1/e[1],t},e.normalize=function(t,e){var r=e[0],n=e[1],i=r*r+n*n;i>0&&(i=1/Math.sqrt(i),t[0]=e[0]*i,t[1]=e[1]*i);return t},e.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},e.cross=function(t,e,r){var n=e[0]*r[1]-e[1]*r[0];return t[0]=t[1]=0,t[2]=n,t},e.lerp=function(t,e,r,n){var i=e[0],a=e[1];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t},e.random=function(t,e){e=e||1;var r=2*n.RANDOM()*Math.PI;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t},e.transformMat2=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[2]*i,t[1]=r[1]*n+r[3]*i,t},e.transformMat2d=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[2]*i+r[4],t[1]=r[1]*n+r[3]*i+r[5],t},e.transformMat3=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[3]*i+r[6],t[1]=r[1]*n+r[4]*i+r[7],t},e.transformMat4=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},e.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},e.exactEquals=function(t,e){return t[0]===e[0]&&t[1]===e[1]},e.equals=function(t,e){var r=t[0],i=t[1],a=e[0],o=e[1];return Math.abs(r-a)<=n.EPSILON*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(i-o)<=n.EPSILON*Math.max(1,Math.abs(i),Math.abs(o))};var n=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(r(0));function i(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t}function a(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function o(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t}function s(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t}function l(t,e){var r=e[0]-t[0],n=e[1]-t[1];return Math.sqrt(r*r+n*n)}function c(t,e){var r=e[0]-t[0],n=e[1]-t[1];return r*r+n*n}function u(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)}function f(t){var e=t[0],r=t[1];return e*e+r*r}var h;e.len=u,e.sub=a,e.mul=o,e.div=s,e.dist=l,e.sqrDist=c,e.sqrLen=f,e.forEach=(h=i(),function(t,e,r,n,i,a){var o=void 0,s=void 0;for(e||(e=2),r||(r=0),s=n?Math.min(n*e+r,t.length):t.length,o=r;o1.0001)return null;v+=m[u]}if(Math.abs(v-1)>.001)return null;return[f,function(t,e){for(var r=[0,0,0],n=0;n 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),u=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}"]),f=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),h=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}"]),d=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}"]),p=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]);r.meshShader={vertex:i,fragment:a,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:o,fragment:s,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:l,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:u,fragment:f,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:h,fragment:f,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:d,fragment:p,attributes:[{name:"position",type:"vec3"}]}},{glslify:253}],201:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("normals"),l=t("gl-mat4/multiply"),c=t("gl-mat4/invert"),u=t("ndarray"),f=t("colormap"),h=t("simplicial-complex-contour"),d=t("typedarray-pool"),p=t("./lib/shaders"),m=t("./lib/closest-point"),v=p.meshShader,g=p.wireShader,y=p.pointShader,b=p.pickShader,x=p.pointPickShader,_=p.contourShader,w=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function M(t,e,r,n,i,a,o,s,l,c,u,f,h,d,p,m,v,g,y,b,x,_,M,k,A,T,E){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=u,this.triangleNormals=h,this.triangleUVs=f,this.triangleIds=c,this.triangleVAO=d,this.triangleCount=0,this.lineWidth=1,this.edgePositions=p,this.edgeColors=v,this.edgeUVs=g,this.edgeIds=m,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=M,this.pointSizes=k,this.pointIds=x,this.pointVAO=A,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=T,this.contourVAO=E,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=w,this._view=w,this._projection=w,this._resolution=[1,1]}var k=M.prototype;function A(t){var e=n(t,y.vertex,y.fragment);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function T(t){var e=n(t,b.vertex,b.fragment);return e.attributes.position.location=0,e.attributes.id.location=1,e}function E(t){var e=n(t,x.vertex,x.fragment);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function S(t){var e=n(t,_.vertex,_.fragment);return e.attributes.position.location=0,e}k.isOpaque=function(){return this.opacity>=1},k.isTransparent=function(){return this.opacity<1},k.pickSlots=1,k.setPickBase=function(t){this.pickId=t},k.highlight=function(t){if(t&&this.contourEnable){for(var e=h(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=d.mallocFloat32(6*a),s=0,l=0;l0&&((f=this.triShader).bind(),f.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((f=this.lineShader).bind(),f.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((f=this.pointShader).bind(),f.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((f=this.contourShader).bind(),f.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},k.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||w,n=t.view||w,i=t.projection||w,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},k.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;ai[k]&&(r.uniforms.dataAxis=c,r.uniforms.screenOffset=u,r.uniforms.color=v[t],r.uniforms.angle=g[t],a.drawArrays(a.TRIANGLES,i[k],i[A]-i[k]))),y[t]&&M&&(u[1^t]-=T*d*b[t],r.uniforms.dataAxis=f,r.uniforms.screenOffset=u,r.uniforms.color=x[t],r.uniforms.angle=_[t],a.drawArrays(a.TRIANGLES,w,M)),u[1^t]=T*s[2+(1^t)]-1,p[t+2]&&(u[1^t]+=T*d*m[t+2],ki[k]&&(r.uniforms.dataAxis=c,r.uniforms.screenOffset=u,r.uniforms.color=v[t+2],r.uniforms.angle=g[t+2],a.drawArrays(a.TRIANGLES,i[k],i[A]-i[k]))),y[t+2]&&M&&(u[1^t]+=T*d*b[t+2],r.uniforms.dataAxis=f,r.uniforms.screenOffset=u,r.uniforms.color=x[t+2],r.uniforms.angle=_[t+2],a.drawArrays(a.TRIANGLES,w,M))}),m.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,c=r.pixelRatio;if(this.titleCount){for(var u=0;u<2;++u)e[u]=2*(o[u]*c-a[u])/(a[2+u]-a[u])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),m.bind=(h=[0,0],d=[0,0],p=[0,0],function(){var t=this.plot,e=this.shader,r=t._tickBounds,n=t.dataBox,i=t.screenBox,a=t.viewBox;e.bind();for(var o=0;o<2;++o){var s=r[o],l=r[o+2]-s,c=.5*(n[o+2]+n[o]),u=n[o+2]-n[o],f=a[o],m=a[o+2]-f,v=i[o],g=i[o+2]-v;d[o]=2*l/u*m/g,h[o]=2*(s-c)/u*m/g}p[1]=2*t.pixelRatio/(i[3]-i[1]),p[0]=p[1]*(i[3]-i[1])/(i[2]-i[0]),e.uniforms.dataScale=d,e.uniforms.dataShift=h,e.uniforms.textScale=p,this.vbo.bind(),e.attributes.textCoordinate.pointer()}),m.update=function(t){var e,r,n,i,o,s=[],l=t.ticks,c=t.bounds;for(o=0;o<2;++o){var u=[Math.floor(s.length/3)],f=[-1/0],h=l[o];for(e=0;e=0){var m=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(m,e[1],m,e[3],d[p],h[p]):o.drawLine(e[0],m,e[2],m,d[p],h[p])}}for(p=0;p=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},c.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},c.removeObject=function(t){for(var e=this.objects,r=0;r0&&0===L[e-1];)L.pop(),C.pop().dispose()}window.addEventListener("resize",j),N.update=function(t){e||(t=t||{},P=!0,z=!0)},N.add=function(t){e||(t.axes=k,E.push(t),S.push(-1),P=!0,z=!0,B())},N.remove=function(t){if(!e){var r=E.indexOf(t);r<0||(E.splice(r,1),S.pop(),P=!0,z=!0,B())}},N.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",j),r.removeEventListener("webglcontextlost",q),N.mouseListener.enabled=!1,!N.contextLost)){k.dispose(),T.dispose();for(var t=0;tb.distance)continue;for(var u=0;u0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function m(t){return"boolean"!=typeof t||t}},{"./lib/shader":209,"3d-view-controls":39,"a-big-triangle":42,"gl-axes3d":157,"gl-axes3d/properties":164,"gl-fbo":171,"gl-mat4/perspective":189,"gl-select-static":219,"gl-spikes3d":229,"is-mobile":265,"mouse-change":424}],211:[function(t,e,r){var n=t("glslify");r.pointVertex=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]),r.pointFragment=n(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]),r.pickVertex=n(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]),r.pickFragment=n(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"])},{glslify:253}],212:[function(t,e,r){"use strict";var n=t("gl-shader"),i=t("gl-buffer"),a=t("typedarray-pool"),o=t("./lib/shader");function s(t,e,r,n,i){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=i,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}e.exports=function(t,e){var r=t.gl,a=i(r),l=i(r),c=n(r,o.pointVertex,o.pointFragment),u=n(r,o.pickVertex,o.pickFragment),f=new s(t,a,l,c,u);return f.update(e),t.addObject(f),f};var l,c,u=s.prototype;u.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},u.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,i=t.positions instanceof Float32Array,o=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,s=t.positions,l=i?s:a.mallocFloat32(s.length),c=o?t.idToIndex:a.mallocInt32(n);if(i||l.set(s),!o)for(l.set(s),e=0;e>>1;for(r=0;r=e[0]&&a<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,i),u=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(s,.33333)));l[0]=2/a,l[4]=2/o,l[6]=-2*i[0]/a-1,l[7]=-2*i[1]/o-1,this.offsetBuffer.bind(),r.bind(),r.attributes.position.pointer(),r.uniforms.matrix=l,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointCloud=u<5,r.uniforms.pointSize=u,r.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),e&&(c[0]=255&t,c[1]=t>>8&255,c[2]=t>>16&255,c[3]=t>>24&255,this.pickBuffer.bind(),r.attributes.pickId.pointer(n.UNSIGNED_BYTE),r.uniforms.pickOffset=c,this.pickOffset=t);var f=n.getParameter(n.BLEND),h=n.getParameter(n.DITHER);return f&&!this.blend&&n.disable(n.BLEND),h&&n.disable(n.DITHER),n.drawArrays(n.POINTS,0,this.pointCount),f&&!this.blend&&n.enable(n.BLEND),h&&n.enable(n.DITHER),t+this.pointCount}),u.draw=u.unifiedDraw,u.drawPick=u.unifiedDraw,u.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(r=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":211,"gl-buffer":165,"gl-shader":220,"typedarray-pool":534}],213:[function(t,e,r){e.exports=function(t,e,r,n){var i,a,o,s,l,c=e[0],u=e[1],f=e[2],h=e[3],d=r[0],p=r[1],m=r[2],v=r[3];(a=c*d+u*p+f*m+h*v)<0&&(a=-a,d=-d,p=-p,m=-m,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*c+l*d,t[1]=s*u+l*p,t[2]=s*f+l*m,t[3]=s*h+l*v,t}},{}],214:[function(t,e,r){"use strict";var n=t("vectorize-text");e.exports=function(t,e){var r=i[e];r||(r=i[e]={});if(t in r)return r[t];for(var a=n(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=n(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-1/0,-1/0]],l=0;l=1)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var p=[0,0],m=[0,0,0],v=[0,0,0],g=[0,0,0,1],y=[0,0,0,1],b=c.slice(),x=[0,0,0],_=[[0,0,0],[0,0,0]];function w(t){return t[0]=t[1]=t[2]=0,t}function M(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function k(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function A(t,e,r,n,i){var a,s=e.axesProject,l=e.gl,u=t.uniforms,h=r.model||c,d=r.view||c,A=r.projection||c,T=e.axesBounds,E=function(t){for(var e=_,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);a=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],p[0]=2/l.drawingBufferWidth,p[1]=2/l.drawingBufferHeight,t.bind(),u.view=d,u.projection=A,u.screenSize=p,u.highlightId=e.highlightId,u.highlightScale=e.highlightScale,u.clipBounds=E,u.pickGroup=e.pickId/255,u.pixelRatio=e.pixelRatio;for(var S=0;S<3;++S)if(s[S]&&e.projectOpacity[S]<1===n){u.scale=e.projectScale[S],u.opacity=e.projectOpacity[S];for(var L=b,C=0;C<16;++C)L[C]=0;for(C=0;C<4;++C)L[5*C]=1;L[5*S]=0,a[S]<0?L[12+S]=T[0][S]:L[12+S]=T[1][S],o(L,h,L),u.model=L;var P=(S+1)%3,z=(S+2)%3,O=w(m),D=w(v);O[P]=1,D[z]=1;var I=f(0,0,0,M(g,O)),R=f(0,0,0,M(y,D));if(Math.abs(I[1])>Math.abs(R[1])){var N=I;I=R,R=N,N=O,O=D,D=N;var F=P;P=z,z=F}I[0]<0&&(O[P]=-1),R[1]>0&&(D[z]=-1);var j=0,B=0;for(C=0;C<4;++C)j+=Math.pow(h[4*P+C],2),B+=Math.pow(h[4*z+C],2);O[P]/=Math.sqrt(j),D[z]/=Math.sqrt(B),u.axes[0]=O,u.axes[1]=D,u.fragClipBounds[0]=k(x,E[0],S,-1e8),u.fragClipBounds[1]=k(x,E[1],S,1e8),e.vao.draw(l.TRIANGLES,e.vertexCount),e.lineWidth>0&&(l.lineWidth(e.lineWidth),e.vao.draw(l.LINES,e.lineVertexCount,e.vertexCount))}}var T=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function E(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||c,s.view=n.view||c,s.projection=n.projection||c,p[0]=2/o.drawingBufferWidth,p[1]=2/o.drawingBufferHeight,s.screenSize=p,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=T,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}A(e,r,n,i),r.vao.unbind()}d.draw=function(t){E(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!1,!1)},d.drawTransparent=function(t){E(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!0,!1)},d.drawPick=function(t){E(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,!1,!0)},d.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},d.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},d.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",o=t.alignment||[0,0],s=[1/0,1/0,1/0],c=[-1/0,-1/0,-1/0],u=t.glyph,f=t.color,h=t.size,d=t.angle,p=t.lineColor,m=0,v=0,g=0,y=n.length;t:for(var b=0;b0&&(C[0]=-o[0]*(1+k[0][0]));var q=w.cells,H=w.positions;for(_=0;_0){var g=r*u;o.drawBox(f-g,h-g,d+g,h+g,a),o.drawBox(f-g,p-g,d+g,p+g,a),o.drawBox(f-g,h-g,f+g,p+g,a),o.drawBox(d-g,h-g,d+g,p+g,a)}}}},s.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},s.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":217,"gl-buffer":165,"gl-shader":220}],219:[function(t,e,r){"use strict";e.exports=function(t,e){var r=n(t,e),a=i.mallocUint8(e[0]*e[1]*4);return new l(t,r,a)};var n=t("gl-fbo"),i=t("typedarray-pool"),a=t("ndarray"),o=t("bit-twiddle").nextPow2,s=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(_inline_46_arg0_<255||_inline_46_arg1_<255||_inline_46_arg2_<255||_inline_46_arg3_<255){var _inline_46_l=_inline_46_arg4_-_inline_46_arg6_[0],_inline_46_a=_inline_46_arg5_-_inline_46_arg6_[1],_inline_46_f=_inline_46_l*_inline_46_l+_inline_46_a*_inline_46_a;_inline_46_fthis.buffer.length){i.free(this.buffer);for(var n=this.buffer=i.mallocUint8(o(r*e*4)),a=0;ar)for(t=r;te)for(t=e;t=0){for(var M=0|w.type.charAt(w.type.length-1),k=new Array(M),A=0;A=0;)T+=1;_[y]=T}var E=new Array(r.length);function S(){h.program=o.program(d,h._vref,h._fref,x,_);for(var t=0;t=0){var p=h.charCodeAt(h.length-1)-48;if(p<2||p>4)throw new n("","Invalid data type for attribute "+f+": "+h);o(t,e,d[0],i,p,a,f)}else{if(!(h.indexOf("mat")>=0))throw new n("","Unknown data type for attribute "+f+": "+h);var p=h.charCodeAt(h.length-1)-48;if(p<2||p>4)throw new n("","Invalid data type for attribute "+f+": "+h);s(t,e,d,i,p,a,f)}}}return a};var n=t("./GLError");function i(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var a=i.prototype;function o(t,e,r,n,a,o,s){for(var l=["gl","v"],c=[],u=0;u4)throw new i("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+a+"fv(locations["+e+"],false,obj"+t+")"}throw new i("","Unknown uniform data type for "+name+": "+r)}var a=r.charCodeAt(r.length-1)-48;if(a<2||a>4)throw new i("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+a+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+a+"fv(locations["+e+"],obj"+t+")";default:throw new i("","Unrecognized data type for vector "+name+": "+r)}}}function c(e){for(var n=["return function updateProperty(obj){"],i=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),a=0;a4)throw new i("","Invalid data type");return"b"===t.charAt(0)?o(r,!1):o(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new i("","Invalid uniform dimension type for matrix "+name+": "+t);return o(r*r,0)}throw new i("","Unknown uniform data type for "+name+": "+t)}}(r[u].type);var d}function f(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var c=1;c1)for(var l=0;l 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n //decide how to interpolate color \u2014 in vertex or in fragment\n vec4 surfaceColor = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + step(.5, vertexColor) * vColor;\n\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"]),s=i(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n vColor = texture2D(colormap, vec2(value, value));\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n"]),l=i(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"]);r.createShader=function(t){var e=n(t,a,o,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,a,l,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,s,o,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,s,l,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":220,glslify:231}],231:[function(t,e,r){arguments[4][169][0].apply(r,arguments)},{dup:169}],232:[function(t,e,r){"use strict";e.exports=function(t){var e=t.gl,r=y(e),n=x(e),s=b(e),l=_(e),c=i(e),u=a(e,[{buffer:c,size:4,stride:w,offset:0},{buffer:c,size:3,stride:w,offset:16},{buffer:c,size:3,stride:w,offset:28}]),f=i(e),h=a(e,[{buffer:f,size:4,stride:20,offset:0},{buffer:f,size:1,stride:20,offset:16}]),d=i(e),p=a(e,[{buffer:d,size:2,type:e.FLOAT}]),m=o(e,1,T,e.RGBA,e.UNSIGNED_BYTE);m.minFilter=e.LINEAR,m.magFilter=e.LINEAR;var v=new E(e,[0,0],[[0,0,0],[0,0,0]],r,n,c,u,m,s,l,f,h,d,p),g={levels:[[],[],[]]};for(var M in t)g[M]=t[M];return g.colormap=g.colormap||"jet",v.update(g),v};var n=t("bit-twiddle"),i=t("gl-buffer"),a=t("gl-vao"),o=t("gl-texture2d"),s=t("typedarray-pool"),l=t("colormap"),c=t("ndarray-ops"),u=t("ndarray-pack"),f=t("ndarray"),h=t("surface-nets"),d=t("gl-mat4/multiply"),p=t("gl-mat4/invert"),m=t("binary-search-bounds"),v=t("ndarray-gradient"),g=t("./lib/shaders"),y=g.createShader,b=g.createContourShader,x=g.createPickShader,_=g.createPickContourShader,w=40,M=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],k=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],A=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;t<3;++t){var e=A[t],r=(t+2)%3;e[(t+1)%3+0]=1,e[r+3]=1,e[t+6]=1}}();var T=256;function E(t,e,r,n,i,a,o,l,c,u,h,d,p,m){this.gl=t,this.shape=e,this.bounds=r,this.intensityBounds=[],this._shader=n,this._pickShader=i,this._coordinateBuffer=a,this._vao=o,this._colorMap=l,this._contourShader=c,this._contourPickShader=u,this._contourBuffer=h,this._contourVAO=d,this._contourOffsets=[[],[],[]],this._contourCounts=[[],[],[]],this._vertexCount=0,this._pickResult=new function(t,e,r,n,i){this.position=t,this.index=e,this.uv=r,this.level=n,this.dataCoordinate=i}([0,0,0],[0,0],[0,0],[0,0,0],[0,0,0]),this._dynamicBuffer=p,this._dynamicVAO=m,this._dynamicOffsets=[0,0,0],this._dynamicCounts=[0,0,0],this.contourWidth=[1,1,1],this.contourLevels=[[1],[1],[1]],this.contourTint=[0,0,0],this.contourColor=[[.5,.5,.5,1],[.5,.5,.5,1],[.5,.5,.5,1]],this.showContour=!0,this.showSurface=!0,this.enableHighlight=[!0,!0,!0],this.highlightColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.highlightTint=[1,1,1],this.highlightLevel=[-1,-1,-1],this.enableDynamic=[!0,!0,!0],this.dynamicLevel=[NaN,NaN,NaN],this.dynamicColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.dynamicTint=[1,1,1],this.dynamicWidth=[1,1,1],this.axesBounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.surfaceProject=[!1,!1,!1],this.contourProject=[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],this.colorBounds=[!1,!1],this._field=[f(s.mallocFloat(1024),[0,0]),f(s.mallocFloat(1024),[0,0]),f(s.mallocFloat(1024),[0,0])],this.pickId=1,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.snapToData=!1,this.opacity=1,this.lightPosition=[10,1e4,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.vertexColor=0,this.dirty=!0}var S=E.prototype;S.isTransparent=function(){return this.opacity<1},S.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},S.pickSlots=1,S.setPickBase=function(t){this.pickId=t};var L=[0,0,0],C={showSurface:!1,showContour:!1,projections:[M.slice(),M.slice(),M.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function P(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||L,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=C.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],d(l,t.model,l);var c=C.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)c[i][n]=t.clipBounds[i][n];c[0][r]=-1e8,c[1][r]=1e8}return C.showSurface=o,C.showContour=s,C}var z={model:M,view:M,projection:M,inverseModel:M.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},O=M.slice(),D=[1,0,0,0,1,0,0,0,1];function I(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=z;n.model=t.model||M,n.view=t.view||M,n.projection=t.projection||M,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=p(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=D,n.vertexColor=this.vertexColor;var s=O;for(d(s,n.view,n.model),d(s,n.projection,s),p(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var c=s[12+i];for(o=0;o<3;++o)c+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=c/l}var u=P(n,this);if(u.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=u.projections[i],this._shader.uniforms.clipBounds=u.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(u.showContour&&!e){var f=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,f.bind(),f.uniforms=n;var h=this._contourVAO;for(h.bind(),i=0;i<3;++i)for(f.uniforms.permutation=A[i],r.lineWidth(this.contourWidth[i]),o=0;o>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var c=r.position;c[0]=c[1]=c[2]=0;for(var u=0;u<2;++u)for(var f=u?a:1-a,h=0;h<2;++h)for(var d=i+u,p=s+h,v=f*(h?l:1-l),g=0;g<3;++g)c[g]+=this._field[g].get(d,p)*v;for(var y=this._pickResult.level,b=0;b<3;++b)if(y[b]=m.le(this.contourLevels[b],c[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]Math.abs(_-c[b])&&(y[b]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],g=0;g<3;++g)r.dataCoordinate[g]=this._field[g].get(r.index[0],r.index[1]);return r},S.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=F(t.contourWidth,Number)),"showContour"in t&&(this.showContour=F(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=F(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=B(t.contourColor)),"contourProject"in t&&(this.contourProject=F(t.contourProject,function(t){return F(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=B(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=F(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=F(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var i=(e.shape[0]+2)*(e.shape[1]+2);i>this._field[2].data.length&&(s.freeFloat(this._field[2].data),this._field[2].data=s.mallocFloat(n.nextPow2(i))),this._field[2]=f(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),N(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;o<2;++o)this._field[2].size>this._field[o].data.length&&(s.freeFloat(this._field[o].data),this._field[o].data=s.mallocFloat(this._field[2].size)),this._field[o]=f(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var d=t.coords;if(!Array.isArray(d)||3!==d.length)throw new Error("gl-surface: invalid coordinates for x/y");for(o=0;o<2;++o){var p=d[o];for(x=0;x<2;++x)if(p.shape[x]!==a[x])throw new Error("gl-surface: coords have incorrect shape");N(this._field[o],p)}}else if(t.ticks){var m=t.ticks;if(!Array.isArray(m)||2!==m.length)throw new Error("gl-surface: invalid ticks");for(o=0;o<2;++o){var g=m[o];if((Array.isArray(g)||g.length)&&(g=f(g)),g.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var y=f(g.data,a);y.stride[o]=g.stride[0],y.stride[1^o]=0,N(this._field[o],y)}}else{for(o=0;o<2;++o){var b=[0,0];b[o]=1,this._field[o]=f(this._field[o].data,[a[0]+2,a[1]+2],b,0)}this._field[0].set(0,0,0);for(var x=0;x0){for(var Mt=0;Mt<5;++Mt)nt.pop();Y-=1}continue t}nt.push(st[0],st[1],ut[0],ut[1],st[2]),Y+=1}}ot.push(Y)}this._contourOffsets[it]=at,this._contourCounts[it]=ot}var kt=s.mallocFloat(nt.length);for(o=0;os||o[1]<0||o[1]>s)throw new Error("gl-texture2d: Invalid texture size");var l=p(o,e.stride.slice()),c=0;"float32"===r?c=t.FLOAT:"float64"===r?(c=t.FLOAT,l=!1,r="float32"):"uint8"===r?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,l=!1,r="uint8");var f,d,v=0;if(2===o.length)v=t.LUMINANCE,o=[o[0],o[1],1],e=n(e.data,o,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==o.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===o[2])v=t.ALPHA;else if(2===o[2])v=t.LUMINANCE_ALPHA;else if(3===o[2])v=t.RGB;else{if(4!==o[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");v=t.RGBA}}c!==t.FLOAT||t.getExtension("OES_texture_float")||(c=t.UNSIGNED_BYTE,l=!1);var g=e.size;if(l)f=0===e.offset&&e.data.length===g?e.data:e.data.subarray(e.offset,e.offset+g);else{var y=[o[2],o[2]*o[0],1];d=a.malloc(g,r);var b=n(d,o,y,0);"float32"!==r&&"float64"!==r||c!==t.UNSIGNED_BYTE?i.assign(b,e):u(b,e),f=d.subarray(0,g)}var x=m(t);t.texImage2D(t.TEXTURE_2D,0,v,o[0],o[1],0,v,c,f),l||a.free(d);return new h(t,x,o[0],o[1],v,c)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")};var o=null,s=null,l=null;function c(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var u=function(t,e){i.muls(t,e,255)};function f(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function h(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var d=h.prototype;function p(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function m(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function v(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=m(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new h(t,o,e,r,n,i)}Object.defineProperties(d,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&o.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),s.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&o.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),s.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),l.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),l.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(l.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return f(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return f(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,f(this,this._shape[0],t),t}}}),d.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},d.dispose=function(){this.gl.deleteTexture(this.handle)},d.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},d.setPixels=function(t,e,r,o){var s=this.gl;this.bind(),Array.isArray(e)?(o=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),o=o||0;var l=c(t)?t:t.raw;if(l){this._mipLevels.indexOf(o)<0?(s.texImage2D(s.TEXTURE_2D,0,this.format,this.format,this.type,l),this._mipLevels.push(o)):s.texSubImage2D(s.TEXTURE_2D,o,e,r,this.format,this.type,l)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>o||r+t.shape[0]>this._shape[0]>>>o||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,o,s,l,c,f){var h=f.dtype,d=f.shape.slice();if(d.length<2||d.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var m=0,v=0,g=p(d,f.stride.slice());"float32"===h?m=t.FLOAT:"float64"===h?(m=t.FLOAT,g=!1,h="float32"):"uint8"===h?m=t.UNSIGNED_BYTE:(m=t.UNSIGNED_BYTE,g=!1,h="uint8");if(2===d.length)v=t.LUMINANCE,d=[d[0],d[1],1],f=n(f.data,d,[f.stride[0],f.stride[1],1],f.offset);else{if(3!==d.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===d[2])v=t.ALPHA;else if(2===d[2])v=t.LUMINANCE_ALPHA;else if(3===d[2])v=t.RGB;else{if(4!==d[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");v=t.RGBA}d[2]}v!==t.LUMINANCE&&v!==t.ALPHA||s!==t.LUMINANCE&&s!==t.ALPHA||(v=s);if(v!==s)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=f.size,b=c.indexOf(o)<0;b&&c.push(o);if(m===l&&g)0===f.offset&&f.data.length===y?b?t.texImage2D(t.TEXTURE_2D,o,s,d[0],d[1],0,s,l,f.data):t.texSubImage2D(t.TEXTURE_2D,o,e,r,d[0],d[1],s,l,f.data):b?t.texImage2D(t.TEXTURE_2D,o,s,d[0],d[1],0,s,l,f.data.subarray(f.offset,f.offset+y)):t.texSubImage2D(t.TEXTURE_2D,o,e,r,d[0],d[1],s,l,f.data.subarray(f.offset,f.offset+y));else{var x;x=l===t.FLOAT?a.mallocFloat32(y):a.mallocUint8(y);var _=n(x,d,[d[2],d[2]*d[0],1]);m===t.FLOAT&&l===t.UNSIGNED_BYTE?u(_,f):i.assign(_,f),b?t.texImage2D(t.TEXTURE_2D,o,s,d[0],d[1],0,s,l,x.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,o,e,r,d[0],d[1],s,l,x.subarray(0,y)),l===t.FLOAT?a.freeFloat32(x):a.freeUint8(x)}}(s,e,r,o,this.format,this.type,this._mipLevels,t)}}},{ndarray:439,"ndarray-ops":433,"typedarray-pool":534}],234:[function(t,e,r){"use strict";e.exports=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t}},{}],243:[function(t,e,r){e.exports=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}},{}],244:[function(t,e,r){e.exports=function(t,e,r,a){return n[0]=a,n[1]=r,n[2]=e,n[3]=t,i[0]};var n=new Uint8Array(4),i=new Float32Array(n.buffer)},{}],245:[function(t,e,r){var n=t("glsl-tokenizer"),i=t("atob-lite");e.exports=function(t){for(var e=Array.isArray(t)?t:n(t),r=0;r0)continue;r=t.slice(0,1).join("")}return N(r),P+=r.length,(E=E.slice(r.length)).length}}function H(){return/[^a-fA-F0-9]/.test(e)?(N(E.join("")),T=l,k):(E.push(e),r=e,k+1)}function G(){return"."===e?(E.push(e),T=m,r=e,k+1):/[eE]/.test(e)?(E.push(e),T=m,r=e,k+1):"x"===e&&1===E.length&&"0"===E[0]?(T=_,E.push(e),r=e,k+1):/[^\d]/.test(e)?(N(E.join("")),T=l,k):(E.push(e),r=e,k+1)}function Y(){return"f"===e&&(E.push(e),r=e,k+=1),/[eE]/.test(e)?(E.push(e),r=e,k+1):"-"===e&&/[eE]/.test(r)?(E.push(e),r=e,k+1):/[^\d]/.test(e)?(N(E.join("")),T=l,k):(E.push(e),r=e,k+1)}function W(){if(/[^\d\w_]/.test(e)){var t=E.join("");return T=R.indexOf(t)>-1?y:I.indexOf(t)>-1?g:v,N(E.join("")),T=l,k}return E.push(e),r=e,k+1}};var n=t("./lib/literals"),i=t("./lib/operators"),a=t("./lib/builtins"),o=t("./lib/literals-300es"),s=t("./lib/builtins-300es"),l=999,c=9999,u=0,f=1,h=2,d=3,p=4,m=5,v=6,g=7,y=8,b=9,x=10,_=11,w=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":248,"./lib/builtins-300es":247,"./lib/literals":250,"./lib/literals-300es":249,"./lib/operators":251}],247:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"])},{"./builtins":248}],248:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],249:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":250}],250:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],251:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],252:[function(t,e,r){var n=t("./index");e.exports=function(t,e){var r=n(e),i=[];return i=(i=i.concat(r(t))).concat(r(null))}},{"./index":246}],253:[function(t,e,r){arguments[4][169][0].apply(r,arguments)},{dup:169}],254:[function(t,e,r){"use strict";e.exports=i;var n=3;function i(t,e,r){var i=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var a=new Int32Array(this.arrayBuffer);t=a[0],e=a[1],r=a[2],this.d=e+2*r;for(var o=0;o=c[h+0]&&n>=c[h+1]?(o[f]=!0,a.push(l[f])):o[f]=!1}}},i.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),c=this._convertToCellCoord(r),u=this._convertToCellCoord(n),f=s;f<=c;f++)for(var h=l;h<=u;h++){var d=this.d*h+f;if(i.call(this,t,e,r,n,d,a,o))return}},i.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},i.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=n+this.cells.length+1+1,r=0,i=0;i>1,u=-7,f=r?i-1:0,h=r?-1:1,d=t[e+f];for(f+=h,a=d&(1<<-u)-1,d>>=-u,u+=s;u>0;a=256*a+t[e+f],f+=h,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+f],f+=h,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),a-=c}return(d?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,c=8*a-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+f>=1?h/l:h*Math.pow(2,1-f))*l>=2&&(o++,l/=2),o+f>=u?(s=0,o=u):o+f>=1?(s=(e*l-1)*Math.pow(2,i),o+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,c-=8);t[r+d-p]|=128*m}},{}],258:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(r<=i)throw new Error("Must input at least d+1 points");var o=t.slice(0,i+1),s=n.apply(void 0,o);if(0===s)throw new Error("Input not in general position");for(var l=new Array(i+1),u=0;u<=i;++u)l[u]=u;s<0&&(l[0]=1,l[1]=0);for(var f=new a(l,new Array(i+1),!1),h=f.adjacent,d=new Array(i+2),u=0;u<=i;++u){for(var p=l.slice(),m=0;m<=i;++m)m===u&&(p[m]=-1);var v=p[0];p[0]=p[1],p[1]=v;var g=new a(p,new Array(i+1),!0);h[u]=g,d[u]=g}d[i+1]=f;for(var u=0;u<=i;++u)for(var p=h[u].vertices,y=h[u].adjacent,m=0;m<=i;++m){var b=p[m];if(b<0)y[m]=f;else for(var x=0;x<=i;++x)h[x].vertices.indexOf(b)<0&&(y[m]=h[x])}for(var _=new c(i,o,d),w=!!e,u=i+1;u0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var i=new Function("test",e.join("")),a=n[t+1];return a||(a=n),i(a)}(t)),this.orient=a}var u=c.prototype;u.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var c=s[l];if(c.boundary&&!(c.lastVisited<=-n)){for(var u=c.vertices,f=0;f<=r;++f){var h=u[f];i[f]=h<0?e:a[h]}var d=this.orient();if(d>0)return c;c.lastVisited=-n,0===d&&o.push(c)}}}return null},u.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,c=s.adjacent,u=0;u<=n;++u)a[u]=i[l[u]];s.lastVisited=r;for(u=0;u<=n;++u){var f=c[u];if(!(f.lastVisited>=r)){var h=a[u];a[u]=t;var d=this.orient();if(a[u]=h,d<0){s=f;continue t}f.boundary?f.lastVisited=-r:f.lastVisited=r}}return}return s},u.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,l=this.tuple,c=this.interior,u=this.simplices,f=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,c.push(e);for(var h=[];f.length>0;){var d=(e=f.pop()).vertices,p=e.adjacent,m=d.indexOf(r);if(!(m<0))for(var v=0;v<=n;++v)if(v!==m){var g=p[v];if(g.boundary&&!(g.lastVisited>=r)){var y=g.vertices;if(g.lastVisited!==-r){for(var b=0,x=0;x<=n;++x)y[x]<0?(b=x,l[x]=t):l[x]=i[y[x]];if(this.orient()>0){y[b]=r,g.boundary=!1,c.push(g),f.push(g),g.lastVisited=r;continue}g.lastVisited=-r}var _=g.adjacent,w=d.slice(),M=p.slice(),k=new a(w,M,!0);u.push(k);var A=_.indexOf(e);if(!(A<0)){_[A]=k,M[m]=g,w[v]=-1,M[v]=e,p[v]=k,k.flip();for(x=0;x<=n;++x){var T=w[x];if(!(T<0||T===r)){for(var E=new Array(n-1),S=0,L=0;L<=n;++L){var C=w[L];C<0||L===x||(E[S++]=C)}h.push(new o(E,k,x))}}}}}}h.sort(s);for(v=0;v+1=0?o[l++]=s[u]:c=1&u;if(c===(1&t)){var f=o[0];o[0]=o[1],o[1]=f}e.push(o)}}return e}},{"robust-orientation":495,"simplicial-complex":506}],259:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=0,a=1;function o(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}e.exports=function(t){if(!t||0===t.length)return new b(null);return new b(y(t))};var s=o.prototype;function l(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function c(t,e){var r=y(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function u(t,e){var r=t.intervals([]);r.push(e),c(t,r)}function f(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?i:(r.splice(n,1),c(t,r),a)}function h(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function p(t,e){for(var r=0;r>1],i=[],a=[],s=[];for(r=0;r3*(e+1)?u(this,t):this.left.insert(t):this.left=y([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?u(this,t):this.right.insert(t):this.right=y([t]);else{var r=n.ge(this.leftPoints,t,v),i=n.ge(this.rightPoints,t,g);this.leftPoints.splice(r,0,t),this.rightPoints.splice(i,0,t)}},s.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?f(this,t):2===(c=this.left.remove(t))?(this.left=null,this.count-=1,a):(c===a&&(this.count-=1),c):i}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:i;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,o=this.left;o.right;)r=o,o=o.right;if(r===this)o.right=this.right;else{var s=this.left;c=this.right;r.count-=o.count,r.right=o.left,o.left=s,o.right=c}l(this,o),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?l(this,this.left):l(this,this.right);return a}for(s=n.ge(this.leftPoints,t,v);s3*(e-1)?f(this,t):2===(c=this.right.remove(t))?(this.right=null,this.count-=1,a):(c===a&&(this.count-=1),c):i;var c}},s.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return d(this.rightPoints,t,e)}return p(this.leftPoints,e)},s.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?d(this.rightPoints,t,r):p(this.leftPoints,r)};var x=b.prototype;x.insert=function(t){this.root?this.root.insert(t):this.root=new o(t[0],null,null,[t],[t])},x.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==i}return!1},x.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},x.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(x,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(x,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":70}],260:[function(t,e,r){"use strict";e.exports=function(t,e){e=e||new Array(t.length);for(var r=0;r4))}},{}],268:[function(t,e,r){"use strict";var n=t("./sort"),i=t("./range"),a=t("./within");function o(t,e,r,i,a){e=e||s,r=r||l,a=a||Array,this.nodeSize=i||64,this.points=t,this.ids=new a(t.length),this.coords=new a(2*t.length);for(var o=0;o=r&&s<=i&&l>=n&&l<=a&&u.push(t[p]);else{var m=Math.floor((d+h)/2);s=e[2*m],l=e[2*m+1],s>=r&&s<=i&&l>=n&&l<=a&&u.push(t[m]);var v=(f+1)%2;(0===f?r<=s:n<=l)&&(c.push(d),c.push(m-1),c.push(v)),(0===f?i>=s:a>=l)&&(c.push(m+1),c.push(h),c.push(v))}}return u}},{}],270:[function(t,e,r){"use strict";function n(t,e,r,n){i(t,r,n),i(e,2*r,2*n),i(e,2*r+1,2*n+1)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=function t(e,r,i,a,o,s){if(o-a<=i)return;var l=Math.floor((a+o)/2);!function t(e,r,i,a,o,s){for(;o>a;){if(o-a>600){var l=o-a+1,c=i-a+1,u=Math.log(l),f=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*f*(l-f)/l)*(c-l/2<0?-1:1),d=Math.max(a,Math.floor(i-c*f/l+h)),p=Math.min(o,Math.floor(i+(l-c)*f/l+h));t(e,r,i,d,p,s)}var m=r[2*i+s],v=a,g=o;for(n(e,r,a,i),r[2*o+s]>m&&n(e,r,a,o);vm;)g--}r[2*a+s]===m?n(e,r,a,g):n(e,r,++g,o),g<=i&&(a=g+1),i<=g&&(o=g-1)}}(e,r,l,a,o,s%2);t(e,r,i,a,l-1,s+1);t(e,r,i,l+1,o,s+1)}},{}],271:[function(t,e,r){"use strict";function n(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}e.exports=function(t,e,r,i,a,o){var s=[0,t.length-1,0],l=[],c=a*a;for(;s.length;){var u=s.pop(),f=s.pop(),h=s.pop();if(f-h<=o)for(var d=h;d<=f;d++)n(e[2*d],e[2*d+1],r,i)<=c&&l.push(t[d]);else{var p=Math.floor((h+f)/2),m=e[2*p],v=e[2*p+1];n(m,v,r,i)<=c&&l.push(t[p]);var g=(u+1)%2;(0===u?r-a<=m:i-a<=v)&&(s.push(h),s.push(p-1),s.push(g)),(0===u?r+a>=m:i+a>=v)&&(s.push(p+1),s.push(f),s.push(g))}}return l}},{}],272:[function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n(t,e);this.nodeSize=e||64,this.coords=t.slice();var r=Math.floor(t.length/2);this.ids=Array(r);for(var i=0;ii;){if(o-i>600){var l=o-i+1,c=n-i+1,u=Math.log(l),f=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*f*(l-f)/l)*(c-l/2<0?-1:1),d=Math.max(i,Math.floor(n-c*f/l+h)),p=Math.min(o,Math.floor(n+(l-c)*f/l+h));t(e,r,n,d,p,s)}var m=r[2*n+s],v=i,g=o;for(a(e,r,i,n),r[2*o+s]>m&&a(e,r,i,o);vm;)g--}r[2*i+s]===m?a(e,r,i,g):a(e,r,++g,o),g<=n&&(i=g+1),n<=g&&(o=g-1)}}(e,r,l,i,o,s%2);t(e,r,n,i,l-1,s+1);t(e,r,n,l+1,o,s+1)}(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0)}function i(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}function a(t,e,r,n){o(t,r,n),o(e,2*r,2*n),o(e,2*r+1,2*n+1)}function o(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=n,n.prototype.range=function(t,e,r,n){for(var i,a,o=this.ids,s=this.coords,l=this.nodeSize,c=[0,o.length-1,0],u=[];c.length;){var f=c.pop(),h=c.pop(),d=c.pop();if(h-d<=l)for(var p=d;p<=h;p++)i=s[2*p],a=s[2*p+1],i>=t&&i<=r&&a>=e&&a<=n&&u.push(o[p]);else{var m=Math.floor((d+h)/2);i=s[2*m],a=s[2*m+1],i>=t&&i<=r&&a>=e&&a<=n&&u.push(o[m]);var v=(f+1)%2;(0===f?t<=i:e<=a)&&(c.push(d),c.push(m-1),c.push(v)),(0===f?r>=i:n>=a)&&(c.push(m+1),c.push(h),c.push(v))}}return u},n.prototype.within=function(t,e,r){for(var n=this.ids,a=this.coords,o=this.nodeSize,s=[0,n.length-1,0],l=[],c=r*r;s.length;){var u=s.pop(),f=s.pop(),h=s.pop();if(f-h<=o)for(var d=h;d<=f;d++)i(a[2*d],a[2*d+1],t,e)<=c&&l.push(n[d]);else{var p=Math.floor((h+f)/2),m=a[2*p],v=a[2*p+1];i(m,v,t,e)<=c&&l.push(n[p]);var g=(u+1)%2;(0===u?t-r<=m:e-r<=v)&&(s.push(h),s.push(p-1),s.push(g)),(0===u?t+r>=m:e+r>=v)&&(s.push(p+1),s.push(f),s.push(g))}}return l}},{}],273:[function(t,e,r){e.exports=function(t,e,r){return t*(1-r)+e*r}},{}],274:[function(t,e,r){"use strict";function n(t,e){var r;if(c(t)){var l,u=t.stops&&"object"==typeof t.stops[0][0],f=u||void 0!==t.property,h=u||!f,d=t.type||e||"exponential";if("exponential"===d)l=o;else if("interval"===d)l=a;else if("categorical"===d)l=i;else{if("identity"!==d)throw new Error('Unknown function type "'+d+'"');l=s}if(u){for(var p={},m=[],v=0;v=t.stops.length||e<=t.stops[n][0]);)n++;return 0===n?t.stops[n][1]:n===t.stops.length?t.stops[n-1][1]:function t(e,r,n,i,a,o){return"function"==typeof a?function(){var s=a.apply(void 0,arguments),l=o.apply(void 0,arguments);return t(e,r,n,i,s,l)}:a.length?function(t,e,r,n,i,a){for(var o=[],s=0;s -1 and 1 => 1\n // In the texture normal, x is 0 if the normal points straight up/down and 1 if it's a round cap\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = mod(a_pos, 2.0);\n normal.y = sign(normal.y - 0.5);\n v_normal = normal;\n\n float inset = u_gapwidth + (u_gapwidth > 0.0 ? u_antialiasing : 0.0);\n float outset = u_gapwidth + u_linewidth * (u_gapwidth > 0.0 ? 2.0 : 1.0) + u_antialiasing;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset = u_offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n // Remove the texture normal bit of the position before scaling it with the\n // model/view matrix.\n gl_Position = u_matrix * vec4(floor(a_pos * 0.5) + (offset + dist) / u_ratio, 0.0, 1.0);\n\n // position of y on the screen\n float y = gl_Position.y / gl_Position.w;\n\n // how much features are squished in the y direction by the tilt\n float squish_scale = length(a_extrude) / length(u_antialiasingmatrix * a_extrude);\n\n // how much features are squished in all directions by the perspectiveness\n float perspective_scale = 1.0 / (1.0 - min(y * u_extra, 0.9));\n\n v_linewidth = vec2(outset, inset);\n v_gamma_scale = perspective_scale * squish_scale;\n}\n"},linepattern:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform float u_blur;\n\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform float u_fade;\nuniform float u_opacity;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_linewidth;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\nvoid main() {\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_linewidth.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_linewidth.t) or when fading out\n // (v_linewidth.s)\n float blur = u_blur * v_gamma_scale;\n float alpha = clamp(min(dist - (v_linewidth.t - blur), v_linewidth.s - dist) / blur, 0.0, 1.0);\n\n float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n float y_a = 0.5 + (v_normal.y * v_linewidth.s / u_pattern_size_a.y);\n float y_b = 0.5 + (v_normal.y * v_linewidth.s / u_pattern_size_b.y);\n vec2 pos_a = mix(u_pattern_tl_a, u_pattern_br_a, vec2(x_a, y_a));\n vec2 pos_b = mix(u_pattern_tl_b, u_pattern_br_b, vec2(x_b, y_b));\n\n vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n alpha *= u_opacity;\n\n gl_FragColor = color * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\nattribute vec2 a_pos;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform mediump float u_linewidth;\nuniform mediump float u_gapwidth;\nuniform mediump float u_antialiasing;\nuniform mediump float u_extra;\nuniform mat2 u_antialiasingmatrix;\nuniform mediump float u_offset;\n\nvarying vec2 v_normal;\nvarying vec2 v_linewidth;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\nvoid main() {\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n // We store the texture normals in the most insignificant bit\n // transform y so that 0 => -1 and 1 => 1\n // In the texture normal, x is 0 if the normal points straight up/down and 1 if it's a round cap\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = mod(a_pos, 2.0);\n normal.y = sign(normal.y - 0.5);\n v_normal = normal;\n\n float inset = u_gapwidth + (u_gapwidth > 0.0 ? u_antialiasing : 0.0);\n float outset = u_gapwidth + u_linewidth * (u_gapwidth > 0.0 ? 2.0 : 1.0) + u_antialiasing;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset = u_offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n // Remove the texture normal bit of the position before scaling it with the\n // model/view matrix.\n gl_Position = u_matrix * vec4(floor(a_pos * 0.5) + (offset + dist) / u_ratio, 0.0, 1.0);\n v_linesofar = a_linesofar;\n\n // position of y on the screen\n float y = gl_Position.y / gl_Position.w;\n\n // how much features are squished in the y direction by the tilt\n float squish_scale = length(a_extrude) / length(u_antialiasingmatrix * a_extrude);\n\n // how much features are squished in all directions by the perspectiveness\n float perspective_scale = 1.0 / (1.0 - min(y * u_extra, 0.9));\n\n v_linewidth = vec2(outset, inset);\n v_gamma_scale = perspective_scale * squish_scale;\n}\n"},linesdfpattern:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform lowp vec4 u_color;\nuniform lowp float u_opacity;\n\nuniform float u_blur;\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_linewidth;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\nvoid main() {\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_linewidth.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_linewidth.t) or when fading out\n // (v_linewidth.s)\n float blur = u_blur * v_gamma_scale;\n float alpha = clamp(min(dist - (v_linewidth.t - blur), v_linewidth.s - dist) / blur, 0.0, 1.0);\n\n float sdfdist_a = texture2D(u_image, v_tex_a).a;\n float sdfdist_b = texture2D(u_image, v_tex_b).a;\n float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n alpha *= smoothstep(0.5 - u_sdfgamma, 0.5 + u_sdfgamma, sdfdist);\n\n gl_FragColor = u_color * (alpha * u_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\nattribute vec2 a_pos;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform mediump float u_linewidth;\nuniform mediump float u_gapwidth;\nuniform mediump float u_antialiasing;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform float u_extra;\nuniform mat2 u_antialiasingmatrix;\nuniform mediump float u_offset;\n\nvarying vec2 v_normal;\nvarying vec2 v_linewidth;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\nvoid main() {\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n // We store the texture normals in the most insignificant bit\n // transform y so that 0 => -1 and 1 => 1\n // In the texture normal, x is 0 if the normal points straight up/down and 1 if it's a round cap\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = mod(a_pos, 2.0);\n normal.y = sign(normal.y - 0.5);\n v_normal = normal;\n\n float inset = u_gapwidth + (u_gapwidth > 0.0 ? u_antialiasing : 0.0);\n float outset = u_gapwidth + u_linewidth * (u_gapwidth > 0.0 ? 2.0 : 1.0) + u_antialiasing;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset = u_offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n // Remove the texture normal bit of the position before scaling it with the\n // model/view matrix.\n gl_Position = u_matrix * vec4(floor(a_pos * 0.5) + (offset + dist) / u_ratio, 0.0, 1.0);\n\n v_tex_a = vec2(a_linesofar * u_patternscale_a.x, normal.y * u_patternscale_a.y + u_tex_y_a);\n v_tex_b = vec2(a_linesofar * u_patternscale_b.x, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n // position of y on the screen\n float y = gl_Position.y / gl_Position.w;\n\n // how much features are squished in the y direction by the tilt\n float squish_scale = length(a_extrude) / length(u_antialiasingmatrix * a_extrude);\n\n // how much features are squished in all directions by the perspectiveness\n float perspective_scale = 1.0 / (1.0 - min(y * u_extra, 0.9));\n\n v_linewidth = vec2(outset, inset);\n v_gamma_scale = perspective_scale * squish_scale;\n}\n"},outline:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\n#pragma mapbox: define lowp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n #pragma mapbox: initialize lowp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = smoothstep(1.0, 0.0, dist);\n gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nattribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},outlinepattern:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform float u_opacity;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\nvoid main() {\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a, u_pattern_br_a, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b, u_pattern_br_b, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n // find distance to outline for alpha interpolation\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = smoothstep(1.0, 0.0, dist);\n \n\n gl_FragColor = mix(color1, color2, u_mix) * alpha * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n vec2 scaled_size_a = u_scale_a * u_pattern_size_a;\n vec2 scaled_size_b = u_scale_b * u_pattern_size_b;\n\n // the correct offset needs to be calculated.\n //\n // The offset depends on how many pixels are between the world origin and\n // the edge of the tile:\n // vec2 offset = mod(pixel_coord, size)\n //\n // At high zoom levels there are a ton of pixels between the world origin\n // and the edge of the tile. The glsl spec only guarantees 16 bits of\n // precision for highp floats. We need more than that.\n //\n // The pixel_coord is passed in as two 16 bit values:\n // pixel_coord_upper = floor(pixel_coord / 2^16)\n // pixel_coord_lower = mod(pixel_coord, 2^16)\n //\n // The offset is calculated in a series of steps that should preserve this precision:\n vec2 offset_a = mod(mod(mod(u_pixel_coord_upper, scaled_size_a) * 256.0, scaled_size_a) * 256.0 + u_pixel_coord_lower, scaled_size_a);\n vec2 offset_b = mod(mod(mod(u_pixel_coord_upper, scaled_size_b) * 256.0, scaled_size_b) * 256.0 + u_pixel_coord_lower, scaled_size_b);\n\n v_pos_a = (u_tile_units_to_pixels * a_pos + offset_a) / scaled_size_a;\n v_pos_b = (u_tile_units_to_pixels * a_pos + offset_b) / scaled_size_b;\n\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},pattern:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform float u_opacity;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a, u_pattern_br_a, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b, u_pattern_br_b, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n gl_FragColor = mix(color1, color2, u_mix) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n vec2 scaled_size_a = u_scale_a * u_pattern_size_a;\n vec2 scaled_size_b = u_scale_b * u_pattern_size_b;\n\n // the correct offset needs to be calculated.\n //\n // The offset depends on how many pixels are between the world origin and\n // the edge of the tile:\n // vec2 offset = mod(pixel_coord, size)\n //\n // At high zoom levels there are a ton of pixels between the world origin\n // and the edge of the tile. The glsl spec only guarantees 16 bits of\n // precision for highp floats. We need more than that.\n //\n // The pixel_coord is passed in as two 16 bit values:\n // pixel_coord_upper = floor(pixel_coord / 2^16)\n // pixel_coord_lower = mod(pixel_coord, 2^16)\n //\n // The offset is calculated in a series of steps that should preserve this precision:\n vec2 offset_a = mod(mod(mod(u_pixel_coord_upper, scaled_size_a) * 256.0, scaled_size_a) * 256.0 + u_pixel_coord_lower, scaled_size_a);\n vec2 offset_b = mod(mod(mod(u_pixel_coord_upper, scaled_size_b) * 256.0, scaled_size_b) * 256.0 + u_pixel_coord_lower, scaled_size_b);\n\n v_pos_a = (u_tile_units_to_pixels * a_pos + offset_a) / scaled_size_a;\n v_pos_b = (u_tile_units_to_pixels * a_pos + offset_b) / scaled_size_b;\n}\n"},raster:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform float u_opacity0;\nuniform float u_opacity1;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n // read and cross-fade colors from the main and parent tiles\n vec4 color0 = texture2D(u_image0, v_pos0);\n vec4 color1 = texture2D(u_image1, v_pos1);\n vec4 color = color0 * u_opacity0 + color1 * u_opacity1;\n vec3 rgb = color.rgb;\n\n // spin\n rgb = vec3(\n dot(rgb, u_spin_weights.xyz),\n dot(rgb, u_spin_weights.zxy),\n dot(rgb, u_spin_weights.yzx));\n\n // saturation\n float average = (color.r + color.g + color.b) / 3.0;\n rgb += (average - rgb) * u_saturation_factor;\n\n // contrast\n rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n // brightness\n vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb), color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos0 = (((a_texture_pos / 32767.0) - 0.5) / u_buffer_scale ) + 0.5;\n v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},icon:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform sampler2D u_texture;\nuniform sampler2D u_fadetexture;\nuniform lowp float u_opacity;\n\nvarying vec2 v_tex;\nvarying vec2 v_fade_tex;\n\nvoid main() {\n lowp float alpha = texture2D(u_fadetexture, v_fade_tex).a * u_opacity;\n gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nattribute vec2 a_pos;\nattribute vec2 a_offset;\nattribute vec2 a_texture_pos;\nattribute vec4 a_data;\n\n\n// matrix is for the vertex position.\nuniform mat4 u_matrix;\n\nuniform mediump float u_zoom;\nuniform bool u_rotate_with_map;\nuniform vec2 u_extrude_scale;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying vec2 v_fade_tex;\n\nvoid main() {\n vec2 a_tex = a_texture_pos.xy;\n mediump float a_labelminzoom = a_data[0];\n mediump vec2 a_zoom = a_data.pq;\n mediump float a_minzoom = a_zoom[0];\n mediump float a_maxzoom = a_zoom[1];\n\n // u_zoom is the current zoom level adjusted for the change in font size\n mediump float z = 2.0 - step(a_minzoom, u_zoom) - (1.0 - step(a_maxzoom, u_zoom));\n\n vec2 extrude = u_extrude_scale * (a_offset / 64.0);\n if (u_rotate_with_map) {\n gl_Position = u_matrix * vec4(a_pos + extrude, 0, 1);\n gl_Position.z += z * gl_Position.w;\n } else {\n gl_Position = u_matrix * vec4(a_pos, 0, 1) + vec4(extrude, 0, 0);\n }\n\n v_tex = a_tex / u_texsize;\n v_fade_tex = vec2(a_labelminzoom / 255.0, 0.0);\n}\n"},sdf:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform sampler2D u_texture;\nuniform sampler2D u_fadetexture;\nuniform lowp vec4 u_color;\nuniform lowp float u_opacity;\nuniform lowp float u_buffer;\nuniform lowp float u_gamma;\n\nvarying vec2 v_tex;\nvarying vec2 v_fade_tex;\nvarying float v_gamma_scale;\n\nvoid main() {\n lowp float dist = texture2D(u_texture, v_tex).a;\n lowp float fade_alpha = texture2D(u_fadetexture, v_fade_tex).a;\n lowp float gamma = u_gamma * v_gamma_scale;\n lowp float alpha = smoothstep(u_buffer - gamma, u_buffer + gamma, dist) * fade_alpha;\n\n gl_FragColor = u_color * (alpha * u_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nconst float PI = 3.141592653589793;\n\nattribute vec2 a_pos;\nattribute vec2 a_offset;\nattribute vec2 a_texture_pos;\nattribute vec4 a_data;\n\n\n// matrix is for the vertex position.\nuniform mat4 u_matrix;\n\nuniform mediump float u_zoom;\nuniform bool u_rotate_with_map;\nuniform bool u_pitch_with_map;\nuniform mediump float u_pitch;\nuniform mediump float u_bearing;\nuniform mediump float u_aspect_ratio;\nuniform vec2 u_extrude_scale;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying vec2 v_fade_tex;\nvarying float v_gamma_scale;\n\nvoid main() {\n vec2 a_tex = a_texture_pos.xy;\n mediump float a_labelminzoom = a_data[0];\n mediump vec2 a_zoom = a_data.pq;\n mediump float a_minzoom = a_zoom[0];\n mediump float a_maxzoom = a_zoom[1];\n\n // u_zoom is the current zoom level adjusted for the change in font size\n mediump float z = 2.0 - step(a_minzoom, u_zoom) - (1.0 - step(a_maxzoom, u_zoom));\n\n // pitch-alignment: map\n // rotation-alignment: map | viewport\n if (u_pitch_with_map) {\n lowp float angle = u_rotate_with_map ? (a_data[1] / 256.0 * 2.0 * PI) : u_bearing;\n lowp float asin = sin(angle);\n lowp float acos = cos(angle);\n mat2 RotationMatrix = mat2(acos, asin, -1.0 * asin, acos);\n vec2 offset = RotationMatrix * a_offset;\n vec2 extrude = u_extrude_scale * (offset / 64.0);\n gl_Position = u_matrix * vec4(a_pos + extrude, 0, 1);\n gl_Position.z += z * gl_Position.w;\n // pitch-alignment: viewport\n // rotation-alignment: map\n } else if (u_rotate_with_map) {\n // foreshortening factor to apply on pitched maps\n // as a label goes from horizontal <=> vertical in angle\n // it goes from 0% foreshortening to up to around 70% foreshortening\n lowp float pitchfactor = 1.0 - cos(u_pitch * sin(u_pitch * 0.75));\n\n lowp float lineangle = a_data[1] / 256.0 * 2.0 * PI;\n\n // use the lineangle to position points a,b along the line\n // project the points and calculate the label angle in projected space\n // this calculation allows labels to be rendered unskewed on pitched maps\n vec4 a = u_matrix * vec4(a_pos, 0, 1);\n vec4 b = u_matrix * vec4(a_pos + vec2(cos(lineangle),sin(lineangle)), 0, 1);\n lowp float angle = atan((b[1]/b[3] - a[1]/a[3])/u_aspect_ratio, b[0]/b[3] - a[0]/a[3]);\n lowp float asin = sin(angle);\n lowp float acos = cos(angle);\n mat2 RotationMatrix = mat2(acos, -1.0 * asin, asin, acos);\n\n vec2 offset = RotationMatrix * (vec2((1.0-pitchfactor)+(pitchfactor*cos(angle*2.0)), 1.0) * a_offset);\n vec2 extrude = u_extrude_scale * (offset / 64.0);\n gl_Position = u_matrix * vec4(a_pos, 0, 1) + vec4(extrude, 0, 0);\n gl_Position.z += z * gl_Position.w;\n // pitch-alignment: viewport\n // rotation-alignment: viewport\n } else {\n vec2 extrude = u_extrude_scale * (a_offset / 64.0);\n gl_Position = u_matrix * vec4(a_pos, 0, 1) + vec4(extrude, 0, 0);\n }\n\n v_gamma_scale = (gl_Position.w - 0.5);\n\n v_tex = a_tex / u_texsize;\n v_fade_tex = vec2(a_labelminzoom / 255.0, 0.0);\n}\n"},collisionbox:{fragmentSource:"#ifdef GL_ES\nprecision mediump float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nuniform float u_zoom;\nuniform float u_maxzoom;\n\nvarying float v_max_zoom;\nvarying float v_placement_zoom;\n\nvoid main() {\n\n float alpha = 0.5;\n\n gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0) * alpha;\n\n if (v_placement_zoom > u_zoom) {\n gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n }\n\n if (u_zoom >= v_max_zoom) {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0) * alpha * 0.25;\n }\n\n if (v_placement_zoom >= u_maxzoom) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0) * alpha * 0.2;\n }\n}\n",vertexSource:"#ifdef GL_ES\nprecision highp float;\n#else\n#define lowp\n#define mediump\n#define highp\n#endif\n\nattribute vec2 a_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_data;\n\nuniform mat4 u_matrix;\nuniform float u_scale;\n\nvarying float v_max_zoom;\nvarying float v_placement_zoom;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos + a_extrude / u_scale, 0.0, 1.0);\n\n v_max_zoom = a_data.x;\n v_placement_zoom = a_data.y;\n}\n"}},e.exports.util="float evaluate_zoom_function_1(const vec4 values, const float t) {\n if (t < 1.0) {\n return mix(values[0], values[1], t);\n } else if (t < 2.0) {\n return mix(values[1], values[2], t - 1.0);\n } else {\n return mix(values[2], values[3], t - 2.0);\n }\n}\nvec4 evaluate_zoom_function_4(const vec4 value0, const vec4 value1, const vec4 value2, const vec4 value3, const float t) {\n if (t < 1.0) {\n return mix(value0, value1, t);\n } else if (t < 2.0) {\n return mix(value1, value2, t - 1.0);\n } else {\n return mix(value2, value3, t - 2.0);\n }\n}\n"},{path:449}],276:[function(t,e,r){"use strict";var n=t("util").format;e.exports=function(t,e){this.message=(t?t+": ":"")+n.apply(n,Array.prototype.slice.call(arguments,2)),null!==e&&void 0!==e&&e.__line__&&(this.line=e.__line__)}},{util:543}],277:[function(t,e,r){"use strict";e.exports=function(t){for(var e=1;e7)return[new n(u,l,"constants have been deprecated as of v8")];if(!(l in h.constants))return[new n(u,l,'constant "%s" not found',l)];e=a({},e,{value:h.constants[l]})}return c.function&&"object"===i(l)?r(e):c.type&&s[c.type]?s[c.type](e):o(a({},e,{valueSpec:c.type?f[c.type]:c}))}},{"../error/validation_error":276,"../util/extend":277,"../util/get_type":278,"./validate_array":281,"./validate_boolean":282,"./validate_color":283,"./validate_constants":284,"./validate_enum":285,"./validate_filter":286,"./validate_function":287,"./validate_layer":289,"./validate_number":291,"./validate_object":292,"./validate_source":294,"./validate_string":295}],281:[function(t,e,r){"use strict";var n=t("../util/get_type"),i=t("./validate"),a=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.valueSpec,o=t.style,s=t.styleSpec,l=t.key,c=t.arrayElementValidator||i;if("array"!==n(e))return[new a(l,e,"array expected, %s found",n(e))];if(r.length&&e.length!==r.length)return[new a(l,e,"array length %d expected, length %d found",r.length,e.length)];if(r["min-length"]&&e.length7)return r?[new n(e,r,"constants have been deprecated as of v8")]:[];var a=i(r);if("object"!==a)return[new n(e,r,"object expected, %s found",a)];var o=[];for(var s in r)"@"!==s[0]&&o.push(new n(e+"."+s,r[s],'constants must start with "@"'));return o}},{"../error/validation_error":276,"../util/get_type":278}],285:[function(t,e,r){"use strict";var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint");e.exports=function(t){var e=t.key,r=t.value,a=t.valueSpec,o=[];return-1===a.values.indexOf(i(r))&&o.push(new n(e,r,"expected one of [%s], %s found",a.values.join(", "),r)),o}},{"../error/validation_error":276,"../util/unbundle_jsonlint":279}],286:[function(t,e,r){"use strict";var n=t("../error/validation_error"),i=t("./validate_enum"),a=t("../util/get_type"),o=t("../util/unbundle_jsonlint");e.exports=function t(e){var r,s=e.value,l=e.key,c=e.styleSpec,u=[];if("array"!==a(s))return[new n(l,s,"array expected, %s found",a(s))];if(s.length<1)return[new n(l,s,"filter array must have at least 1 element")];switch(u=u.concat(i({key:l+"[0]",value:s[0],valueSpec:c.filter_operator,style:e.style,styleSpec:e.styleSpec})),o(s[0])){case"<":case"<=":case">":case">=":s.length>=2&&"$type"==s[1]&&u.push(new n(l,s,'"$type" cannot be use with operator "%s"',s[0]));case"==":case"!=":3!=s.length&&u.push(new n(l,s,'filter array for operator "%s" must have 3 elements',s[0]));case"in":case"!in":s.length>=2&&("string"!==(r=a(s[1]))?u.push(new n(l+"[1]",s[1],"string expected, %s found",r)):"@"===s[1][0]&&u.push(new n(l+"[1]",s[1],"filter key cannot be a constant")));for(var f=2;f=8&&(c&&!t.valueSpec["property-function"]?f.push(new n(t.key,t.value,"property functions not supported")):u&&!t.valueSpec["zoom-function"]&&f.push(new n(t.key,t.value,"zoom functions not supported"))),f;function h(t){var s=[],c=t.value,f=t.key;if("array"!==i(c))return[new n(f,c,"array expected, %s found",i(c))];if(2!==c.length)return[new n(f,c,"array length %d expected, length %d found",2,c.length)];var h=i(c[0]);if(e||(e=h),h!==e)return[new n(f,c,"%s stop key type must match previous stop key type %s",h,e)];if("object"===h){if(void 0===c[0].zoom)return[new n(f,c,"object stop key must have zoom")];if(void 0===c[0].value)return[new n(f,c,"object stop key must have value")];s=s.concat(o({key:f+"[0]",value:c[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:l,value:d}}))}else s=s.concat((u?l:d)({key:f+"[0]",value:c[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec}));return s=s.concat(a({key:f+"[1]",value:c[1],valueSpec:r,style:t.style,styleSpec:t.styleSpec})),"number"===i(c[0])&&("piecewise-constant"===r.function&&c[0]%1!=0&&s.push(new n(f+"[0]",c[0],"zoom level for piecewise-constant functions must be an integer")),0!==t.arrayIndex&&c[0]a.maximum?[new i(e,r,"%s is greater than the maximum value %s",r,a.maximum)]:[]}},{"../error/validation_error":276,"../util/get_type":278}],292:[function(t,e,r){"use strict";var n=t("../error/validation_error"),i=t("../util/get_type"),a=t("./validate");e.exports=function(t){var e=t.key,r=t.value,o=t.valueSpec,s=t.objectElementValidators||{},l=t.style,c=t.styleSpec,u=[],f=i(r);if("object"!==f)return[new n(e,r,"object expected, %s found",f)];for(var h in r){var d=h.split(".")[0],p=o&&(o[d]||o["*"]),m=s[d]||s["*"];p||m?u=u.concat((m||a)({key:(e?e+".":e)+h,value:r[h],valueSpec:p,style:l,styleSpec:c,object:r,objectKey:h})):""!==e&&1!==e.split(".").length&&u.push(new n(e,r[h],'unknown property "%s"',h))}for(d in o)o[d].required&&void 0===o[d].default&&void 0===r[d]&&u.push(new n(e,r,'missing required property "%s"',d));return u}},{"../error/validation_error":276,"../util/get_type":278,"./validate":280}],293:[function(t,e,r){"use strict";var n=t("./validate"),i=t("../error/validation_error");e.exports=function(t){var e=t.key,r=t.style,a=t.styleSpec,o=t.value,s=t.objectKey,l=a["paint_"+t.layerType],c=s.match(/^(.*)-transition$/);return c&&l[c[1]]&&l[c[1]].transition?n({key:e,value:o,valueSpec:a.transition,style:r,styleSpec:a}):t.valueSpec||l[s]?n({key:t.key,value:o,valueSpec:t.valueSpec||l[s],style:r,styleSpec:a}):[new i(e,o,'unknown property "%s"',s)]}},{"../error/validation_error":276,"./validate":280}],294:[function(t,e,r){"use strict";var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_enum");e.exports=function(t){var e=t.value,r=t.key,s=t.styleSpec,l=t.style;if(!e.type)return[new n(r,e,'"type" is required')];switch(i(e.type)){case"vector":case"raster":var c=[];if(c=c.concat(a({key:r,value:e,valueSpec:s.source_tile,style:t.style,styleSpec:s})),"url"in e)for(var u in e)["type","url","tileSize"].indexOf(u)<0&&c.push(new n(r+"."+u,e[u],'a source with a "url" property may not include a "%s" property',u));return c;case"geojson":return a({key:r,value:e,valueSpec:s.source_geojson,style:l,styleSpec:s});case"video":return a({key:r,value:e,valueSpec:s.source_video,style:l,styleSpec:s});case"image":return a({key:r,value:e,valueSpec:s.source_image,style:l,styleSpec:s});default:return o({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","geojson","video","image"]},style:l,styleSpec:s})}}},{"../error/validation_error":276,"../util/unbundle_jsonlint":279,"./validate_enum":285,"./validate_object":292}],295:[function(t,e,r){"use strict";var n=t("../util/get_type"),i=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.key,a=n(e);return"string"!==a?[new i(r,e,"string expected, %s found",a)]:[]}},{"../error/validation_error":276,"../util/get_type":278}],296:[function(t,e,r){"use strict";var n=t("./validate/validate_constants"),i=t("./validate/validate"),a=t("../reference/latest.min"),o=t("./validate/validate_glyphs_url");function s(t,e){e=e||a;var r=[];return r=r.concat(i({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:o}})),e.$version>7&&t.constants&&(r=r.concat(n({key:"constants",value:t.constants,style:t,styleSpec:e}))),l(r)}function l(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function c(t){return function(){return l(t.apply(this,arguments))}}s.source=c(t("./validate/validate_source")),s.layer=c(t("./validate/validate_layer")),s.filter=c(t("./validate/validate_filter")),s.paintProperty=c(t("./validate/validate_paint_property")),s.layoutProperty=c(t("./validate/validate_layout_property")),e.exports=s},{"../reference/latest.min":297,"./validate/validate":280,"./validate/validate_constants":284,"./validate/validate_filter":286,"./validate/validate_glyphs_url":288,"./validate/validate_layer":289,"./validate/validate_layout_property":290,"./validate/validate_paint_property":293,"./validate/validate_source":294}],297:[function(t,e,r){e.exports=t("./v8.min.json")},{"./v8.min.json":298}],298:[function(t,e,r){e.exports={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_tile","source_geojson","source_video","source_image"],source_tile:{type:{required:!0,type:"enum",values:["vector","raster"]},url:{type:"string"},tiles:{type:"array",value:"string"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:["geojson"]},data:{type:"*"},maxzoom:{type:"number",default:14},buffer:{type:"number",default:64},tolerance:{type:"number",default:3},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:400},clusterMaxZoom:{type:"number"}},source_video:{type:{required:!0,type:"enum",values:["video"]},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:["image"]},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:["fill","line","symbol","circle","raster","background"]},metadata:{type:"*"},ref:{type:"string"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:22},maxzoom:{type:"number",minimum:0,maximum:22},interactive:{type:"boolean",default:!1},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"},"paint.*":{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_symbol","layout_raster","layout_background"],layout_background:{visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},layout_fill:{visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},layout_circle:{visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},layout_line:{"line-cap":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["butt","round","square"],default:"butt"},"line-join":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["bevel","round","miter"],default:"miter"},"line-miter-limit":{type:"number",default:2,function:"interpolated","zoom-function":!0,"property-function":!0,requires:[{"line-join":"miter"}]},"line-round-limit":{type:"number",default:1.05,function:"interpolated","zoom-function":!0,"property-function":!0,requires:[{"line-join":"round"}]},visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},layout_symbol:{"symbol-placement":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["point","line"],default:"point"},"symbol-spacing":{type:"number",default:250,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,units:"pixels",requires:[{"symbol-placement":"line"}]},"symbol-avoid-edges":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1},"icon-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["icon-image"]},"icon-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["icon-image"]},"icon-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["icon-image","text-field"]},"icon-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"viewport",requires:["icon-image"]},"icon-size":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image"]},"icon-text-fit":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!1,values:["none","both","width","height"],default:"none",requires:["icon-image","text-field"]},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image","icon-text-fit","text-field"]},"icon-image":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,tokens:!0},"icon-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,"property-function":!0,units:"degrees",requires:["icon-image"]},"icon-padding":{type:"number",default:2,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,units:"pixels",requires:["icon-image"]},"icon-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":"line"}]},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,requires:["icon-image"]},"text-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],requires:["text-field"]},"text-rotation-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"viewport",requires:["text-field"]},"text-field":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:"",tokens:!0},"text-font":{type:"array",value:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"]},"text-size":{type:"number",default:16,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-max-width":{type:"number",default:10,minimum:0,units:"em",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-line-height":{type:"number",default:1.2,units:"em",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-letter-spacing":{type:"number",default:0,units:"em",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-justify":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["left","center","right"],default:"center",requires:["text-field"]},"text-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"],default:"center",requires:["text-field"]},"text-max-angle":{type:"number",default:45,units:"degrees",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field",{"symbol-placement":"line"}]},"text-rotate":{type:"number",default:0,period:360,units:"degrees",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",function:"interpolated","zoom-function":!0,"property-function":!0,requires:["text-field"]},"text-keep-upright":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":"line"}]},"text-transform":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["none","uppercase","lowercase"],default:"none",requires:["text-field"]},"text-offset":{type:"array",value:"number",units:"ems",function:"interpolated","zoom-function":!0,"property-function":!0,length:2,default:[0,0],requires:["text-field"]},"text-allow-overlap":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["text-field"]},"text-ignore-placement":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["text-field"]},"text-optional":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!1,requires:["text-field","icon-image"]},visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},layout_raster:{visibility:{type:"enum",function:"piecewise-constant","zoom-function":!0,values:["visible","none"],default:"visible"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:["==","!=",">",">=","<","<=","in","!in","all","any","none","has","!has"]},geometry_type:{type:"enum",values:["Point","LineString","Polygon"]},color_operation:{type:"enum",values:["lighten","saturate","spin","fade","mix"]},function:{stops:{type:"array",required:!0,value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:["exponential","interval","categorical"],default:"exponential"}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},paint:["paint_fill","paint_line","paint_circle","paint_symbol","paint_raster","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,"property-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,transition:!0}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,"property-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,"property-function":!0,transition:!0}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,"property-function":!0,values:["map","viewport"],default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!0,units:"milliseconds"}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}}}},{}],299:[function(t,e,r){"use strict";function n(t){return!!("undefined"!=typeof window&&"undefined"!=typeof document&&Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray&&Function.prototype&&Function.prototype.bind&&Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions&&"JSON"in window&&"parse"in JSON&&"stringify"in JSON&&"Worker"in window&&"Uint8ClampedArray"in window&&function(t){void 0===i[t]&&(i[t]=function(t){var e=document.createElement("canvas"),r=Object.create(n.webGLContextAttributes);return r.failIfMajorPerformanceCaveat=t,e.probablySupportsContext?e.probablySupportsContext("webgl",r)||e.probablySupportsContext("experimental-webgl",r):e.supportsContext?e.supportsContext("webgl",r)||e.supportsContext("experimental-webgl",r):e.getContext("webgl",r)||e.getContext("experimental-webgl",r)}(t));return i[t]}(t&&t.failIfMajorPerformanceCaveat))}void 0!==e&&e.exports?e.exports=n:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=n);var i={};n.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0}},{}],300:[function(t,e,r){"use strict";var n=t("../util/util");function i(t){var e=t.layoutVertexArrayType;this.layoutVertexArray=new e;var r=t.elementArrayType;r&&(this.elementArray=new r);var i=t.elementArrayType2;i&&(this.elementArray2=new i),this.paintVertexArrays=n.mapObject(t.paintVertexArrayTypes,function(t){return new t})}e.exports=i,i.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,i.prototype.hasCapacityFor=function(t){return this.layoutVertexArray.length+t<=i.MAX_VERTEX_ARRAY_LENGTH},i.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},i.prototype.trim=function(){for(var t in this.layoutVertexArray.trim(),this.elementArray&&this.elementArray.trim(),this.elementArray2&&this.elementArray2.trim(),this.paintVertexArrays)this.paintVertexArrays[t].trim()},i.prototype.serialize=function(){return{layoutVertexArray:this.layoutVertexArray.serialize(),elementArray:this.elementArray&&this.elementArray.serialize(),elementArray2:this.elementArray2&&this.elementArray2.serialize(),paintVertexArrays:n.mapObject(this.paintVertexArrays,function(t){return t.serialize()})}},i.prototype.getTransferables=function(t){for(var e in t.push(this.layoutVertexArray.arrayBuffer),this.elementArray&&t.push(this.elementArray.arrayBuffer),this.elementArray2&&t.push(this.elementArray2.arrayBuffer),this.paintVertexArrays)t.push(this.paintVertexArrays[e].arrayBuffer)}},{"../util/util":414}],301:[function(t,e,r){"use strict";var n=t("feature-filter"),i=t("./array_group"),a=t("./buffer_group"),o=t("../util/util"),s=t("../util/struct_array"),l=t("assert");function c(t){if(this.zoom=t.zoom,this.overscaling=t.overscaling,this.layer=t.layer,this.childLayers=t.childLayers,this.type=this.layer.type,this.features=[],this.id=this.layer.id,this.index=t.index,this.sourceLayer=this.layer.sourceLayer,this.sourceLayerIndex=t.sourceLayerIndex,this.minZoom=this.layer.minzoom,this.maxZoom=this.layer.maxzoom,this.paintAttributes=function(t){var e={};for(var r in t.programInterfaces){for(var n=e[r]={},i=0;i1?p.name+x:p.name]=m[x]*v}}},c.VertexArrayType=function(t){return new s({members:t,alignment:4})},c.ElementArrayType=function(t){return new s({members:[{type:"Uint16",name:"vertices",components:t||3}]})}},{"../util/struct_array":412,"../util/util":414,"./array_group":300,"./bucket/circle_bucket":302,"./bucket/fill_bucket":303,"./bucket/line_bucket":304,"./bucket/symbol_bucket":305,"./buffer_group":307,assert:51,"feature-filter":141}],302:[function(t,e,r){"use strict";var n=t("../bucket"),i=t("../../util/util"),a=t("../load_geometry"),o=n.EXTENT;function s(){n.apply(this,arguments)}e.exports=s,s.prototype=i.inherit(n,{}),s.prototype.addCircleVertex=function(t,e,r,n,i){return t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2)},s.prototype.programInterfaces={circle:{layoutVertexArrayType:new n.VertexArrayType([{name:"a_pos",components:2,type:"Int16"}]),elementArrayType:new n.ElementArrayType,paintAttributes:[{name:"a_color",components:4,type:"Uint8",getValue:function(t,e,r){return t.getPaintValue("circle-color",e,r)},multiplier:255,paintProperty:"circle-color"},{name:"a_radius",components:1,type:"Uint16",isLayerConstant:!1,getValue:function(t,e,r){return[t.getPaintValue("circle-radius",e,r)]},multiplier:10,paintProperty:"circle-radius"},{name:"a_blur",components:1,type:"Uint16",isLayerConstant:!1,getValue:function(t,e,r){return[t.getPaintValue("circle-blur",e,r)]},multiplier:10,paintProperty:"circle-blur"},{name:"a_opacity",components:1,type:"Uint16",isLayerConstant:!1,getValue:function(t,e,r){return[t.getPaintValue("circle-opacity",e,r)]},multiplier:255,paintProperty:"circle-opacity"}]}},s.prototype.addFeature=function(t){for(var e={zoom:this.zoom},r=a(t),n=this.prepareArrayGroup("circle",0),i=n.layoutVertexArray.length,s=0;s=o||u<0||u>=o)){var f=this.prepareArrayGroup("circle",4),h=f.layoutVertexArray,d=this.addCircleVertex(h,c,u,-1,-1);this.addCircleVertex(h,c,u,1,-1),this.addCircleVertex(h,c,u,1,1),this.addCircleVertex(h,c,u,-1,1),f.elementArray.emplaceBack(d,d+1,d+2),f.elementArray.emplaceBack(d,d+3,d+2)}}this.populatePaintArrays("circle",e,t.properties,n,i)}},{"../../util/util":414,"../bucket":301,"../load_geometry":309}],303:[function(t,e,r){"use strict";var n=t("../bucket"),i=t("../../util/util"),a=t("../load_geometry"),o=t("earcut"),s=t("../../util/classify_rings");function l(){n.apply(this,arguments)}e.exports=l,l.prototype=i.inherit(n,{}),l.prototype.programInterfaces={fill:{layoutVertexArrayType:new n.VertexArrayType([{name:"a_pos",components:2,type:"Int16"}]),elementArrayType:new n.ElementArrayType(1),elementArrayType2:new n.ElementArrayType(2),paintAttributes:[{name:"a_color",components:4,type:"Uint8",getValue:function(t,e,r){return t.getPaintValue("fill-color",e,r)},multiplier:255,paintProperty:"fill-color"},{name:"a_outline_color",components:4,type:"Uint8",getValue:function(t,e,r){return t.getPaintValue("fill-outline-color",e,r)},multiplier:255,paintProperty:"fill-outline-color"},{name:"a_opacity",components:1,type:"Uint8",getValue:function(t,e,r){return[t.getPaintValue("fill-opacity",e,r)]},multiplier:255,paintProperty:"fill-opacity"}]}},l.prototype.addFeature=function(t){for(var e=a(t),r=s(e,500),n=this.prepareArrayGroup("fill",0),i=n.layoutVertexArray.length,o=0;o0&&a.push(i.length/2);for(var u=0;u=1&&n.elementArray2.emplaceBack(h-1,h),i.push(f.x),i.push(f.y)}}for(var d=o(i,a),p=0;p>6)},c.prototype.programInterfaces={line:{layoutVertexArrayType:new n.VertexArrayType([{name:"a_pos",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}]),elementArrayType:new n.ElementArrayType}},c.prototype.addFeature=function(t){for(var e=a(t,15),r=0;r2&&t[a-1].equals(t[a-2]);)a--;if(!(t.length<2)){"bevel"===e&&(n=1.05);var l=o/(512*this.overscaling)*15,c=t[0],u=t[a-1],f=c.equals(u);if(this.prepareArrayGroup("line",10*a),2!==a||!f){this.distance=0;var h,d,p,m,v,g,y,b=r,x=f?"butt":r,_=!0;this.e1=this.e2=this.e3=-1,f&&(h=t[a-2],v=c.sub(h)._unit()._perp());for(var w=0;w0){var E=h.dist(d);if(E>2*l){var S=h.sub(h.sub(d)._mult(l/E)._round());this.distance+=S.dist(d),this.addCurrentVertex(S,this.distance,m.mult(1),0,0,!1),d=S}}var L=d&&p,C=L?e:p?b:x;if(L&&"round"===C&&(An&&(C="bevel"),"bevel"===C&&(A>2&&(C="flipbevel"),A100)M=v.clone();else{var P=m.x*v.y-m.y*v.x>0?-1:1,z=A*m.add(v).mag()/m.sub(v).mag();M._perp()._mult(z*P)}this.addCurrentVertex(h,this.distance,M,0,0,!1),this.addCurrentVertex(h,this.distance,M.mult(-1),0,0,!1)}else if("bevel"===C||"fakeround"===C){var O=m.x*v.y-m.y*v.x>0,D=-Math.sqrt(A*A-1);if(O?(y=0,g=D):(g=0,y=D),_||this.addCurrentVertex(h,this.distance,m,g,y,!1),"fakeround"===C){for(var I,R=Math.floor(8*(.5-(k-.5))),N=0;N=0;F--)I=m.mult((F+1)/(R+1))._add(v)._unit(),this.addPieSliceVertex(h,this.distance,I,O)}p&&this.addCurrentVertex(h,this.distance,v,-g,-y,!1)}else"butt"===C?(_||this.addCurrentVertex(h,this.distance,m,0,0,!1),p&&this.addCurrentVertex(h,this.distance,v,0,0,!1)):"square"===C?(_||(this.addCurrentVertex(h,this.distance,m,1,1,!1),this.e1=this.e2=-1),p&&this.addCurrentVertex(h,this.distance,v,-1,-1,!1)):"round"===C&&(_||(this.addCurrentVertex(h,this.distance,m,0,0,!1),this.addCurrentVertex(h,this.distance,m,1,1,!0),this.e1=this.e2=-1),p&&(this.addCurrentVertex(h,this.distance,v,-1,-1,!0),this.addCurrentVertex(h,this.distance,v,0,0,!1)));if(T&&w2*l){var B=h.add(p.sub(h)._mult(l/j)._round());this.distance+=B.dist(h),this.addCurrentVertex(B,this.distance,v.mult(1),0,0,!1),h=B}}_=!1}}}},c.prototype.addCurrentVertex=function(t,e,r,n,i,a){var o,s=a?1:0,c=this.arrayGroups.line[this.arrayGroups.line.length-1],u=c.layoutVertexArray,f=c.elementArray;o=r.clone(),n&&o._sub(r.perp()._mult(n)),this.e3=this.addLineVertex(u,t,o,s,0,n,e),this.e1>=0&&this.e2>=0&&f.emplaceBack(this.e1,this.e2,this.e3),this.e1=this.e2,this.e2=this.e3,o=r.mult(-1),i&&o._sub(r.perp()._mult(i)),this.e3=this.addLineVertex(u,t,o,s,1,-i,e),this.e1>=0&&this.e2>=0&&f.emplaceBack(this.e1,this.e2,this.e3),this.e1=this.e2,this.e2=this.e3,e>l/2&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,n,i,a))},c.prototype.addPieSliceVertex=function(t,e,r,n){var i=n?1:0;r=r.mult(n?-1:1);var a=this.arrayGroups.line[this.arrayGroups.line.length-1],o=a.layoutVertexArray,s=a.elementArray;this.e3=this.addLineVertex(o,t,r,0,i,0,e),this.e1>=0&&this.e2>=0&&s.emplaceBack(this.e1,this.e2,this.e3),n?this.e2=this.e3:this.e1=this.e3}},{"../../util/util":414,"../bucket":301,"../load_geometry":309}],305:[function(t,e,r){"use strict";var n=t("point-geometry"),i=t("../bucket"),a=t("../../symbol/anchor"),o=t("../../symbol/get_anchors"),s=t("../../util/token"),l=t("../../symbol/quads"),c=t("../../symbol/shaping"),u=t("../../symbol/resolve_text"),f=t("../../symbol/mergelines"),h=t("../../symbol/clip_line"),d=t("../../util/util"),p=t("../load_geometry"),m=t("../../symbol/collision_feature"),v=c.shapeText,g=c.shapeIcon,y=l.getGlyphQuads,b=l.getIconQuads,x=i.EXTENT;function _(t){i.apply(this,arguments),this.showCollisionBoxes=t.showCollisionBoxes,this.overscaling=t.overscaling,this.collisionBoxArray=t.collisionBoxArray,this.symbolQuadsArray=t.symbolQuadsArray,this.symbolInstancesArray=t.symbolInstancesArray,this.sdfIcons=t.sdfIcons,this.iconsNeedLinear=t.iconsNeedLinear,this.adjustedTextSize=t.adjustedTextSize,this.adjustedIconSize=t.adjustedIconSize,this.fontstack=t.fontstack}e.exports=_,_.MAX_QUADS=65535,_.prototype=d.inherit(i,{}),_.prototype.serialize=function(){var t=i.prototype.serialize.apply(this);return t.sdfIcons=this.sdfIcons,t.iconsNeedLinear=this.iconsNeedLinear,t.adjustedTextSize=this.adjustedTextSize,t.adjustedIconSize=this.adjustedIconSize,t.fontstack=this.fontstack,t};var w=new i.VertexArrayType([{name:"a_pos",components:2,type:"Int16"},{name:"a_offset",components:2,type:"Int16"},{name:"a_texture_pos",components:2,type:"Uint16"},{name:"a_data",components:4,type:"Uint8"}]),M=new i.ElementArrayType;function k(t,e,r,n,i,a,o,s,l,c,u){return t.emplaceBack(e,r,Math.round(64*n),Math.round(64*i),a/4,o/4,10*(c||0),u,10*(s||0),10*Math.min(l||25,25))}_.prototype.addCollisionBoxVertex=function(t,e,r,n,i){return t.emplaceBack(e.x,e.y,Math.round(r.x),Math.round(r.y),10*n,10*i)},_.prototype.programInterfaces={glyph:{layoutVertexArrayType:w,elementArrayType:M},icon:{layoutVertexArrayType:w,elementArrayType:M},collisionBox:{layoutVertexArrayType:new i.VertexArrayType([{name:"a_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"},{name:"a_data",components:2,type:"Uint8"}])}},_.prototype.populateArrays=function(t,e,r){var n={lastIntegerZoom:1/0,lastIntegerZoomTime:0,lastZoom:0};this.adjustedTextMaxSize=this.layer.getLayoutValue("text-size",{zoom:18,zoomHistory:n}),this.adjustedTextSize=this.layer.getLayoutValue("text-size",{zoom:this.zoom+1,zoomHistory:n}),this.adjustedIconMaxSize=this.layer.getLayoutValue("icon-size",{zoom:18,zoomHistory:n}),this.adjustedIconSize=this.layer.getLayoutValue("icon-size",{zoom:this.zoom+1,zoomHistory:n});var i=512*this.overscaling;this.tilePixelRatio=x/i,this.compareText={},this.iconsNeedLinear=!1,this.symbolInstancesStartIndex=this.symbolInstancesArray.length;var a=this.layer.layout,o=this.features,l=this.textFeatures,c=.5,u=.5;switch(a["text-anchor"]){case"right":case"top-right":case"bottom-right":c=1;break;case"left":case"top-left":case"bottom-left":c=0}switch(a["text-anchor"]){case"bottom":case"bottom-right":case"bottom-left":u=1;break;case"top":case"top-right":case"top-left":u=0}for(var h,m,y="right"===a["text-justify"]?1:"left"===a["text-justify"]?0:.5,b=24*a["text-line-height"],_="line"!==a["symbol-placement"]?24*a["text-max-width"]:0,w=24*a["text-letter-spacing"],M=[24*a["text-offset"][0],24*a["text-offset"][1]],k=this.fontstack=a["text-font"].join(","),A=[],T=0;Tx||L.y<0||L.y>x);if(!p||C){var P=C||_;this.addSymbolInstance(L,T,e,r,this.layer,P,this.symbolInstancesArray.length,this.collisionBoxArray,n.index,this.sourceLayerIndex,this.index,c,m,y,f,v,b,{zoom:this.zoom},n.properties)}}}},_.prototype.anchorIsTooClose=function(t,e,r){var n=this.compareText;if(t in n){for(var i=n[t],a=i.length-1;a>=0;a--)if(r.dist(i[a])3*Math.PI/2))){var m=d.tl,v=d.tr,g=d.bl,y=d.br,b=d.tex,x=d.anchorPoint,_=Math.max(u+Math.log(d.minScale)/Math.LN2,f),w=Math.min(u+Math.log(d.maxScale)/Math.LN2,25);if(!(w<=_)){_===f&&(_=0);var M=Math.round(d.glyphAngle/(2*Math.PI)*256),A=k(c,x.x,x.y,m.x,m.y,b.x,b.y,_,w,f,M);k(c,x.x,x.y,v.x,v.y,b.x+b.w,b.y,_,w,f,M),k(c,x.x,x.y,g.x,g.y,b.x,b.y+b.h,_,w,f,M),k(c,x.x,x.y,y.x,y.y,b.x+b.w,b.y+b.h,_,w,f,M),l.emplaceBack(A,A+1,A+2),l.emplaceBack(A+1,A+2,A+3)}}}},_.prototype.updateIcons=function(t){this.recalculateStyleLayers();var e=this.layer.layout["icon-image"];if(e)for(var r=0;r_.MAX_QUADS&&d.warnOnce("Too many symbols being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),A>_.MAX_QUADS&&d.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),this.symbolInstancesArray.emplaceBack(O,D,I,R,k,A,T,E,t.x,t.y,o)},_.prototype.addSymbolQuad=function(t){return this.symbolQuadsArray.emplaceBack(t.anchorPoint.x,t.anchorPoint.y,t.tl.x,t.tl.y,t.tr.x,t.tr.y,t.bl.x,t.bl.y,t.br.x,t.br.y,t.tex.h,t.tex.w,t.tex.x,t.tex.y,t.anchorAngle,t.glyphAngle,t.maxScale,t.minScale)}},{"../../symbol/anchor":363,"../../symbol/clip_line":365,"../../symbol/collision_feature":367,"../../symbol/get_anchors":369,"../../symbol/mergelines":372,"../../symbol/quads":373,"../../symbol/resolve_text":374,"../../symbol/shaping":375,"../../util/token":413,"../../util/util":414,"../bucket":301,"../load_geometry":309,"point-geometry":458}],306:[function(t,e,r){"use strict";function n(t,e,r){this.arrayBuffer=t.arrayBuffer,this.length=t.length,this.attributes=e.members,this.itemSize=e.bytesPerElement,this.type=r,this.arrayType=e}e.exports=n,n.prototype.bind=function(t){var e=t[this.type];this.buffer?t.bindBuffer(e,this.buffer):(this.buffer=t.createBuffer(),t.bindBuffer(e,this.buffer),t.bufferData(e,this.arrayBuffer,t.STATIC_DRAW),this.arrayBuffer=null)};var i={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT"};n.prototype.setVertexAttribPointers=function(t,e){for(var r=0;r0?t["line-gap-width"]+2*t["line-width"]:t["line-width"]}function M(t,e,r,i,a){if(!e[0]&&!e[1])return t;e=n.convert(e),"viewport"===r&&e._rotate(-i);for(var o=[],s=0;sr.max||h.yr.max)&&n.warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return l}},{"../util/util":414,"./bucket":301,assert:51}],310:[function(t,e,r){"use strict";function n(t,e,r){this.column=t,this.row=e,this.zoom=r}e.exports=n,n.prototype={clone:function(){return new n(this.column,this.row,this.zoom)},zoomTo:function(t){return this.clone()._zoomTo(t)},sub:function(t){return this.clone()._sub(t)},_zoomTo:function(t){var e=Math.pow(2,t-this.zoom);return this.column*=e,this.row*=e,this.zoom=t,this},_sub:function(t){return t=t.zoomTo(this.zoom),this.column-=t.column,this.row-=t.row,this}}},{}],311:[function(t,e,r){"use strict";e.exports=i;var n=t("../util/util").wrap;function i(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}i.prototype.wrap=function(){return new i(n(this.lng,-180,180),this.lat)},i.prototype.toArray=function(){return[this.lng,this.lat]},i.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},i.convert=function(t){return t instanceof i?t:Array.isArray(t)?new i(t[0],t[1]):t}},{"../util/util":414}],312:[function(t,e,r){"use strict";e.exports=i;var n=t("./lng_lat");function i(t,e){t&&(e?this.extend(t).extend(e):4===t.length?this.extend([t[0],t[1]]).extend([t[2],t[3]]):this.extend(t[0]).extend(t[1]))}i.prototype={extend:function(t){var e,r,a=this._sw,o=this._ne;if(t instanceof n)e=t,r=t;else{if(!(t instanceof i))return t?this.extend(n.convert(t)||i.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return a||o?(a.lng=Math.min(e.lng,a.lng),a.lat=Math.min(e.lat,a.lat),o.lng=Math.max(r.lng,o.lng),o.lat=Math.max(r.lat,o.lat)):(this._sw=new n(e.lng,e.lat),this._ne=new n(r.lng,r.lat)),this},getCenter:function(){return new n((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},getSouthWest:function(){return this._sw},getNorthEast:function(){return this._ne},getNorthWest:function(){return new n(this.getWest(),this.getNorth())},getSouthEast:function(){return new n(this.getEast(),this.getSouth())},getWest:function(){return this._sw.lng},getSouth:function(){return this._sw.lat},getEast:function(){return this._ne.lng},getNorth:function(){return this._ne.lat},toArray:function(){return[this._sw.toArray(),this._ne.toArray()]},toString:function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"}},i.convert=function(t){return!t||t instanceof i?t:new i(t)}},{"./lng_lat":311}],313:[function(t,e,r){"use strict";var n=t("./lng_lat"),i=t("point-geometry"),a=t("./coordinate"),o=t("../util/util").wrap,s=t("../util/interpolate"),l=t("../source/tile_coord"),c=t("../data/bucket").EXTENT,u=t("gl-matrix"),f=u.vec4,h=u.mat4,d=u.mat2;function p(t,e){this.tileSize=512,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new n(0,0),this.zoom=0,this.angle=0,this._altitude=1.5,this._pitch=0,this._unmodified=!0}e.exports=p,p.prototype={get minZoom(){return this._minZoom},set minZoom(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},get maxZoom(){return this._maxZoom},set maxZoom(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},get worldSize(){return this.tileSize*this.scale},get centerPoint(){return this.size._div(2)},get size(){return new i(this.width,this.height)},get bearing(){return-this.angle/Math.PI*180},set bearing(t){var e=-o(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=d.create(),d.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},get pitch(){return this._pitch/Math.PI*180},set pitch(t){var e=Math.min(60,t)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())},get altitude(){return this._altitude},set altitude(t){var e=Math.max(.75,t);this._altitude!==e&&(this._unmodified=!1,this._altitude=e,this._calcMatrices())},get zoom(){return this._zoom},set zoom(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._calcMatrices(),this._constrain())},get center(){return this._center},set center(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._calcMatrices(),this._constrain())},coveringZoomLevel:function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},coveringTiles:function(t){var e=this.coveringZoomLevel(t),r=e;if(et.maxzoom&&(e=t.maxzoom);var n=this,a=n.locationCoordinate(n.center)._zoomTo(e),o=new i(a.column-.5,a.row-.5);return l.cover(e,[n.pointCoordinate(new i(0,0))._zoomTo(e),n.pointCoordinate(new i(n.width,0))._zoomTo(e),n.pointCoordinate(new i(n.width,n.height))._zoomTo(e),n.pointCoordinate(new i(0,n.height))._zoomTo(e)],t.reparseOverscaled?r:e).sort(function(t,e){return o.dist(t)-o.dist(e)})},resize:function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._calcMatrices(),this._constrain()},get unmodified(){return this._unmodified},zoomScale:function(t){return Math.pow(2,t)},scaleZoom:function(t){return Math.log(t)/Math.LN2},project:function(t,e){return new i(this.lngX(t.lng,e),this.latY(t.lat,e))},unproject:function(t,e){return new n(this.xLng(t.x,e),this.yLat(t.y,e))},get x(){return this.lngX(this.center.lng)},get y(){return this.latY(this.center.lat)},get point(){return new i(this.x,this.y)},lngX:function(t,e){return(180+t)*(e||this.worldSize)/360},latY:function(t,e){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*(e||this.worldSize)/360},xLng:function(t,e){return 360*t/(e||this.worldSize)-180},yLat:function(t,e){var r=180-360*t/(e||this.worldSize);return 360/Math.PI*Math.atan(Math.exp(r*Math.PI/180))-90},panBy:function(t){var e=this.centerPoint._add(t);this.center=this.pointLocation(e)},setLocationAtPoint:function(t,e){var r=this.locationCoordinate(t),n=this.pointCoordinate(e),i=this.pointCoordinate(this.centerPoint),a=n._sub(r);this._unmodified=!1,this.center=this.coordinateLocation(i._sub(a))},locationPoint:function(t){return this.coordinatePoint(this.locationCoordinate(t))},pointLocation:function(t){return this.coordinateLocation(this.pointCoordinate(t))},locationCoordinate:function(t){var e=this.zoomScale(this.tileZoom)/this.worldSize,r=n.convert(t);return new a(this.lngX(r.lng)*e,this.latY(r.lat)*e,this.tileZoom)},coordinateLocation:function(t){var e=this.zoomScale(t.zoom);return new n(this.xLng(t.column,e),this.yLat(t.row,e))},pointCoordinate:function(t){var e=[t.x,t.y,0,1],r=[t.x,t.y,1,1];f.transformMat4(e,e,this.pixelMatrixInverse),f.transformMat4(r,r,this.pixelMatrixInverse);var n=e[3],i=r[3],o=e[0]/n,l=r[0]/i,c=e[1]/n,u=r[1]/i,h=e[2]/n,d=r[2]/i,p=h===d?0:(0-h)/(d-h),m=this.worldSize/this.zoomScale(this.tileZoom);return new a(s(o,l,p)/m,s(c,u,p)/m,this.tileZoom)},coordinatePoint:function(t){var e=this.worldSize/this.zoomScale(t.zoom),r=[t.column*e,t.row*e,0,1];return f.transformMat4(r,r,this.pixelMatrix),new i(r[0]/r[3],r[1]/r[3])},calculatePosMatrix:function(t,e){void 0===e&&(e=1/0),t instanceof l&&(t=t.toCoordinate(e));var r=Math.min(t.zoom,e),n=this.worldSize/Math.pow(2,r),i=new Float64Array(16);return h.identity(i),h.translate(i,i,[t.column*n,t.row*n,0]),h.scale(i,i,[n/c,n/c,1]),h.multiply(i,this.projMatrix,i),new Float32Array(i)},_constrain:function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var t,e,r,n,a,o,s,l,c=this.size,u=this._unmodified;this.latRange&&(t=this.latY(this.latRange[1]),a=(e=this.latY(this.latRange[0]))-te&&(l=e-d)}if(this.lngRange){var p=this.x,m=c.x/2;p-mn&&(s=n-m)}void 0===s&&void 0===l||(this.center=this.unproject(new i(void 0!==s?s:this.x,void 0!==l?l:this.y))),this._unmodified=u,this._constraining=!1}},_calcMatrices:function(){if(this.height){var t=Math.atan(.5/this.altitude),e=Math.sin(t)*this.altitude/Math.sin(Math.PI/2-this._pitch-t),r=Math.cos(Math.PI/2-this._pitch)*e+this.altitude,n=new Float64Array(16);if(h.perspective(n,2*Math.atan(this.height/2/this.altitude),this.width/this.height,.1,r),h.translate(n,n,[0,0,-this.altitude]),h.scale(n,n,[1,-1,1/this.height]),h.rotateX(n,n,this._pitch),h.rotateZ(n,n,this.angle),h.translate(n,n,[-this.x,-this.y,0]),this.projMatrix=n,n=h.create(),h.scale(n,n,[this.width/2,-this.height/2,1]),h.translate(n,n,[1,-1,0]),this.pixelMatrix=h.multiply(new Float64Array(16),n,this.projMatrix),!(n=h.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=n}}}},{"../data/bucket":301,"../source/tile_coord":341,"../util/interpolate":408,"../util/util":414,"./coordinate":310,"./lng_lat":311,"gl-matrix":198,"point-geometry":458}],314:[function(t,e,r){"use strict";var n={" ":[16,[]],"!":[10,[5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2]],'"':[16,[4,21,4,14,-1,-1,12,21,12,14]],"#":[21,[11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6]],$:[20,[8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],"%":[24,[21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7]],"&":[26,[23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2]],"'":[10,[5,19,4,20,5,21,6,20,6,18,5,16,4,15]],"(":[14,[11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7]],")":[14,[3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7]],"*":[16,[8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12]],"+":[26,[13,18,13,0,-1,-1,4,9,22,9]],",":[10,[6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"-":[26,[4,9,22,9]],".":[10,[5,2,4,1,5,0,6,1,5,2]],"/":[22,[20,25,2,-7]],0:[20,[9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21]],1:[20,[6,17,8,18,11,21,11,0]],2:[20,[4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0]],3:[20,[5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],4:[20,[13,21,3,7,18,7,-1,-1,13,21,13,0]],5:[20,[15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],6:[20,[16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7]],7:[20,[17,21,7,0,-1,-1,3,21,17,21]],8:[20,[8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21]],9:[20,[16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3]],":":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2]],";":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"<":[24,[20,18,4,9,20,0]],"=":[26,[4,12,22,12,-1,-1,4,6,22,6]],">":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]};e.exports=function(t,e,r,i){i=i||1;var a,o,s,l,c,u,f,h,d=[];for(a=0,o=t.length;a>16,_>>16),s.uniform2f(o.u_pixel_coord_lower,65535&x,65535&_)}s.uniformMatrix4fv(o.u_matrix,!1,t.transform.calculatePosMatrix(g)),s.drawArrays(s.TRIANGLE_STRIP,0,t.tileExtentBuffer.length)}s.stencilMask(0),s.stencilFunc(s.EQUAL,128,128)}},{"../source/pixels_to_tile_units":335,"./create_uniform_pragmas":316}],318:[function(t,e,r){"use strict";var n=t("../util/browser");e.exports=function(t,e,r,i){if(t.isOpaquePass)return;var a=t.gl;t.setDepthSublayer(0),t.depthMask(!1),a.disable(a.STENCIL_TEST);for(var o=0;o>16,h>>16),s.uniform2f(o.u_pixel_coord_lower,65535&f,65535&h),s.activeTexture(s.TEXTURE0),a.spriteAtlas.bind(s,!0)}}e.exports=function(t,e,r,n){var o,s=t.gl;s.enable(s.STENCIL_TEST),o=!r.paint["fill-pattern"]&&(r.isPaintValueFeatureConstant("fill-color")&&r.isPaintValueFeatureConstant("fill-opacity")&&1===r.paint["fill-color"][3]&&1===r.paint["fill-opacity"]);if(t.isOpaquePass===o){t.setDepthSublayer(1);for(var l=0;l0?1-1/(1.001-o):-o),a.uniform1f(u.u_contrast_factor,(s=r.paint["raster-contrast"])>0?1/(1-s):1+s),a.uniform3fv(u.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint["raster-hue-rotate"]));var f,h,d=l.source&&l.source.findLoadedParent(i,0,{}),p=function(t,e,r,i){var a=[1,0],o=r.paint["raster-fade-duration"];if(t.source&&o>0){var s=(new Date).getTime(),l=(s-t.timeAdded)/o,c=e?(s-e.timeAdded)/o:-1,u=i.coveringZoomLevel(t.source),f=!!e&&Math.abs(e.coord.z-u)>Math.abs(t.coord.z-u);!e||f?(a[0]=n.clamp(l,0,1),a[1]=1-a[0]):(a[0]=n.clamp(1-c,0,1),a[1]=1-a[0])}var h=r.paint["raster-opacity"];return a[0]*=h,a[1]*=h,a}(l,d,r,t.transform);a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,l.texture),a.activeTexture(a.TEXTURE1),d?(a.bindTexture(a.TEXTURE_2D,d.texture),f=Math.pow(2,d.coord.z-l.coord.z),h=[l.coord.x*f%1,l.coord.y*f%1]):(a.bindTexture(a.TEXTURE_2D,l.texture),p[1]=0),a.uniform2fv(u.u_tl_parent,h||[0,0]),a.uniform1f(u.u_scale_parent,f||1),a.uniform1f(u.u_buffer_scale,1),a.uniform1f(u.u_opacity0,p[0]),a.uniform1f(u.u_opacity1,p[1]),a.uniform1i(u.u_image0,0),a.uniform1i(u.u_image1,1);var m=l.boundsBuffer||t.rasterBoundsBuffer;(l.boundsVAO||t.rasterBoundsVAO).bind(a,u,m),a.drawArrays(a.TRIANGLE_STRIP,0,m.length)}e.exports=a,a.RasterBoundsArray=new i({members:[{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]})},{"../util/struct_array":412,"../util/util":414}],324:[function(t,e,r){"use strict";var n=t("../util/browser"),i=t("./draw_collision_debug"),a=t("../source/pixels_to_tile_units");function o(t,e,r,n,i,a,o,l,c,u,f,h,d,p,m){for(var v=0;vthis.previousZoom;e--)this.changeTimes[e]=r,this.changeOpacities[e]=this.opacities[e];for(e=0;e<256;e++){var n=(r-this.changeTimes[e])/this.fadeDuration*255;this.opacities[e]=e<=t?this.changeOpacities[e]+n:this.changeOpacities[e]-n}this.changed=!0,this.previousZoom=t},n.prototype.bind=function(t){this.texture?(t.bindTexture(t.TEXTURE_2D,this.texture),this.changed&&(t.texSubImage2D(t.TEXTURE_2D,0,0,0,256,1,t.ALPHA,t.UNSIGNED_BYTE,this.array),this.changed=!1)):(this.texture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.ALPHA,256,1,0,t.ALPHA,t.UNSIGNED_BYTE,this.array))}},{}],326:[function(t,e,r){"use strict";var n=t("../util/util");function i(t,e){this.width=t,this.height=e,this.nextRow=0,this.bytes=4,this.data=new Uint8Array(this.width*this.height*this.bytes),this.positions={}}e.exports=i,i.prototype.setSprite=function(t){this.sprite=t},i.prototype.getDash=function(t,e){var r=t.join(",")+e;return this.positions[r]||(this.positions[r]=this.addDash(t,e)),this.positions[r]},i.prototype.addDash=function(t,e){var r=e?7:0,i=2*r+1;if(this.nextRow+i>this.height)return n.warnOnce("LineAtlas out of space"),null;for(var a=0,o=0;o0?e.pop():null},m.prototype.lineWidth=function(t){this.gl.lineWidth(c.clamp(t,this.lineWidthRange[0],this.lineWidthRange[1]))},m.prototype.showOverdrawInspector=function(t){if(t||this._showOverdrawInspector){this._showOverdrawInspector=t;var e=this.gl;if(t){e.blendFunc(e.CONSTANT_COLOR,e.ONE);e.blendColor(1/8,1/8,1/8,0),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT)}else e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}}},{"../data/bucket":301,"../data/buffer":306,"../source/pixels_to_tile_units":335,"../source/source_cache":339,"../util/browser":398,"../util/struct_array":412,"../util/util":414,"./create_uniform_pragmas":316,"./draw_background":317,"./draw_circle":318,"./draw_debug":320,"./draw_fill":321,"./draw_line":322,"./draw_raster":323,"./draw_symbol":324,"./frame_history":325,"./painter/use_program":328,"./vertex_array_object":329,"gl-matrix":198}],328:[function(t,e,r){"use strict";var n=t("assert"),i=t("../../util/util"),a=t("mapbox-gl-shaders"),o=a.util;function s(t,e){return t.replace(/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,function(t,r,n,i,a){return e[r][a].replace(/{type}/g,i).replace(/{precision}/g,n)})}e.exports._createProgram=function(t,e,r,l){for(var c=this.gl,u=c.createProgram(),f=a[t],h="#define MAPBOX_GL_JS;\n",d=0;dthis.maxzoom?Math.pow(2,t.coord.z-this.maxzoom):1,n={type:this.type,uid:t.uid,coord:t.coord,zoom:t.coord.z,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,overscaling:r,angle:this.map.transform.angle,pitch:this.map.transform.pitch,showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send("load tile",n,function(r,n){if(t.unloadVectorData(this.map.painter),!t.aborted)return r?e(r):(t.loadVectorData(n,this.map.style),t.redoWhenDone&&(t.redoWhenDone=!1,t.redoPlacement(this)),e(null))}.bind(this),this.workerID)},abortTile:function(t){t.aborted=!0},unloadTile:function(t){t.unloadVectorData(this.map.painter),this.dispatcher.send("remove tile",{uid:t.uid,source:this.id},function(){},t.workerID)},serialize:function(){return{type:this.type,data:this._data}}})},{"../data/bucket":301,"../util/evented":406,"../util/util":414,"resolve-url":488}],331:[function(t,e,r){"use strict";var n=t("../util/util"),i=t("../util/ajax"),a=t("geojson-rewind"),o=t("./geojson_wrapper"),s=t("vt-pbf"),l=t("supercluster"),c=t("geojson-vt"),u=t("./vector_tile_worker_source");function f(t,e,r){r&&(this.loadGeoJSON=r),u.call(this,t,e)}e.exports=f,f.prototype=n.inherit(u,{_geoJSONIndexes:{},loadVectorData:function(t,e){var r=t.source,n=t.coord;if(!this._geoJSONIndexes[r])return e(null,null);var i=this._geoJSONIndexes[r].getTile(Math.min(n.z,t.maxZoom),n.x,n.y);if(!i)return e(null,null);var a=new o(i.features);a.name="_geojsonTileLayer";var l=s({layers:{_geojsonTileLayer:a}});0===l.byteOffset&&l.byteLength===l.buffer.byteLength||(l=new Uint8Array(l)),e(null,{tile:a,rawTileData:l.buffer})},loadData:function(t,e){var r=function(r,n){return r?e(r):"object"!=typeof n?e(new Error("Input data is not a valid GeoJSON object.")):(a(n,!0),void this._indexData(n,t,function(r,n){if(r)return e(r);this._geoJSONIndexes[t.source]=n,e(null)}.bind(this)))}.bind(this);this.loadGeoJSON(t,r)},loadGeoJSON:function(t,e){if(t.url)i.getJSON(t.url,e);else{if("string"!=typeof t.data)return e(new Error("Input data is not a valid GeoJSON object."));try{return e(null,JSON.parse(t.data))}catch(t){return e(new Error("Input data is not a valid GeoJSON object."))}}},_indexData:function(t,e,r){try{e.cluster?r(null,l(e.superclusterOptions).load(t.features)):r(null,c(t,e.geojsonVtOptions))}catch(t){return r(t)}}})},{"../util/ajax":397,"../util/util":414,"./geojson_wrapper":332,"./vector_tile_worker_source":343,"geojson-rewind":147,"geojson-vt":151,supercluster:518,"vt-pbf":550}],332:[function(t,e,r){"use strict";var n=t("point-geometry"),i=t("vector-tile").VectorTileFeature,a=t("../data/bucket").EXTENT;function o(t){this.features=t,this.length=t.length,this.extent=a}function s(t){if(this.type=t.type,1===t.type){this.rawGeometry=[];for(var e=0;ee)){var o=Math.pow(2,Math.min(a.coord.z,this.maxzoom)-Math.min(t.z,this.maxzoom));if(Math.floor(a.coord.x/o)===t.x&&Math.floor(a.coord.y/o)===t.y)for(r[i]=!0,n=!0;a&&a.coord.z-1>t.z;){var s=a.coord.parent(this.maxzoom).id;(a=this._tiles[s])&&a.isRenderable()&&(delete r[i],r[s]=!0)}}}return n},findLoadedParent:function(t,e,r){for(var n=t.z-1;n>=e;n--){t=t.parent(this.maxzoom);var i=this._tiles[t.id];if(i&&i.isRenderable())return r[t.id]=!0,i;if(this._cache.has(t.id))return this.addTile(t),r[t.id]=!0,this._tiles[t.id]}},updateCacheSize:function(t){var e=(Math.ceil(t.width/t.tileSize)+1)*(Math.ceil(t.height/t.tileSize)+1);this._cache.setMaxSize(Math.floor(5*e))},update:function(t,e){if(this._sourceLoaded){var r,n,i;this.updateCacheSize(t);var a=(this.roundZoom?Math.round:Math.floor)(this.getZoom(t)),s=Math.max(a-f.maxOverzooming,this.minzoom),l=Math.max(a+f.maxUnderzooming,this.minzoom),u={},h=(new Date).getTime();this._coveredTiles={};var d=this.used?t.coveringTiles(this._source):[];for(r=0;rh-(e||0)&&(this.findLoadedChildren(n,l,u)&&(u[y]=!0),this.findLoadedParent(n,s,m))}for(p in m)u[p]||(this._coveredTiles[p]=!0);for(p in m)u[p]=!0;var b=c.keysDifference(this._tiles,u);for(r=0;rthis.maxzoom?Math.pow(2,n-this.maxzoom):1;e=new i(r,this.tileSize*a,this.maxzoom),this.loadTile(e,this._tileLoaded.bind(this,e))}return e.uses++,this._tiles[t.id]=e,this.fire("tile.add",{tile:e}),this._source.fire("tile.add",{tile:e}),e},removeTile:function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this.fire("tile.remove",{tile:e}),this._source.fire("tile.remove",{tile:e}),e.uses>0||(e.isRenderable()?this._cache.add(e.coord.wrapped().id,e):(e.aborted=!0,this.abortTile(e),this.unloadTile(e))))},clearTiles:function(){for(var t in this._tiles)this.removeTile(t);this._cache.reset()},tilesIn:function(t){for(var e={},r=this.getIds(),n=1/0,i=1/0,a=-1/0,s=-1/0,c=t[0].zoom,f=0;f=0&&g[1].y>=0){for(var y=[],b=0;b=0&&t%1==0),n(!isNaN(e)&&e>=0&&e%1==0),n(!isNaN(r)&&r>=0&&r%1==0),isNaN(i)&&(i=0),this.z=+t,this.x=+e,this.y=+r,this.w=+i,(i*=2)<0&&(i=-1*i-1);var a=1<e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function l(t,e,r,n,i){var a=Math.max(r,Math.floor(e.y0)),o=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx0,f=e.dx<0,h=a;hu.dy&&(o=c,c=u,u=o),c.dy>f.dy&&(o=c,c=f,f=o),u.dy>f.dy&&(o=u,u=f,f=o),c.dy&&l(f,c,n,i,a),u.dy&&l(f,u,n,i,a)}e.exports=o,o.prototype.toString=function(){return this.z+"/"+this.x+"/"+this.y},o.prototype.toCoordinate=function(t){var e=Math.min(this.z,t),r=Math.pow(2,e),n=this.y,i=this.x+r*this.w;return new a(i,n,e)},o.fromID=function(t){var e=t%32,r=1<0;a--)i+=(e&(n=1<t?new o(this.z-1,this.x,this.y,this.w):new o(this.z-1,Math.floor(this.x/2),Math.floor(this.y/2),this.w)},o.prototype.wrapped=function(){return new o(this.z,this.x,this.y,0)},o.prototype.children=function(t){if(this.z>=t)return[new o(this.z+1,this.x,this.y,this.w)];var e=this.z+1,r=2*this.x,n=2*this.y;return[new o(e,r,n,this.w),new o(e,r+1,n,this.w),new o(e,r,n+1,this.w),new o(e,r+1,n+1,this.w)]},o.cover=function(t,e,r){var n=1<=0&&a<=n)for(s=t;sthis.maxzoom?Math.pow(2,t.coord.z-this.maxzoom):1,n={url:o(t.coord.url(this.tiles,this.maxzoom,this.scheme),this.url),uid:t.uid,coord:t.coord,zoom:t.coord.z,tileSize:this.tileSize*r,source:this.id,overscaling:r,angle:this.map.transform.angle,pitch:this.map.transform.pitch,showCollisionBoxes:this.map.showCollisionBoxes};function i(r,n){if(!t.aborted){if(r)return e(r);t.loadVectorData(n,this.map.style),t.redoWhenDone&&(t.redoWhenDone=!1,t.redoPlacement(this)),e(null),t.reloadCallback&&(this.loadTile(t,t.reloadCallback),t.reloadCallback=null)}}t.workerID?"loading"===t.state?t.reloadCallback=e:(n.rawTileData=t.rawTileData,this.dispatcher.send("reload tile",n,i.bind(this),t.workerID)):t.workerID=this.dispatcher.send("load tile",n,i.bind(this))},abortTile:function(t){this.dispatcher.send("abort tile",{uid:t.uid,source:this.id},null,t.workerID)},unloadTile:function(t){t.unloadVectorData(this.map.painter),this.dispatcher.send("remove tile",{uid:t.uid,source:this.id},null,t.workerID)}})},{"../util/evented":406,"../util/mapbox":411,"../util/util":414,"./load_tilejson":334}],343:[function(t,e,r){"use strict";var n=t("../util/ajax"),i=t("vector-tile"),a=t("pbf"),o=t("./worker_tile");function s(t,e,r){this.actor=t,this.styleLayers=e,r&&(this.loadVectorData=r),this.loading={},this.loaded={}}e.exports=s,s.prototype={loadTile:function(t,e){var r=t.source,n=t.uid;this.loading[r]||(this.loading[r]={});var i=this.loading[r][n]=new o(t);i.abort=this.loadVectorData(t,function(t,a){if(delete this.loading[r][n],t)return e(t);if(!a)return e(null,null);i.data=a.tile,i.parse(i.data,this.styleLayers.getLayerFamilies(),this.actor,a.rawTileData,e),this.loaded[r]=this.loaded[r]||{},this.loaded[r][n]=i}.bind(this))},reloadTile:function(t,e){var r=this.loaded[t.source],n=t.uid;if(r&&r[n]){var i=r[n];i.parse(i.data,this.styleLayers.getLayerFamilies(),this.actor,t.rawTileData,e)}},abortTile:function(t){var e=this.loading[t.source],r=t.uid;e&&e[r]&&e[r].abort&&(e[r].abort(),delete e[r])},removeTile:function(t){var e=this.loaded[t.source],r=t.uid;e&&e[r]&&delete e[r]},loadVectorData:function(t,e){var r=n.getArrayBuffer(t.url,function(t,r){if(t)return e(t);var n=new i.VectorTile(new a(new Uint8Array(r)));e(t,{tile:n,rawTileData:r})}.bind(this));return function(){r.abort()}},redoPlacement:function(t,e){var r=this.loaded[t.source],n=this.loading[t.source],i=t.uid;if(r&&r[i]){var a=r[i].redoPlacement(t.angle,t.pitch,t.showCollisionBoxes);a.result&&e(null,a.result,a.transferables)}else n&&n[i]&&(n[i].angle=t.angle)}}},{"../util/ajax":397,"./worker_tile":346,pbf:451,"vector-tile":544}],344:[function(t,e,r){"use strict";var n=t("../util/util"),i=t("./tile_coord"),a=t("../geo/lng_lat"),o=t("point-geometry"),s=t("../util/evented"),l=t("../util/ajax"),c=t("../data/bucket").EXTENT,u=t("../render/draw_raster").RasterBoundsArray,f=t("../data/buffer"),h=t("../render/vertex_array_object");function d(t,e){this.id=t,this.urls=e.urls,this.coordinates=e.coordinates,l.getVideo(e.urls,function(t,r){if(t)return this.fire("error",{error:t});var n;this.video=r,this.video.loop=!0,this.video.addEventListener("playing",function(){n=this.map.style.animationLoop.set(1/0),this.map._rerender()}.bind(this)),this.video.addEventListener("pause",function(){this.map.style.animationLoop.cancel(n)}.bind(this)),this.map&&(this.video.play(),this.setCoordinates(e.coordinates)),this.fire("load")}.bind(this))}e.exports=d,d.prototype=n.inherit(s,{minzoom:0,maxzoom:22,tileSize:512,roundZoom:!0,getVideo:function(){return this.video},onAdd:function(t){this.map||(this.map=t,this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))},setCoordinates:function(t){this.coordinates=t;var e=this.map,r=t.map(function(t){return e.transform.locationCoordinate(a.convert(t)).zoomTo(0)}),s=this.centerCoord=n.getCoordinatesCenter(r);return s.column=Math.round(s.column),s.row=Math.round(s.row),this.minzoom=this.maxzoom=s.zoom,this._coord=new i(s.zoom,s.column,s.row),this._tileCoords=r.map(function(t){var e=t.zoomTo(s.zoom);return new o(Math.round((e.column-s.column)*c),Math.round((e.row-s.row)*c))}),this.fire("change"),this},_setTile:function(t){this._prepared=!1,this.tile=t;var e=new u;e.emplaceBack(this._tileCoords[0].x,this._tileCoords[0].y,0,0),e.emplaceBack(this._tileCoords[1].x,this._tileCoords[1].y,32767,0),e.emplaceBack(this._tileCoords[3].x,this._tileCoords[3].y,0,32767),e.emplaceBack(this._tileCoords[2].x,this._tileCoords[2].y,32767,32767),this.tile.buckets={},this.tile.boundsBuffer=new f(e.serialize(),u.serialize(),f.BufferType.VERTEX),this.tile.boundsVAO=new h,this.tile.state="loaded"},prepare:function(){if(!(this.video.readyState<2)&&this.tile){var t=this.map.painter.gl;this._prepared?(t.bindTexture(t.TEXTURE_2D,this.tile.texture),t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.video)):(this._prepared=!0,this.tile.texture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this.tile.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.video)),this._currentTime=this.video.currentTime}},loadTile:function(t,e){this._coord&&this._coord.toString()===t.coord.toString()?(this._setTile(t),e(null)):(t.state="errored",e(null))},serialize:function(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}})},{"../data/bucket":301,"../data/buffer":306,"../geo/lng_lat":311,"../render/draw_raster":323,"../render/vertex_array_object":329,"../util/ajax":397,"../util/evented":406,"../util/util":414,"./tile_coord":341,"point-geometry":458}],345:[function(t,e,r){"use strict";var n=t("../util/actor"),i=t("../style/style_layer"),a=t("../util/util"),o=t("./vector_tile_worker_source"),s=t("./geojson_worker_source");function l(t){this.self=t,this.actor=new n(t,this);var e={getLayers:function(){return this.layers}.bind(this),getLayerFamilies:function(){return this.layerFamilies}.bind(this)};this.workerSources={vector:new o(this.actor,e),geojson:new s(this.actor,e)},this.self.registerWorkerSource=function(t,r){if(this.workerSources[t])throw new Error('Worker source with name "'+t+'" already registered.');this.workerSources[t]=new r(this.actor,e)}.bind(this)}function c(t){var e={};for(var r in t){var n=t[r],i=n.ref||n.id,a=t[i];a.layout&&"none"===a.layout.visibility||(e[i]=e[i]||[],r===i?e[i].unshift(n):e[i].push(n))}return e}e.exports=function(t){return new l(t)},a.extend(l.prototype,{"set layers":function(t){this.layers={};for(var e=this,r=[],n=0;n=y.maxzoom||y.layout&&"none"===y.layout.visibility||t.layers&&!t.layers[y.sourceLayer]||((x=a.create({layer:y,index:E++,childLayers:e[S],zoom:this.zoom,overscaling:this.overscaling,showCollisionBoxes:this.showCollisionBoxes,collisionBoxArray:this.collisionBoxArray,symbolQuadsArray:this.symbolQuadsArray,symbolInstancesArray:this.symbolInstancesArray,sourceLayerIndex:M.encode(y.sourceLayer||"_geojsonTileLayer")})).createFilter(),A[y.id]=x,t.layers&&(T[b=y.sourceLayer]=T[b]||{},T[b][y.id]=x)));if(t.layers)for(b in T)1===y.version&&l.warnOnce('Vector tile source "'+this.source+'" layer "'+b+'" does not use vector tile spec v2 and therefore may have some rendering errors.'),(y=t.layers[b])&&L(y,T[b]);else L(t,A);function L(t,e){for(var r=0;r0){for(g=P.length-1;g>=0;g--)P[g].updateIcons(D),P[g].updateFont(I);for(var N in I)I[N]=Object.keys(I[N]).map(Number);D=Object.keys(D),r.send("get glyphs",{uid:this.uid,stacks:I},function(t,e){I=e,F(t)}),D.length?r.send("get icons",{icons:D},function(t,e){D=e,F(t)}):F()}for(g=z.length-1;g>=0;g--)j(this,z[g]);if(0===P.length)return B();function F(t){if(t)return v(t);if(2===++R){for(var e=P.length-1;e>=0;e--)j(k,P[e]);B()}}function j(t,e){if(e.populateArrays(_,I,D),"symbol"!==e.type)for(var r=0;r=0;o--)a[o].placeFeatures(n,r);var s=n.serialize(),l=a.filter(h);return{result:{buckets:l.map(d),collisionTile:s.data},transferables:p(l).concat(s.transferables)}}},{"../data/bucket":301,"../data/feature_index":308,"../symbol/collision_box":366,"../symbol/collision_tile":368,"../symbol/symbol_instances":377,"../symbol/symbol_quads":378,"../util/dictionary_coder":404,"../util/util":414}],347:[function(t,e,r){"use strict";function n(){this.n=0,this.times=[]}e.exports=n,n.prototype.stopped=function(){return this.times=this.times.filter(function(t){return t.time>=(new Date).getTime()}),!this.times.length},n.prototype.set=function(t){return this.times.push({id:this.n,time:t+(new Date).getTime()}),this.n++},n.prototype.cancel=function(t){this.times=this.times.filter(function(e){return e.id!==t})}},{}],348:[function(t,e,r){"use strict";var n=t("../util/evented"),i=t("../util/ajax"),a=t("../util/browser"),o=t("../util/mapbox").normalizeSpriteURL;function s(t){this.base=t,this.retina=a.devicePixelRatio>1;var e=this.retina?"@2x":"";i.getJSON(o(t,e,".json"),function(t,e){t?this.fire("error",{error:t}):(this.data=e,this.img&&this.fire("load"))}.bind(this)),i.getImage(o(t,e,".png"),function(t,e){if(t)this.fire("error",{error:t});else{for(var r=e.getData(),n=e.data=new Uint8Array(r.length),i=0;i1!==this.retina){var t=new s(this.base);t.on("load",function(){this.img=t.img,this.data=t.data,this.retina=t.retina}.bind(this))}},l.prototype={x:0,y:0,width:0,height:0,pixelRatio:1,sdf:!1},s.prototype.getSpritePosition=function(t){if(!this.loaded())return new l;var e=this.data&&this.data[t];return e&&this.img?e:new l}},{"../util/ajax":397,"../util/browser":398,"../util/evented":406,"../util/mapbox":411}],349:[function(t,e,r){"use strict";var n=t("csscolorparser").parseCSSColor,i=t("../util/util"),a=t("./style_function"),o={};e.exports=function t(e){if(a.isFunctionDefinition(e))return i.extend({},e,{stops:e.stops.map(function(e){return[e[0],t(e[1])]})});if("string"==typeof e){if(!o[e]){var r=n(e);if(!r)throw new Error("Invalid color "+e);o[e]=[r[0]/255*r[3],r[1]/255*r[3],r[2]/255*r[3],r[3]]}return o[e]}throw new Error("Invalid color "+e)}},{"../util/util":414,"./style_function":352,csscolorparser:114}],350:[function(t,e,r){"use strict";var n=t("../util/evented"),i=t("./style_layer"),a=t("./image_sprite"),o=t("../symbol/glyph_source"),s=t("../symbol/sprite_atlas"),l=t("../render/line_atlas"),c=t("../util/util"),u=t("../util/ajax"),f=t("../util/mapbox").normalizeStyleURL,h=t("../util/browser"),d=t("../util/dispatcher"),p=t("./animation_loop"),m=t("./validate_style"),v=t("../source/source"),g=t("../source/query_features"),y=t("../source/source_cache"),b=t("./style_spec"),x=t("./style_function");function _(t,e,r){this.animationLoop=e||new p,this.dispatcher=new d(r||1,this),this.spriteAtlas=new s(1024,1024),this.lineAtlas=new l(256,512),this._layers={},this._order=[],this._groups=[],this.sources={},this.zoomHistory={},c.bindAll(["_forwardSourceEvent","_forwardTileEvent","_forwardLayerEvent","_redoPlacement"],this),this._resetUpdates();var n=function(t,e){if(t)this.fire("error",{error:t});else if(!m.emitErrors(this,m(e))){this._loaded=!0,this.stylesheet=e,this.updateClasses();var r=e.sources;for(var n in r)this.addSource(n,r[n]);e.sprite&&(this.sprite=new a(e.sprite),this.sprite.on("load",this.fire.bind(this,"change"))),this.glyphSource=new o(e.glyphs),this._resolve(),this.fire("load")}}.bind(this);"string"==typeof t?u.getJSON(f(t),n):h.frame(n.bind(this,null,t)),this.on("source.load",function(t){var e=t.source;if(e&&e.vectorLayerIds)for(var r in this._layers){var n=this._layers[r];n.source===e.id&&this._validateLayer(n)}})}e.exports=_,_.prototype=c.inherit(n,{_loaded:!1,_validateLayer:function(t){var e=this.sources[t.source];t.sourceLayer&&e&&e.vectorLayerIds&&-1===e.vectorLayerIds.indexOf(t.sourceLayer)&&this.fire("error",{error:new Error('Source layer "'+t.sourceLayer+'" does not exist on source "'+e.id+'" as specified by style layer "'+t.id+'"')})},loaded:function(){if(!this._loaded)return!1;if(Object.keys(this._updates.sources).length)return!1;for(var t in this.sources)if(!this.sources[t].loaded())return!1;return!(this.sprite&&!this.sprite.loaded())},_resolve:function(){var t,e;this._layers={},this._order=this.stylesheet.layers.map(function(t){return t.id});for(var r=0;rMath.floor(t)&&(e.lastIntegerZoom=Math.floor(t+1),e.lastIntegerZoomTime=Date.now()),e.lastZoom=t},_checkLoaded:function(){if(!this._loaded)throw new Error("Style is not done loading")},update:function(t,e){if(!this._updates.changed)return this;if(this._updates.allLayers)this._groupLayers(),this._updateWorkerLayers();else{var r=Object.keys(this._updates.layers);r.length&&this._updateWorkerLayers(r)}var n,i=Object.keys(this._updates.sources);for(n=0;n=0&&this._handleErrors(m.source,"sources."+t,e)?this:(e=new y(t,e,this.dispatcher),this.sources[t]=e,e.style=this,e.on("load",this._forwardSourceEvent).on("error",this._forwardSourceEvent).on("change",this._forwardSourceEvent).on("tile.add",this._forwardTileEvent).on("tile.load",this._forwardTileEvent).on("tile.error",this._forwardTileEvent).on("tile.remove",this._forwardTileEvent).on("tile.stats",this._forwardTileEvent),this._updates.events.push(["source.add",{source:e}]),this._updates.changed=!0,this)},removeSource:function(t){if(this._checkLoaded(),void 0===this.sources[t])throw new Error("There is no source with this ID");var e=this.sources[t];return delete this.sources[t],delete this._updates.sources[t],e.off("load",this._forwardSourceEvent).off("error",this._forwardSourceEvent).off("change",this._forwardSourceEvent).off("tile.add",this._forwardTileEvent).off("tile.load",this._forwardTileEvent).off("tile.error",this._forwardTileEvent).off("tile.remove",this._forwardTileEvent).off("tile.stats",this._forwardTileEvent),this._updates.events.push(["source.remove",{source:e}]),this._updates.changed=!0,this},getSource:function(t){return this.sources[t]&&this.sources[t].getSource()},addLayer:function(t,e){if(this._checkLoaded(),!(t instanceof i)){if(this._handleErrors(m.layer,"layers."+t.id,t,!1,{arrayIndex:-1}))return this;var r=t.ref&&this.getLayer(t.ref);t=i.create(t,r)}return this._validateLayer(t),t.on("error",this._forwardLayerEvent),this._layers[t.id]=t,this._order.splice(e?this._order.indexOf(e):1/0,0,t.id),this._updates.allLayers=!0,t.source&&(this._updates.sources[t.source]=!0),this._updates.events.push(["layer.add",{layer:t}]),this.updateClasses(t.id)},removeLayer:function(t){this._checkLoaded();var e=this._layers[t];if(void 0===e)throw new Error("There is no layer with this ID");for(var r in this._layers)this._layers[r].ref===t&&this.removeLayer(r);return e.off("error",this._forwardLayerEvent),delete this._layers[t],delete this._updates.layers[t],delete this._updates.paintProps[t],this._order.splice(this._order.indexOf(t),1),this._updates.allLayers=!0,this._updates.events.push(["layer.remove",{layer:e}]),this._updates.changed=!0,this},getLayer:function(t){return this._layers[t]},getReferentLayer:function(t){var e=this.getLayer(t);return e.ref&&(e=this.getLayer(e.ref)),e},setLayerZoomRange:function(t,e,r){this._checkLoaded();var n=this.getReferentLayer(t);return n.minzoom===e&&n.maxzoom===r?this:(null!=e&&(n.minzoom=e),null!=r&&(n.maxzoom=r),this._updateLayer(n))},setFilter:function(t,e){this._checkLoaded();var r=this.getReferentLayer(t);return null!==e&&this._handleErrors(m.filter,"layers."+r.id+".filter",e)?this:c.deepEqual(r.filter,e)?this:(r.filter=c.clone(e),this._updateLayer(r))},getFilter:function(t){return this.getReferentLayer(t).filter},setLayoutProperty:function(t,e,r){this._checkLoaded();var n=this.getReferentLayer(t);return c.deepEqual(n.getLayoutProperty(e),r)?this:(n.setLayoutProperty(e,r),this._updateLayer(n))},getLayoutProperty:function(t,e){return this.getReferentLayer(t).getLayoutProperty(e)},setPaintProperty:function(t,e,r,n){this._checkLoaded();var i=this.getLayer(t);if(c.deepEqual(i.getPaintProperty(e,n),r))return this;var a=i.isPaintValueFeatureConstant(e);return i.setPaintProperty(e,r,n),!(r&&x.isFunctionDefinition(r)&&"$zoom"!==r.property&&void 0!==r.property)&&a||(this._updates.layers[t]=!0,i.source&&(this._updates.sources[i.source]=!0)),this.updateClasses(t,e)},getPaintProperty:function(t,e,r){return this.getLayer(t).getPaintProperty(e,r)},updateClasses:function(t,e){if(this._updates.changed=!0,t){var r=this._updates.paintProps;r[t]||(r[t]={}),r[t][e||"all"]=!0}else this._updates.allPaintProps=!0;return this},serialize:function(){return c.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:c.mapObject(this.sources,function(t){return t.serialize()}),layers:this._order.map(function(t){return this._layers[t].serialize()},this)},function(t){return void 0!==t})},_updateLayer:function(t){return this._updates.layers[t.id]=!0,t.source&&(this._updates.sources[t.source]=!0),this._updates.changed=!0,this},_flattenRenderedFeatures:function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0;is.lastIntegerZoom?(r=c+(1-c)*u,f*=2,n=o({zoom:a-1},e),i=o({zoom:a},e)):(r=1-(1-u)*c,i=o({zoom:a},e),n=o({zoom:a+1},e),f/=2),void 0===n||void 0===i?void 0:{from:n,fromScale:f,to:i,toScale:1,t:r}}));var o;if(!this.isFeatureConstant&&!this.isZoomConstant){this.stopZoomLevels=[];for(var s=[],l=this.value.stops,c=0;c=this.maxzoom)||("none"===this.layout.visibility||0===this.paint[this.type+"-opacity"]))},updatePaintTransitions:function(t,e,r,i){for(var a,o=n.extend({},this._paintDeclarations[""]),s=0;s-r/2;){if(--o<0)return!1;s-=t[o].dist(a),a=t[o]}s+=t[o].dist(t[o+1]),o++;var l=[],c=0;for(;sn;)c-=l.shift().angleDelta;if(c>i)return!1;o++,s+=f.dist(h)}return!0}},{}],365:[function(t,e,r){"use strict";var n=t("point-geometry");e.exports=function(t,e,r,i,a){for(var o=[],s=0;s=i&&h.x>=i||(f.x>=i?f=new n(i,f.y+(h.y-f.y)*((i-f.x)/(h.x-f.x)))._round():h.x>=i&&(h=new n(i,f.y+(h.y-f.y)*((i-f.x)/(h.x-f.x)))._round()),f.y>=a&&h.y>=a||(f.y>=a?f=new n(f.x+(h.x-f.x)*((a-f.y)/(h.y-f.y)),a)._round():h.y>=a&&(h=new n(f.x+(h.x-f.x)*((a-f.y)/(h.y-f.y)),a)._round()),l&&f.equals(l[l.length-1])||(l=[f],o.push(l)),l.push(h)))))}return o}},{"point-geometry":458}],366:[function(t,e,r){"use strict";var n=t("../util/struct_array"),i=t("../util/util"),a=t("point-geometry"),o=e.exports=new n({members:[{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Float32",name:"maxScale"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"bbox0"},{type:"Int16",name:"bbox1"},{type:"Int16",name:"bbox2"},{type:"Int16",name:"bbox3"},{type:"Float32",name:"placementScale"}]});i.extendAll(o.prototype.StructType.prototype,{get anchorPoint(){return new a(this.anchorPointX,this.anchorPointY)}})},{"../util/struct_array":412,"../util/util":414,"point-geometry":458}],367:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,c,u){var f=o.top*s-l,h=o.bottom*s+l,d=o.left*s-l,p=o.right*s+l;if(this.boxStartIndex=t.length,c){var m=h-f,v=p-d;if(m>0)if(m=Math.max(10*s,m),u){var g=e[r.segment+1].sub(e[r.segment])._unit()._mult(v),y=[r.sub(g),r.add(g)];this._addLineCollisionBoxes(t,y,r,0,v,m,n,i,a)}else this._addLineCollisionBoxes(t,e,r,r.segment,v,m,n,i,a)}else t.emplaceBack(r.x,r.y,d,f,p,h,1/0,n,i,a,0,0,0,0,0);this.boxEndIndex=t.length}e.exports=n,n.prototype._addLineCollisionBoxes=function(t,e,r,n,i,a,o,s,l){var c=a/2,u=Math.floor(i/c),f=-a/2,h=this.boxes,d=r,p=n+1,m=f;do{if(--p<0)return h;m-=e[p].dist(d),d=e[p]}while(m>-i/2);for(var v=e[p].dist(e[p+1]),g=0;g=e.length)return h;v=e[p].dist(e[p+1])}var b=y-m,x=e[p],_=e[p+1].sub(x)._unit()._mult(b)._add(x)._round(),w=i/2/Math.max(Math.abs(y-f)-c/2,0);t.emplaceBack(_.x,_.y,-a/2,-a/2,a/2,a/2,w,o,s,l,0,0,0,0,0)}return h}},{}],368:[function(t,e,r){"use strict";var n=t("point-geometry"),i=t("../data/bucket").EXTENT,a=t("grid-index");function o(t,e,r){if("object"==typeof t){var n=t;r=e,t=n.angle,e=n.pitch,this.grid=new a(n.grid),this.ignoredGrid=new a(n.ignoredGrid)}else this.grid=new a(i,12,6),this.ignoredGrid=new a(i,12,0);this.angle=t,this.pitch=e;var o=Math.sin(t),s=Math.cos(t);if(this.rotationMatrix=[s,-o,o,s],this.reverseRotationMatrix=[s,o,-o,s],this.yStretch=1/Math.cos(e/180*Math.PI),this.yStretch=Math.pow(this.yStretch,1.3),this.collisionBoxArray=r,0===r.length){r.emplaceBack();r.emplaceBack(0,0,0,-32767,0,32767,32767,0,0,0,0,0,0,0,0,0),r.emplaceBack(i,0,0,-32767,0,32767,32767,0,0,0,0,0,0,0,0,0),r.emplaceBack(0,0,-32767,0,32767,0,32767,0,0,0,0,0,0,0,0,0),r.emplaceBack(0,i,-32767,0,32767,0,32767,0,0,0,0,0,0,0,0,0)}this.tempCollisionBox=r.get(0),this.edges=[r.get(1),r.get(2),r.get(3),r.get(4)]}e.exports=o,o.prototype.serialize=function(){var t={angle:this.angle,pitch:this.pitch,grid:this.grid.toArrayBuffer(),ignoredGrid:this.ignoredGrid.toArrayBuffer()};return{data:t,transferables:[t.grid,t.ignoredGrid]}},o.prototype.minScale=.25,o.prototype.maxScale=2,o.prototype.placeCollisionFeature=function(t,e,r){for(var i=this.collisionBoxArray,a=this.minScale,o=this.rotationMatrix,s=this.yStretch,l=t.boxStartIndex;l=this.maxScale)return a}if(r){var _;if(this.angle){var w=this.reverseRotationMatrix,M=new n(c.x1,c.y1).matMult(w),k=new n(c.x2,c.y1).matMult(w),A=new n(c.x1,c.y2).matMult(w),T=new n(c.x2,c.y2).matMult(w);(_=this.tempCollisionBox).anchorPointX=c.anchorPoint.x,_.anchorPointY=c.anchorPoint.y,_.x1=Math.min(M.x,k.x,A.x,T.x),_.y1=Math.min(M.y,k.x,A.x,T.x),_.x2=Math.max(M.x,k.x,A.x,T.x),_.y2=Math.max(M.y,k.x,A.x,T.x),_.maxScale=c.maxScale}else _=c;for(var E=0;E=this.maxScale)return a}}}return a},o.prototype.queryRenderedSymbols=function(t,e,r,i,a){var o={},s=[],l=this.collisionBoxArray,c=this.rotationMatrix,u=new n(t,e)._matMult(c),f=this.tempCollisionBox;f.anchorX=u.x,f.anchorY=u.y,f.x1=0,f.y1=0,f.x2=r-t,f.y2=i-e,f.maxScale=a,a=f.maxScale;for(var h=[u.x+f.x1/a,u.y+f.y1/a*this.yStretch,u.x+f.x2/a,u.y+f.y2/a*this.yStretch],d=this.grid.query(h[0],h[1],h[2],h[3]),p=this.ignoredGrid.query(h[0],h[1],h[2],h[3]),m=0;m=a&&(o[y][b]=!0,s.push(d[v]))}}return s},o.prototype.getPlacementScale=function(t,e,r,n,i){var a=e.x-n.x,o=e.y-n.y,s=(i.x1-r.x2)/a,l=(i.x2-r.x1)/a,c=(i.y1-r.y2)*this.yStretch/o,u=(i.y2-r.y1)*this.yStretch/o;(isNaN(s)||isNaN(l))&&(s=l=1),(isNaN(c)||isNaN(u))&&(c=u=1);var f=Math.min(Math.max(s,l),Math.max(c,u)),h=i.maxScale,d=r.maxScale;return f>h&&(f=h),f>d&&(f=d),f>t&&f>=i.placementScale&&(t=f),t},o.prototype.insertCollisionFeature=function(t,e,r){for(var n=r?this.ignoredGrid:this.grid,i=this.collisionBoxArray,a=t.boxStartIndex;a=0&&A=0&&T=0&&g+d<=p){var E=new i(A,T,M,b)._round();s&&!a(e,E,c,s,l)||y.push(E)}}v+=w}f||y.length||u||(y=t(e,v/2,o,s,l,c,u,!0,h));return y}(t,p?e/2*u%e:(d/2+2*l)*c*u%e,e,h,r,d*c,p,!1,f)}},{"../symbol/anchor":363,"../util/interpolate":408,"./check_max_angle":364}],370:[function(t,e,r){"use strict";var n=t("shelf-pack"),i=t("../util/util"),a=128;function o(){this.width=a,this.height=a,this.bin=new n(this.width,this.height),this.index={},this.ids={},this.data=new Uint8Array(this.width*this.height)}e.exports=o,o.prototype.getGlyphs=function(){var t,e,r,n={};for(var i in this.ids)e=(t=i.split("#"))[0],r=t[1],n[e]||(n[e]=[]),n[e].push(r);return n},o.prototype.getRects=function(){var t,e,r,n={};for(var i in this.ids)e=(t=i.split("#"))[0],r=t[1],n[e]||(n[e]={}),n[e][r]=this.index[i];return n},o.prototype.addGlyph=function(t,e,r,n){if(!r)return null;var a=e+"#"+r.id;if(this.index[a])return this.ids[a].indexOf(t)<0&&this.ids[a].push(t),this.index[a];if(!r.bitmap)return null;var o=r.width+2*n,s=r.height+2*n,l=o+2,c=s+2;l+=4-l%4,c+=4-c%4;var u=this.bin.packOne(l,c);if(u||(this.resize(),u=this.bin.packOne(l,c)),!u)return i.warnOnce("glyph bitmap overflow"),null;this.index[a]=u,this.ids[a]=[t];for(var f=this.data,h=r.bitmap,d=0;d=2048||e>=2048)){this.texture&&(this.gl&&this.gl.deleteTexture(this.texture),this.texture=null),this.width*=4,this.height*=4,this.bin.resize(this.width,this.height);for(var r=new ArrayBuffer(this.width*this.height),n=0;n65535)return r("glyphs > 65535 not supported");void 0===this.loading[t]&&(this.loading[t]={});var n=this.loading[t];if(n[e])n[e].push(r);else{n[e]=[r];var o=function(t,e,r,n){return n=n||"abc",r.replace("{s}",n[t.length%n.length]).replace("{fontstack}",t).replace("{range}",e)}(t,256*e+"-"+(256*e+255),this.url);i(o,function(t,r){for(var i=!t&&new a(new s(new Uint8Array(r))),o=0;on&&null!==f){var b=v[f+1].x;m=Math.max(b,m);for(var x=f+1;x<=g;x++)v[x].y+=r,v[x].x-=b;if(c){var _=f;i[v[f].codePoint]&&_--,o(v,e,d,_,c)}d=f+1,f=null,h+=b,p++}a[y.codePoint]&&(f=g)}var w=v[v.length-1],M=w.x+e[w.codePoint].advance;m=Math.max(m,M);var k=(p+1)*r;o(v,e,d,v.length-1,c),function(t,e,r,n,i,a,o,s){for(var l=(e-r)*i+s[0],c=(-n*(o+1)+.5)*a+s[1],u=0;u1?2:1,this.canvas&&(this.canvas.width=this.width*this.pixelRatio,this.canvas.height=this.height*this.pixelRatio)),this.sprite=t},o.prototype.addIcons=function(t,e){for(var r=0;r1)return;l?(clearTimeout(l),l=null,f("dblclick",e)):l=setTimeout(u,300)},!1),r.addEventListener("touchend",function(t){h("touchend",t)},!1),r.addEventListener("touchmove",function(t){h("touchmove",t)},!1),r.addEventListener("touchcancel",function(t){h("touchcancel",t)},!1),r.addEventListener("click",function(t){n.mousePos(r,t).equals(s)&&f("click",t)},!1),r.addEventListener("dblclick",function(t){f("dblclick",t),t.preventDefault()},!1),r.addEventListener("contextmenu",function(t){o=t,t.preventDefault()},!1)}},{"../util/dom":400,"./handler/box_zoom":385,"./handler/dblclick_zoom":386,"./handler/drag_pan":387,"./handler/drag_rotate":388,"./handler/keyboard":389,"./handler/scroll_zoom":390,"./handler/touch_zoom_rotate":391,"point-geometry":458}],380:[function(t,e,r){"use strict";var n=t("../util/util"),i=t("../util/interpolate"),a=t("../util/browser"),o=t("../geo/lng_lat"),s=t("../geo/lng_lat_bounds"),l=t("point-geometry"),c=e.exports=function(){};n.extend(c.prototype,{getCenter:function(){return this.transform.center},setCenter:function(t,e){return this.jumpTo({center:t},e),this},panBy:function(t,e,r){return this.panTo(this.transform.center,n.extend({offset:l.convert(t).mult(-1)},e),r),this},panTo:function(t,e,r){return this.easeTo(n.extend({center:t},e),r)},getZoom:function(){return this.transform.zoom},setZoom:function(t,e){return this.jumpTo({zoom:t},e),this},zoomTo:function(t,e,r){return this.easeTo(n.extend({zoom:t},e),r)},zoomIn:function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},zoomOut:function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},getBearing:function(){return this.transform.bearing},setBearing:function(t,e){return this.jumpTo({bearing:t},e),this},rotateTo:function(t,e,r){return this.easeTo(n.extend({bearing:t},e),r)},resetNorth:function(t,e){return this.rotateTo(0,n.extend({duration:1e3},t),e),this},snapToNorth:function(t,e){return Math.abs(this.getBearing())180&&(r.center.lng>0&&f.lng<0?f.lng+=360:r.center.lng<0&&f.lng>0&&(f.lng-=360));var m=r.zoomScale(h-s),v=r.point,g="center"in t?r.project(f).sub(a.div(m)):v,y=r.worldSize,b=t.curve,x=Math.max(r.width,r.height),_=x/m,w=g.sub(v).mag();if("minZoom"in t){var M=n.clamp(Math.min(t.minZoom,s,h),r.minZoom,r.maxZoom),k=x/r.zoomScale(M-s);b=Math.sqrt(k/w*2)}var A=b*b;function T(t){var e=(_*_-x*x+(t?-1:1)*A*A*w*w)/(2*(t?_:x)*A*w);return Math.log(Math.sqrt(e*e+1)-e)}function E(t){return(Math.exp(t)-Math.exp(-t))/2}function S(t){return(Math.exp(t)+Math.exp(-t))/2}var L=T(0),C=function(t){return S(L)/S(L+b*t)},P=function(t){return x*((S(L)*(E(e=L+b*t)/S(e))-E(L))/A)/w;var e},z=(T(1)-L)/b;if(Math.abs(w)<1e-6){if(Math.abs(x-_)<1e-6)return this.easeTo(t);var O=_=0)return!1;return!0})).join(" | ")},o.prototype=a.inherit(n,{options:{position:"bottom-right"},onAdd:function(t){var e=this._container=i.create("div","mapboxgl-ctrl-attrib",t.getContainer());return this._update(),t.on("source.load",this._update.bind(this)),t.on("source.change",this._update.bind(this)),t.on("source.remove",this._update.bind(this)),t.on("moveend",this._updateEditLink.bind(this)),e},_update:function(){this._map.style&&(this._container.innerHTML=o.createAttributionString(this._map.style.sources)),this._editLink=this._container.getElementsByClassName("mapbox-improve-map")[0],this._updateEditLink()},_updateEditLink:function(){if(this._editLink){var t=this._map.getCenter();this._editLink.href="https://www.mapbox.com/map-feedback/#/"+t.lng+"/"+t.lat+"/"+Math.round(this._map.getZoom()+1)}}})},{"../../util/dom":400,"../../util/util":414,"./control":382}],382:[function(t,e,r){"use strict";var n=t("../../util/util"),i=t("../../util/evented");function a(){}e.exports=a,a.prototype={addTo:function(t){this._map=t;var e=this._container=this.onAdd(t);if(this.options&&this.options.position){var r=this.options.position,n=t._controlCorners[r];e.className+=" mapboxgl-ctrl",-1!==r.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e)}return this},remove:function(){return this._container.parentNode.removeChild(this._container),this.onRemove&&this.onRemove(this._map),this._map=null,this}},n.extend(a.prototype,i)},{"../../util/evented":406,"../../util/util":414}],383:[function(t,e,r){"use strict";var n=t("./control"),i=t("../../util/browser"),a=t("../../util/dom"),o=t("../../util/util");e.exports=l;var s={enableHighAccuracy:!1,timeout:6e3};function l(t){o.setOptions(this,t)}l.prototype=o.inherit(n,{options:{position:"top-right"},onAdd:function(t){var e=this._container=a.create("div","mapboxgl-ctrl-group",t.getContainer());return i.supportsGeolocation?(this._container.addEventListener("contextmenu",this._onContextMenu.bind(this)),this._geolocateButton=a.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.addEventListener("click",this._onClickGeolocate.bind(this)),e):e},_onContextMenu:function(t){t.preventDefault()},_onClickGeolocate:function(){navigator.geolocation.getCurrentPosition(this._success.bind(this),this._error.bind(this),s),this._timeoutId=setTimeout(this._finish.bind(this),1e4)},_success:function(t){this._map.jumpTo({center:[t.coords.longitude,t.coords.latitude],zoom:17,bearing:0,pitch:0}),this.fire("geolocate",t),this._finish()},_error:function(t){this.fire("error",t),this._finish()},_finish:function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}})},{"../../util/browser":398,"../../util/dom":400,"../../util/util":414,"./control":382}],384:[function(t,e,r){"use strict";var n=t("./control"),i=t("../../util/dom"),a=t("../../util/util");function o(t){a.setOptions(this,t)}function s(t){return new MouseEvent(t.type,{button:2,buttons:2,bubbles:!0,cancelable:!0,detail:t.detail,view:t.view,screenX:t.screenX,screenY:t.screenY,clientX:t.clientX,clientY:t.clientY,movementX:t.movementX,movementY:t.movementY,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey})}e.exports=o,o.prototype=a.inherit(n,{options:{position:"top-right"},onAdd:function(t){var e="mapboxgl-ctrl",r=this._container=i.create("div",e+"-group",t.getContainer());return this._container.addEventListener("contextmenu",this._onContextMenu.bind(this)),this._zoomInButton=this._createButton(e+"-icon "+e+"-zoom-in",t.zoomIn.bind(t)),this._zoomOutButton=this._createButton(e+"-icon "+e+"-zoom-out",t.zoomOut.bind(t)),this._compass=this._createButton(e+"-icon "+e+"-compass",t.resetNorth.bind(t)),this._compassArrow=i.create("div","arrow",this._compass),this._compass.addEventListener("mousedown",this._onCompassDown.bind(this)),this._onCompassMove=this._onCompassMove.bind(this),this._onCompassUp=this._onCompassUp.bind(this),t.on("rotate",this._rotateCompassArrow.bind(this)),this._rotateCompassArrow(),this._el=t.getCanvasContainer(),r},_onContextMenu:function(t){t.preventDefault()},_onCompassDown:function(t){0===t.button&&(i.disableDrag(),document.addEventListener("mousemove",this._onCompassMove),document.addEventListener("mouseup",this._onCompassUp),this._el.dispatchEvent(s(t)),t.stopPropagation())},_onCompassMove:function(t){0===t.button&&(this._el.dispatchEvent(s(t)),t.stopPropagation())},_onCompassUp:function(t){0===t.button&&(document.removeEventListener("mousemove",this._onCompassMove),document.removeEventListener("mouseup",this._onCompassUp),i.enableDrag(),this._el.dispatchEvent(s(t)),t.stopPropagation())},_createButton:function(t,e){var r=i.create("button",t,this._container);return r.type="button",r.addEventListener("click",function(){e()}),r},_rotateCompassArrow:function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t}})},{"../../util/dom":400,"../../util/util":414,"./control":382}],385:[function(t,e,r){"use strict";var n=t("../../util/dom"),i=t("../../geo/lng_lat_bounds"),a=t("../../util/util");function o(t){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),a.bindHandlers(this)}e.exports=o,o.prototype={_enabled:!1,_active:!1,isEnabled:function(){return this._enabled},isActive:function(){return this._active},enable:function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onMouseDown,!1),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onMouseDown),this._enabled=!1)},_onMouseDown:function(t){t.shiftKey&&0===t.button&&(document.addEventListener("mousemove",this._onMouseMove,!1),document.addEventListener("keydown",this._onKeyDown,!1),document.addEventListener("mouseup",this._onMouseUp,!1),n.disableDrag(),this._startPos=n.mousePos(this._el,t),this._active=!0)},_onMouseMove:function(t){var e=this._startPos,r=n.mousePos(this._el,t);this._box||(this._box=n.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var i=Math.min(e.x,r.x),a=Math.max(e.x,r.x),o=Math.min(e.y,r.y),s=Math.max(e.y,r.y);n.setTransform(this._box,"translate("+i+"px,"+o+"px)"),this._box.style.width=a-i+"px",this._box.style.height=s-o+"px"},_onMouseUp:function(t){if(0===t.button){var e=this._startPos,r=n.mousePos(this._el,t),a=new i(this._map.unproject(e),this._map.unproject(r));this._finish(),e.x===r.x&&e.y===r.y?this._fireEvent("boxzoomcancel",t):this._map.fitBounds(a,{linear:!0}).fire("boxzoomend",{originalEvent:t,boxZoomBounds:a})}},_onKeyDown:function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},_finish:function(){this._active=!1,document.removeEventListener("mousemove",this._onMouseMove,!1),document.removeEventListener("keydown",this._onKeyDown,!1),document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.parentNode.removeChild(this._box),this._box=null),n.enableDrag()},_fireEvent:function(t,e){return this._map.fire(t,{originalEvent:e})}}},{"../../geo/lng_lat_bounds":312,"../../util/dom":400,"../../util/util":414}],386:[function(t,e,r){"use strict";function n(t){this._map=t,this._onDblClick=this._onDblClick.bind(this)}e.exports=n,n.prototype={_enabled:!1,isEnabled:function(){return this._enabled},enable:function(){this.isEnabled()||(this._map.on("dblclick",this._onDblClick),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._map.off("dblclick",this._onDblClick),this._enabled=!1)},_onDblClick:function(t){this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)}}},{}],387:[function(t,e,r){"use strict";var n=t("../../util/dom"),i=t("../../util/util");e.exports=o;var a=i.bezier(0,0,.3,1);function o(t){this._map=t,this._el=t.getCanvasContainer(),i.bindHandlers(this)}o.prototype={_enabled:!1,_active:!1,isEnabled:function(){return this._enabled},isActive:function(){return this._active},enable:function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._el.addEventListener("touchstart",this._onDown),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._el.removeEventListener("touchstart",this._onDown),this._enabled=!1)},_onDown:function(t){this._ignoreEvent(t)||this.isActive()||(t.touches?(document.addEventListener("touchmove",this._onMove),document.addEventListener("touchend",this._onTouchEnd)):(document.addEventListener("mousemove",this._onMove),document.addEventListener("mouseup",this._onMouseUp)),this._active=!1,this._startPos=this._pos=n.mousePos(this._el,t),this._inertia=[[Date.now(),this._pos]])},_onMove:function(t){if(!this._ignoreEvent(t)){this.isActive()||(this._active=!0,this._fireEvent("dragstart",t),this._fireEvent("movestart",t));var e=n.mousePos(this._el,t),r=this._map;r.stop(),this._drainInertiaBuffer(),this._inertia.push([Date.now(),e]),r.transform.setLocationAtPoint(r.transform.pointLocation(this._pos),e),this._fireEvent("drag",t),this._fireEvent("move",t),this._pos=e,t.preventDefault()}},_onUp:function(t){if(this.isActive()){this._active=!1,this._fireEvent("dragend",t),this._drainInertiaBuffer();var e=function(){this._fireEvent("moveend",t)}.bind(this),r=this._inertia;if(r.length<2)e();else{var n=r[r.length-1],i=r[0],o=n[1].sub(i[1]),s=(n[0]-i[0])/1e3;if(0===s||n[1].equals(i[1]))e();else{var l=o.mult(.3/s),c=l.mag();c>1400&&(c=1400,l._unit()._mult(c));var u=c/750,f=l.mult(-u/2);this._map.panBy(f,{duration:1e3*u,easing:a,noMoveStart:!0},{originalEvent:t})}}}},_onMouseUp:function(t){this._ignoreEvent(t)||(this._onUp(t),document.removeEventListener("mousemove",this._onMove),document.removeEventListener("mouseup",this._onMouseUp))},_onTouchEnd:function(t){this._ignoreEvent(t)||(this._onUp(t),document.removeEventListener("touchmove",this._onMove),document.removeEventListener("touchend",this._onTouchEnd))},_fireEvent:function(t,e){return this._map.fire(t,{originalEvent:e})},_ignoreEvent:function(t){var e=this._map;if(e.boxZoom&&e.boxZoom.isActive())return!0;if(e.dragRotate&&e.dragRotate.isActive())return!0;if(t.touches)return t.touches.length>1;if(t.ctrlKey)return!0;return"mousemove"===t.type?!1&t.buttons:0!==t.button},_drainInertiaBuffer:function(){for(var t=this._inertia,e=Date.now();t.length>0&&e-t[0][0]>160;)t.shift()}}},{"../../util/dom":400,"../../util/util":414}],388:[function(t,e,r){"use strict";var n=t("../../util/dom"),i=t("point-geometry"),a=t("../../util/util");e.exports=s;var o=a.bezier(0,0,.25,1);function s(t,e){this._map=t,this._el=t.getCanvasContainer(),this._bearingSnap=e.bearingSnap,a.bindHandlers(this)}s.prototype={_enabled:!1,_active:!1,isEnabled:function(){return this._enabled},isActive:function(){return this._active},enable:function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._enabled=!1)},_onDown:function(t){if(!this._ignoreEvent(t)&&!this.isActive()){document.addEventListener("mousemove",this._onMove),document.addEventListener("mouseup",this._onUp),this._active=!1,this._inertia=[[Date.now(),this._map.getBearing()]],this._startPos=this._pos=n.mousePos(this._el,t),this._center=this._map.transform.centerPoint;var e=this._startPos.sub(this._center);e.mag()<200&&(this._center=this._startPos.add(new i(-200,0)._rotate(e.angle()))),t.preventDefault()}},_onMove:function(t){if(!this._ignoreEvent(t)){this.isActive()||(this._active=!0,this._fireEvent("rotatestart",t),this._fireEvent("movestart",t));var e=this._map;e.stop();var r=this._pos,i=n.mousePos(this._el,t),a=this._center,o=r.sub(a).angleWith(i.sub(a))/Math.PI*180,s=e.getBearing()-o,l=this._inertia,c=l[l.length-1];this._drainInertiaBuffer(),l.push([Date.now(),e._normalizeBearing(s,c[1])]),e.transform.bearing=s,this._fireEvent("rotate",t),this._fireEvent("move",t),this._pos=i}},_onUp:function(t){if(!this._ignoreEvent(t)&&(document.removeEventListener("mousemove",this._onMove),document.removeEventListener("mouseup",this._onUp),this.isActive())){this._active=!1,this._fireEvent("rotateend",t),this._drainInertiaBuffer();var e=this._map,r=e.getBearing(),n=this._inertia,i=function(){Math.abs(r)180&&(d=180);var p=d/180;c+=f*d*(p/2),Math.abs(e._normalizeBearing(c,0))1;var r=t.ctrlKey?1:2,n=t.ctrlKey?0:2;return"mousemove"===t.type?t.buttons&0===r:t.button!==n},_drainInertiaBuffer:function(){for(var t=this._inertia,e=Date.now();t.length>0&&e-t[0][0]>160;)t.shift()}}},{"../../util/dom":400,"../../util/util":414,"point-geometry":458}],389:[function(t,e,r){"use strict";e.exports=n;function n(t){this._map=t,this._el=t.getCanvasContainer(),this._onKeyDown=this._onKeyDown.bind(this)}n.prototype={_enabled:!1,isEnabled:function(){return this._enabled},enable:function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},_onKeyDown:function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=this._map,r={originalEvent:t};if(!e.isEasing())switch(t.keyCode){case 61:case 107:case 171:case 187:e.zoomTo(Math.round(e.getZoom())+(t.shiftKey?2:1),r);break;case 189:case 109:case 173:e.zoomTo(Math.round(e.getZoom())-(t.shiftKey?2:1),r);break;case 37:t.shiftKey?e.easeTo({bearing:e.getBearing()-2},r):(t.preventDefault(),e.panBy([-80,0],r));break;case 39:t.shiftKey?e.easeTo({bearing:e.getBearing()+2},r):(t.preventDefault(),e.panBy([80,0],r));break;case 38:t.shiftKey?e.easeTo({pitch:e.getPitch()+5},r):(t.preventDefault(),e.panBy([0,-80],r));break;case 40:t.shiftKey?e.easeTo({pitch:Math.max(e.getPitch()-5,0)},r):(t.preventDefault(),e.panBy([0,80],r))}}}}},{}],390:[function(t,e,r){"use strict";var n=t("../../util/dom"),i=t("../../util/browser"),a=t("../../util/util");e.exports=c;var o="undefined"!=typeof navigator?navigator.userAgent.toLowerCase():"",s=-1!==o.indexOf("firefox"),l=-1!==o.indexOf("safari")&&-1===o.indexOf("chrom");function c(t){this._map=t,this._el=t.getCanvasContainer(),a.bindHandlers(this)}c.prototype={_enabled:!1,isEnabled:function(){return this._enabled},enable:function(){this.isEnabled()||(this._el.addEventListener("wheel",this._onWheel,!1),this._el.addEventListener("mousewheel",this._onWheel,!1),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("wheel",this._onWheel),this._el.removeEventListener("mousewheel",this._onWheel),this._enabled=!1)},_onWheel:function(t){var e;"wheel"===t.type?(e=t.deltaY,s&&t.deltaMode===window.WheelEvent.DOM_DELTA_PIXEL&&(e/=i.devicePixelRatio),t.deltaMode===window.WheelEvent.DOM_DELTA_LINE&&(e*=40)):"mousewheel"===t.type&&(e=-t.wheelDeltaY,l&&(e/=3));var r=i.now(),a=r-(this._time||0);this._pos=n.mousePos(this._el,t),this._time=r,0!==e&&e%4.000244140625==0?(this._type="wheel",e=Math.floor(e/4)):0!==e&&Math.abs(e)<4?this._type="trackpad":a>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40)):this._type||(this._type=Math.abs(a*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&this._zoom(-e,t),t.preventDefault()},_onTimeout:function(){this._type="wheel",this._zoom(-this._lastValue)},_zoom:function(t,e){if(0!==t){var r=this._map,n=2/(1+Math.exp(-Math.abs(t/100)));t<0&&0!==n&&(n=1/n);var i=r.ease?r.ease.to:r.transform.scale,a=r.transform.scaleZoom(i*n);r.zoomTo(a,{duration:0,around:r.unproject(this._pos),delayEndEvents:200},{originalEvent:e})}}}},{"../../util/browser":398,"../../util/dom":400,"../../util/util":414}],391:[function(t,e,r){"use strict";var n=t("../../util/dom"),i=t("../../util/util");e.exports=o;var a=i.bezier(0,0,.15,1);function o(t){this._map=t,this._el=t.getCanvasContainer(),i.bindHandlers(this)}o.prototype={_enabled:!1,isEnabled:function(){return this._enabled},enable:function(){this.isEnabled()||(this._el.addEventListener("touchstart",this._onStart,!1),this._enabled=!0)},disable:function(){this.isEnabled()&&(this._el.removeEventListener("touchstart",this._onStart),this._enabled=!1)},disableRotation:function(){this._rotationDisabled=!0},enableRotation:function(){this._rotationDisabled=!1},_onStart:function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]);this._startVec=e.sub(r),this._startScale=this._map.transform.scale,this._startBearing=this._map.transform.bearing,this._gestureIntent=void 0,this._inertia=[],document.addEventListener("touchmove",this._onMove,!1),document.addEventListener("touchend",this._onEnd,!1)}},_onMove:function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]),i=e.add(r).div(2),a=e.sub(r),o=a.mag()/this._startVec.mag(),s=this._rotationDisabled?0:180*a.angleWith(this._startVec)/Math.PI,l=this._map;if(this._gestureIntent){var c={duration:0,around:l.unproject(i)};"rotate"===this._gestureIntent&&(c.bearing=this._startBearing+s),"zoom"!==this._gestureIntent&&"rotate"!==this._gestureIntent||(c.zoom=l.transform.scaleZoom(this._startScale*o)),l.stop(),this._drainInertiaBuffer(),this._inertia.push([Date.now(),o,i]),l.easeTo(c,{originalEvent:t})}else{var u=Math.abs(1-o)>.15;Math.abs(s)>4?this._gestureIntent="rotate":u&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._startVec=a,this._startScale=l.transform.scale,this._startBearing=l.transform.bearing)}t.preventDefault()}},_onEnd:function(t){document.removeEventListener("touchmove",this._onMove),document.removeEventListener("touchend",this._onEnd),this._drainInertiaBuffer();var e=this._inertia,r=this._map;if(e.length<2)r.snapToNorth({},{originalEvent:t});else{var n=e[e.length-1],i=e[0],o=r.transform.scaleZoom(this._startScale*n[1]),s=r.transform.scaleZoom(this._startScale*i[1]),l=o-s,c=(n[0]-i[0])/1e3,u=n[2];if(0!==c&&o!==s){var f=.15*l/c;Math.abs(f)>2.5&&(f=f>0?2.5:-2.5);var h=1e3*Math.abs(f/(12*.15)),d=o+f*h/2e3;d<0&&(d=0),r.easeTo({zoom:d,duration:h,easing:a,around:r.unproject(u)},{originalEvent:t})}else r.snapToNorth({},{originalEvent:t})}},_drainInertiaBuffer:function(){for(var t=this._inertia,e=Date.now();t.length>2&&e-t[0][0]>160;)t.shift()}}},{"../../util/dom":400,"../../util/util":414}],392:[function(t,e,r){"use strict";e.exports=i;var n=t("../util/util");function i(){n.bindAll(["_onHashChange","_updateHash"],this)}i.prototype={addTo:function(t){return this._map=t,window.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},remove:function(){return window.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),delete this._map,this},_onHashChange:function(){var t=location.hash.replace("#","").split("/");return t.length>=3&&(this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:+(t[3]||0)}),!0)},_updateHash:function(){var t=this._map.getCenter(),e=this._map.getZoom(),r=this._map.getBearing(),n=Math.max(0,Math.ceil(Math.log(e)/Math.LN2)),i="#"+Math.round(100*e)/100+"/"+t.lat.toFixed(n)+"/"+t.lng.toFixed(n)+(r?"/"+Math.round(10*r)/10:"");window.history.replaceState("","",i)}}},{"../util/util":414}],393:[function(t,e,r){"use strict";var n=t("../util/canvas"),i=t("../util/util"),a=t("../util/browser"),o=t("../util/browser").window,s=t("../util/evented"),l=t("../util/dom"),c=t("../style/style"),u=t("../style/animation_loop"),f=t("../render/painter"),h=t("../geo/transform"),d=t("./hash"),p=t("./bind_handlers"),m=t("./camera"),v=t("../geo/lng_lat"),g=t("../geo/lng_lat_bounds"),y=t("point-geometry"),b=t("./control/attribution"),x={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:20,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,workerCount:Math.max(a.hardwareConcurrency-1,1)},_=e.exports=function(t){if((t=i.extend({},x,t)).workerCount<1)throw new Error("workerCount must an integer greater than or equal to 1.");this._interactive=t.interactive,this._failIfMajorPerformanceCaveat=t.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=t.preserveDrawingBuffer,this._trackResize=t.trackResize,this._workerCount=t.workerCount,this._bearingSnap=t.bearingSnap,"string"==typeof t.container?this._container=document.getElementById(t.container):this._container=t.container,this.animationLoop=new u,this.transform=new h(t.minZoom,t.maxZoom),t.maxBounds&&this.setMaxBounds(t.maxBounds),i.bindAll(["_forwardStyleEvent","_forwardSourceEvent","_forwardLayerEvent","_forwardTileEvent","_onStyleLoad","_onStyleChange","_onSourceAdd","_onSourceRemove","_onSourceUpdate","_onWindowOnline","_onWindowResize","_update","_render"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),this.on("moveend",function(){this.animationLoop.set(300),this._rerender()}.bind(this)),void 0!==o&&(o.addEventListener("online",this._onWindowOnline,!1),o.addEventListener("resize",this._onWindowResize,!1)),p(this,t),this._hash=t.hash&&(new d).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:t.center,zoom:t.zoom,bearing:t.bearing,pitch:t.pitch}),this.stacks={},this._classes=[],this.resize(),t.classes&&this.setClasses(t.classes),t.style&&this.setStyle(t.style),t.attributionControl&&this.addControl(new b(t.attributionControl));var e=this.fire.bind(this,"error");this.on("style.error",e),this.on("source.error",e),this.on("tile.error",e),this.on("layer.error",e)};function w(t){t.parentNode&&t.parentNode.removeChild(t)}i.extend(_.prototype,s),i.extend(_.prototype,m.prototype),i.extend(_.prototype,{addControl:function(t){return t.addTo(this),this},addClass:function(t,e){return this._classes.indexOf(t)>=0||""===t?this:(this._classes.push(t),this._classOptions=e,this.style&&this.style.updateClasses(),this._update(!0))},removeClass:function(t,e){var r=this._classes.indexOf(t);return r<0||""===t?this:(this._classes.splice(r,1),this._classOptions=e,this.style&&this.style.updateClasses(),this._update(!0))},setClasses:function(t,e){for(var r={},n=0;n=0},getClasses:function(){return this._classes},resize:function(){var t=0,e=0;return this._container&&(t=this._container.offsetWidth||400,e=this._container.offsetHeight||300),this._canvas.resize(t,e),this.transform.resize(t,e),this.painter.resize(t,e),this.fire("movestart").fire("move").fire("resize").fire("moveend")},getBounds:function(){var t=new g(this.transform.pointLocation(new y(0,0)),this.transform.pointLocation(this.transform.size));return(this.transform.angle||this.transform.pitch)&&(t.extend(this.transform.pointLocation(new y(this.transform.size.x,0))),t.extend(this.transform.pointLocation(new y(0,this.transform.size.y)))),t},setMaxBounds:function(t){if(t){var e=g.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null!==t&&void 0!==t||(this.transform.lngRange=[],this.transform.latRange=[],this._update());return this},setMinZoom:function(t){if((t=null===t||void 0===t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom&&t<=20)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be between the current minZoom and 20, inclusive")},project:function(t){return this.transform.locationPoint(v.convert(t))},unproject:function(t){return this.transform.pointLocation(y.convert(t))},queryRenderedFeatures:function(){var t,e,r={};return 2===arguments.length?(t=arguments[0],r=arguments[1]):1===arguments.length&&((e=arguments[0])instanceof y||Array.isArray(e))?t=arguments[0]:1===arguments.length&&(r=arguments[0]),this.style.queryRenderedFeatures(this._makeQueryGeometry(t),r,this.transform.zoom,this.transform.angle)},_makeQueryGeometry:function(t){var e;if(void 0===t&&(t=[y.convert([0,0]),y.convert([this.transform.width,this.transform.height])]),t instanceof y||"number"==typeof t[0]){e=[y.convert(t)]}else{var r=[y.convert(t[0]),y.convert(t[1])];e=[r[0],new y(r[1].x,r[0].y),r[1],new y(r[0].x,r[1].y),r[0]]}return e=e.map(function(t){return this.transform.pointCoordinate(t)}.bind(this))},querySourceFeatures:function(t,e){return this.style.querySourceFeatures(t,e)},setStyle:function(t){return this.style&&(this.style.off("load",this._onStyleLoad).off("error",this._forwardStyleEvent).off("change",this._onStyleChange).off("source.add",this._onSourceAdd).off("source.remove",this._onSourceRemove).off("source.load",this._onSourceUpdate).off("source.error",this._forwardSourceEvent).off("source.change",this._onSourceUpdate).off("layer.add",this._forwardLayerEvent).off("layer.remove",this._forwardLayerEvent).off("layer.error",this._forwardLayerEvent).off("tile.add",this._forwardTileEvent).off("tile.remove",this._forwardTileEvent).off("tile.load",this._update).off("tile.error",this._forwardTileEvent).off("tile.stats",this._forwardTileEvent)._remove(),this.off("rotate",this.style._redoPlacement),this.off("pitch",this.style._redoPlacement)),t?(this.style=t instanceof c?t:new c(t,this.animationLoop,this._workerCount),this.style.on("load",this._onStyleLoad).on("error",this._forwardStyleEvent).on("change",this._onStyleChange).on("source.add",this._onSourceAdd).on("source.remove",this._onSourceRemove).on("source.load",this._onSourceUpdate).on("source.error",this._forwardSourceEvent).on("source.change",this._onSourceUpdate).on("layer.add",this._forwardLayerEvent).on("layer.remove",this._forwardLayerEvent).on("layer.error",this._forwardLayerEvent).on("tile.add",this._forwardTileEvent).on("tile.remove",this._forwardTileEvent).on("tile.load",this._update).on("tile.error",this._forwardTileEvent).on("tile.stats",this._forwardTileEvent),this.on("rotate",this.style._redoPlacement),this.on("pitch",this.style._redoPlacement),this):(this.style=null,this)},getStyle:function(){if(this.style)return this.style.serialize()},addSource:function(t,e){return this.style.addSource(t,e),this._update(!0),this},addSourceType:function(t,e,r){return this.style.addSourceType(t,e,r)},removeSource:function(t){return this.style.removeSource(t),this._update(!0),this},getSource:function(t){return this.style.getSource(t)},addLayer:function(t,e){return this.style.addLayer(t,e),this._update(!0),this},removeLayer:function(t){return this.style.removeLayer(t),this._update(!0),this},getLayer:function(t){return this.style.getLayer(t)},setFilter:function(t,e){return this.style.setFilter(t,e),this._update(!0),this},setLayerZoomRange:function(t,e,r){return this.style.setLayerZoomRange(t,e,r),this._update(!0),this},getFilter:function(t){return this.style.getFilter(t)},setPaintProperty:function(t,e,r,n){return this.style.setPaintProperty(t,e,r,n),this._update(!0),this},getPaintProperty:function(t,e,r){return this.style.getPaintProperty(t,e,r)},setLayoutProperty:function(t,e,r){return this.style.setLayoutProperty(t,e,r),this._update(!0),this},getLayoutProperty:function(t,e){return this.style.getLayoutProperty(t,e)},getContainer:function(){return this._container},getCanvasContainer:function(){return this._canvasContainer},getCanvas:function(){return this._canvas.getElement()},_setupContainer:function(){var t=this._container;t.classList.add("mapboxgl-map");var e=this._canvasContainer=l.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=new n(this,e);var r=this._controlContainer=l.create("div","mapboxgl-control-container",t),i=this._controlCorners={};["top-left","top-right","bottom-left","bottom-right"].forEach(function(t){i[t]=l.create("div","mapboxgl-ctrl-"+t,r)})},_setupPainter:function(){var t=this._canvas.getWebGLContext({failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer});t?this.painter=new f(t,this.transform):this.fire("error",{error:new Error("Failed to initialize WebGL")})},_contextLost:function(t){t.preventDefault(),this._frameId&&a.cancelFrame(this._frameId),this.fire("webglcontextlost",{originalEvent:t})},_contextRestored:function(t){this._setupPainter(),this.resize(),this._update(),this.fire("webglcontextrestored",{originalEvent:t})},loaded:function(){return!this._styleDirty&&!this._sourcesDirty&&!(!this.style||!this.style.loaded())},_update:function(t){return this.style?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this._rerender(),this):this},_render:function(){try{this.style&&this._styleDirty&&(this._styleDirty=!1,this.style.update(this._classes,this._classOptions),this._classOptions=null,this.style._recalculate(this.transform.zoom)),this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.painter.render(this.style,{debug:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,vertices:this.vertices,rotating:this.rotating,zooming:this.zooming}),this.fire("render"),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire("load")),this._frameId=null,this.animationLoop.stopped()||(this._styleDirty=!0),(this._sourcesDirty||this._repaint||this._styleDirty)&&this._rerender()}catch(t){this.fire("error",{error:t})}return this},remove:function(){this._hash&&this._hash.remove(),a.cancelFrame(this._frameId),this.setStyle(null),void 0!==o&&o.removeEventListener("resize",this._onWindowResize,!1);var t=this.painter.gl.getExtension("WEBGL_lose_context");t&&t.loseContext(),w(this._canvasContainer),w(this._controlContainer),this._container.classList.remove("mapboxgl-map")},_rerender:function(){this.style&&!this._frameId&&(this._frameId=a.frame(this._render))},_forwardStyleEvent:function(t){this.fire("style."+t.type,i.extend({style:t.target},t))},_forwardSourceEvent:function(t){this.fire(t.type,i.extend({style:t.target},t))},_forwardLayerEvent:function(t){this.fire(t.type,i.extend({style:t.target},t))},_forwardTileEvent:function(t){this.fire(t.type,i.extend({style:t.target},t))},_onStyleLoad:function(t){this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this.style.update(this._classes,{transition:!1}),this._forwardStyleEvent(t)},_onStyleChange:function(t){this._update(!0),this._forwardStyleEvent(t)},_onSourceAdd:function(t){var e=t.source;e.onAdd&&e.onAdd(this),this._forwardSourceEvent(t)},_onSourceRemove:function(t){var e=t.source;e.onRemove&&e.onRemove(this),this._forwardSourceEvent(t)},_onSourceUpdate:function(t){this._update(),this._forwardSourceEvent(t)},_onWindowOnline:function(){this._update()},_onWindowResize:function(){this._trackResize&&this.stop().resize()._update()}}),i.extendAll(_.prototype,{_showTileBoundaries:!1,get showTileBoundaries(){return this._showTileBoundaries},set showTileBoundaries(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update())},_showCollisionBoxes:!1,get showCollisionBoxes(){return this._showCollisionBoxes},set showCollisionBoxes(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,this.style._redoPlacement())},_showOverdrawInspector:!1,get showOverdrawInspector(){return this._showOverdrawInspector},set showOverdrawInspector(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update())},_repaint:!1,get repaint(){return this._repaint},set repaint(t){this._repaint=t,this._update()},_vertices:!1,get vertices(){return this._vertices},set vertices(t){this._vertices=t,this._update()}})},{"../geo/lng_lat":311,"../geo/lng_lat_bounds":312,"../geo/transform":313,"../render/painter":327,"../style/animation_loop":347,"../style/style":350,"../util/browser":398,"../util/canvas":399,"../util/dom":400,"../util/evented":406,"../util/util":414,"./bind_handlers":379,"./camera":380,"./control/attribution":381,"./hash":392,"point-geometry":458}],394:[function(t,e,r){"use strict";e.exports=o;var n=t("../util/dom"),i=t("../geo/lng_lat"),a=t("point-geometry");function o(t,e){t||(t=n.create("div")),t.classList.add("mapboxgl-marker"),this._el=t,this._offset=a.convert(e&&e.offset||[0,0]),this._update=this._update.bind(this)}o.prototype={addTo:function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._el),t.on("move",this._update),this._update(),this},remove:function(){this._map&&(this._map.off("move",this._update),this._map=null);var t=this._el.parentNode;return t&&t.removeChild(this._el),this},getLngLat:function(){return this._lngLat},setLngLat:function(t){return this._lngLat=i.convert(t),this._update(),this},getElement:function(){return this._el},_update:function(){if(this._map){var t=this._map.project(this._lngLat)._add(this._offset);n.setTransform(this._el,"translate("+t.x+"px,"+t.y+"px)")}}}},{"../geo/lng_lat":311,"../util/dom":400,"point-geometry":458}],395:[function(t,e,r){"use strict";e.exports=s;var n=t("../util/util"),i=t("../util/evented"),a=t("../util/dom"),o=t("../geo/lng_lat");function s(t){n.setOptions(this,t),n.bindAll(["_update","_onClickClose"],this)}s.prototype=n.inherit(i,{options:{closeButton:!0,closeOnClick:!0},addTo:function(t){return this._map=t,this._map.on("move",this._update),this.options.closeOnClick&&this._map.on("click",this._onClickClose),this._update(),this},remove:function(){return this._content&&this._content.parentNode&&this._content.parentNode.removeChild(this._content),this._container&&(this._container.parentNode.removeChild(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("click",this._onClickClose),delete this._map),this.fire("close"),this},getLngLat:function(){return this._lngLat},setLngLat:function(t){return this._lngLat=o.convert(t),this._update(),this},setText:function(t){return this.setDOMContent(document.createTextNode(t))},setHTML:function(t){var e,r=document.createDocumentFragment(),n=document.createElement("body");for(n.innerHTML=t;e=n.firstChild;)r.appendChild(e);return this.setDOMContent(r)},setDOMContent:function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},_createContent:function(){this._content&&this._content.parentNode&&this._content.parentNode.removeChild(this._content),this._content=a.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=a.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClickClose))},_update:function(){if(this._map&&this._lngLat&&this._content){this._container||(this._container=a.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=a.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content));var t=this._map.project(this._lngLat).round(),e=this.options.anchor;if(!e){var r=this._container.offsetWidth,n=this._container.offsetHeight;e=t.ythis._map.transform.height-n?["bottom"]:[],t.xthis._map.transform.width-r/2&&e.push("right"),e=0===e.length?"bottom":e.join("-")}var i={top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},o=this._container.classList;for(var s in i)o.remove("mapboxgl-popup-anchor-"+s);o.add("mapboxgl-popup-anchor-"+e),a.setTransform(this._container,i[e]+" translate("+t.x+"px,"+t.y+"px)")}},_onClickClose:function(){this.remove()}})},{"../geo/lng_lat":311,"../util/dom":400,"../util/evented":406,"../util/util":414}],396:[function(t,e,r){"use strict";function n(t,e){this.target=t,this.parent=e,this.callbacks={},this.callbackID=0,this.receive=this.receive.bind(this),this.target.addEventListener("message",this.receive,!1)}e.exports=n,n.prototype.receive=function(t){var e,r=t.data,n=r.id;if(""===r.type)e=this.callbacks[r.id],delete this.callbacks[r.id],e&&e(r.error||null,r.data);else if(void 0!==r.id&&this.parent[r.type])this.parent[r.type](r.data,a.bind(this));else if(void 0!==r.id&&this.parent.workerSources){var i=r.type.split(".");this.parent.workerSources[i[0]][i[1]](r.data,a.bind(this))}else this.parent[r.type](r.data);function a(t,e,r){this.postMessage({type:"",id:String(n),error:t?String(t):null,data:e},r)}},n.prototype.send=function(t,e,r,n){var i=null;r&&(this.callbacks[i=this.callbackID++]=r),this.postMessage({type:t,id:String(i),data:e},n)},n.prototype.postMessage=function(t,e){this.target.postMessage(t,e)}},{}],397:[function(t,e,r){"use strict";r.getJSON=function(t,e){var r=new XMLHttpRequest;return r.open("GET",t,!0),r.setRequestHeader("Accept","application/json"),r.onerror=function(t){e(t)},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var t;try{t=JSON.parse(r.response)}catch(t){return e(t)}e(null,t)}else e(new Error(r.statusText))},r.send(),r},r.getArrayBuffer=function(t,e){var r=new XMLHttpRequest;return r.open("GET",t,!0),r.responseType="arraybuffer",r.onerror=function(t){e(t)},r.onload=function(){r.status>=200&&r.status<300&&r.response?e(null,r.response):e(new Error(r.statusText))},r.send(),r},r.getImage=function(t,e){return r.getArrayBuffer(t,function(t,r){if(t)return e(t);var n=new Image;n.onload=function(){e(null,n),(window.URL||window.webkitURL).revokeObjectURL(n.src)};var i=new Blob([new Uint8Array(r)],{type:"image/png"});return n.src=(window.URL||window.webkitURL).createObjectURL(i),n.getData=function(){var t=document.createElement("canvas"),e=t.getContext("2d");return t.width=n.width,t.height=n.height,e.drawImage(n,0,0),e.getImageData(0,0,n.width,n.height).data},n})},r.getVideo=function(t,e){var r,n,i=document.createElement("video");i.onloadstart=function(){e(null,i)};for(var a=0;a=o+n?t.call(i,1):(t.call(i,(l-o)/n),r.frame(s)))}),function(){a=!0}},r.supported=t("mapbox-gl-supported"),r.hardwareConcurrency=navigator.hardwareConcurrency||4,Object.defineProperty(r,"devicePixelRatio",{get:function(){return window.devicePixelRatio}}),r.supportsWebp=!1;var a=document.createElement("img");a.onload=function(){r.supportsWebp=!0},a.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=",r.supportsGeolocation=!!navigator.geolocation},{"mapbox-gl-supported":299}],399:[function(t,e,r){"use strict";var n=t("../util"),i=t("mapbox-gl-supported");function a(t,e){this.canvas=document.createElement("canvas"),t&&e&&(this.canvas.style.position="absolute",this.canvas.classList.add("mapboxgl-canvas"),this.canvas.addEventListener("webglcontextlost",t._contextLost.bind(t),!1),this.canvas.addEventListener("webglcontextrestored",t._contextRestored.bind(t),!1),this.canvas.setAttribute("tabindex",0),e.appendChild(this.canvas))}e.exports=a,a.prototype.resize=function(t,e){var r=window.devicePixelRatio||1;this.canvas.width=r*t,this.canvas.height=r*e,this.canvas.style.width=t+"px",this.canvas.style.height=e+"px"},a.prototype.getWebGLContext=function(t){return t=n.extend({},t,i.webGLContextAttributes),this.canvas.getContext("webgl",t)||this.canvas.getContext("experimental-webgl",t)},a.prototype.getElement=function(){return this.canvas}},{"../util":414,"mapbox-gl-supported":299}],400:[function(t,e,r){"use strict";var n=t("point-geometry");r.create=function(t,e,r){var n=document.createElement(t);return e&&(n.className=e),r&&r.appendChild(n),n};var i=document.documentElement.style;function a(t){for(var e=0;e1)for(var f=0;f=0&&this._events[t].splice(r,1),this._events[t].length||delete this._events[t]}else delete this._events[t];return this},once:function(t,e){var r=function(n){this.off(t,r),e.call(this,n)}.bind(this);return this.on(t,r),this},fire:function(t,e){if(!this.listens(t))return n.endsWith(t,"error")&&console.error(e&&e.error||e||"Empty error event"),this;e=n.extend({},e),n.extend(e,{type:t,target:this});for(var r=this._events[t].slice(),i=0;i1){if(i(t,e))return!0;for(var n=0;n(e.y-t.y)*(r.x-t.x)}function o(t,e,r,n){return a(t,r,n)!==a(e,r,n)&&a(t,e,r)!==a(t,e,n)}function s(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function c(t,e){for(var r,n,i,a=!1,o=0;oe.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function u(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r)}return r}e.exports={multiPolygonIntersectsBufferedMultiPoint:function(t,e,r){for(var n=0;n=3)for(var l=0;lthis.max){var r=this.get(this.order[0]);r&&this.onRemove(r)}return this},n.prototype.has=function(t){return t in this.data},n.prototype.keys=function(){return this.order},n.prototype.get=function(t){if(!this.has(t))return null;var e=this.data[t];return delete this.data[t],this.order.splice(this.order.indexOf(t),1),e},n.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this.get(this.order[0]);e&&this.onRemove(e)}return this}},{}],411:[function(t,e,r){"use strict";var n=t("./config"),i=t("./browser"),a=t("url"),o=t("./util");function s(t,e,r){if(!(r=r||n.ACCESS_TOKEN)&&n.REQUIRE_ACCESS_TOKEN)throw new Error("An API access token is required to use Mapbox GL. See https://www.mapbox.com/developers/api/#access-tokens");if(t=t.replace(/^mapbox:\/\//,n.API_URL+e),t+=-1!==t.indexOf("?")?"&access_token=":"?access_token=",n.REQUIRE_ACCESS_TOKEN){if("s"===r[0])throw new Error("Use a public access token (pk.*) with Mapbox GL JS, not a secret access token (sk.*). See https://www.mapbox.com/developers/api/#access-tokens");t+=r}return t}function l(t){return t?"?"+t:""}e.exports.normalizeStyleURL=function(t,e){var r=a.parse(t);return"mapbox:"!==r.protocol?t:s("mapbox:/"+r.pathname+l(r.query),"/styles/v1/",e)},e.exports.normalizeSourceURL=function(t,e){return"mapbox:"!==a.parse(t).protocol?t:s(t+".json","/v4/",e)+"&secure"},e.exports.normalizeGlyphsURL=function(t,e){var r=a.parse(t);return"mapbox:"!==r.protocol?t:s("mapbox://"+r.pathname.split("/")[1]+"/{fontstack}/{range}.pbf"+l(r.query),"/fonts/v1/",e)},e.exports.normalizeSpriteURL=function(t,e,r,n){var i=a.parse(t);return"mapbox:"!==i.protocol?(i.pathname+=e+r,a.format(i)):s("mapbox:/"+i.pathname+"/sprite"+e+r+l(i.query),"/styles/v1/",n)},e.exports.normalizeTileURL=function(t,e,r){var s=a.parse(t,!0);if(!e)return t;if("mapbox:"!==a.parse(e).protocol)return t;var l,c=i.supportsWebp?".webp":"$1",u=i.devicePixelRatio>=2||512===r?"@2x":"";return a.format({protocol:s.protocol,hostname:s.hostname,pathname:s.pathname.replace(/(\.(?:png|jpg)\d*)/,u+c),query:(l=s.query,l.access_token&&"tk."===l.access_token.slice(0,3)?o.extend({},l,{access_token:n.ACCESS_TOKEN}):l)})}},{"./browser":398,"./config":403,"./util":414,url:539}],412:[function(t,e,r){"use strict";var n=t("assert");e.exports=function(t){var e=JSON.stringify(t);if(a[e])return a[e];void 0===t.alignment&&(t.alignment=1);function r(){d.apply(this,arguments)}r.prototype=Object.create(d.prototype);var u=0,m=0,v=["Uint8"];function g(){p.apply(this,arguments),this.members=r.prototype.members}return r.prototype.members=t.members.map(function(e){e={name:e.name,type:e.type,components:e.components||1},n(e.name.length),n(e.type in i),v.indexOf(e.type)<0&&v.push(e.type);var a=l(e.type);m=Math.max(m,a),e.offset=u=s(u,Math.max(t.alignment,a));for(var o=0;othis.capacity){this.capacity=Math.max(t,Math.floor(this.capacity*this.RESIZE_MULTIPLIER),this.DEFAULT_CAPACITY),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},p.prototype._refreshViews=function(){for(var t=0;t=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)},r.bezier=function(t,e,r,i){var a=new n(t,e,r,i);return function(t){return a.solve(t)}},r.ease=r.bezier(.25,.1,.25,1),r.clamp=function(t,e,r){return Math.min(r,Math.max(e,t))},r.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},r.coalesce=function(){for(var t=0;t=0)return!0;return!1};var o={};r.warnOnce=function(t){o[t]||("undefined"!=typeof console&&console.warn(t),o[t]=!0)}},{"../geo/coordinate":310,unitbezier:537}],415:[function(t,e,r){"use strict";function n(t,e,r,n){this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)}e.exports=n,n.prototype={type:"Feature",get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},set geometry(t){this._geometry=t},toJSON:function(){var t={};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&"toJSON"!==e&&(t[e]=this[e]);return t}}},{}],416:[function(t,e,r){e.exports={_args:[["mapbox-gl@0.22.1","/home/etienne/Documents/plotly/plotly.js"]],_from:"mapbox-gl@0.22.1",_id:"mapbox-gl@0.22.1",_inBundle:!1,_integrity:"sha1-kqllVH1MLyTCLLxIfu2khpTLYno=",_location:"/mapbox-gl",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"mapbox-gl@0.22.1",name:"mapbox-gl",escapedName:"mapbox-gl",rawSpec:"0.22.1",saveSpec:null,fetchSpec:"0.22.1"},_requiredBy:["/"],_resolved:"https://registry.npmjs.org/mapbox-gl/-/mapbox-gl-0.22.1.tgz",_spec:"0.22.1",_where:"/home/etienne/Documents/plotly/plotly.js",browser:{"./js/util/ajax.js":"./js/util/browser/ajax.js","./js/util/browser.js":"./js/util/browser/browser.js","./js/util/canvas.js":"./js/util/browser/canvas.js","./js/util/dom.js":"./js/util/browser/dom.js","./js/util/web_worker.js":"./js/util/browser/web_worker.js"},bugs:{url:"https://github.com/mapbox/mapbox-gl-js/issues"},dependencies:{csscolorparser:"^1.0.2",earcut:"^2.0.3","feature-filter":"^2.2.0","geojson-rewind":"^0.1.0","geojson-vt":"^2.4.0","gl-matrix":"^2.3.1","grid-index":"^1.0.0","mapbox-gl-function":"^1.2.1","mapbox-gl-shaders":"github:mapbox/mapbox-gl-shaders#de2ab007455aa2587c552694c68583f94c9f2747","mapbox-gl-style-spec":"github:mapbox/mapbox-gl-style-spec#83b1a3e5837d785af582efd5ed1a212f2df6a4ae","mapbox-gl-supported":"^1.2.0",pbf:"^1.3.2",pngjs:"^2.2.0","point-geometry":"^0.0.0",quickselect:"^1.0.0",request:"^2.39.0","resolve-url":"^0.2.1","shelf-pack":"^1.0.0",supercluster:"^2.0.1",unassertify:"^2.0.0",unitbezier:"^0.0.0","vector-tile":"^1.3.0","vt-pbf":"^2.0.2",webworkify:"^1.3.0","whoots-js":"^2.0.0"},description:"A WebGL interactive maps library",devDependencies:{"babel-preset-react":"^6.11.1",babelify:"^7.3.0",benchmark:"~2.1.0",browserify:"^13.0.0",clipboard:"^1.5.12","concat-stream":"1.5.1",coveralls:"^2.11.8",doctrine:"^1.2.1",documentation:"https://github.com/documentationjs/documentation/archive/bb41619c734e59ef3fbc3648610032efcfdaaace.tar.gz","documentation-theme-utils":"3.0.0",envify:"^3.4.0",eslint:"^2.5.3","eslint-config-mourner":"^2.0.0","eslint-plugin-html":"^1.5.1",gl:"^4.0.1",handlebars:"4.0.5","highlight.js":"9.3.0",istanbul:"^0.4.2","json-loader":"^0.5.4",lodash:"^4.13.1","mapbox-gl-test-suite":"github:mapbox/mapbox-gl-test-suite#7babab52fb02788ebbc38384139bf350e8e38552","memory-fs":"^0.3.0",minifyify:"^7.0.1","npm-run-all":"^3.0.0",nyc:"6.4.0",proxyquire:"^1.7.9",remark:"4.2.2","remark-html":"3.0.0",sinon:"^1.15.4",st:"^1.2.0",tap:"^5.7.0","transform-loader":"^0.2.3","unist-util-visit":"1.1.0",vinyl:"1.1.1","vinyl-fs":"2.4.3",watchify:"^3.7.0",webpack:"^1.13.1","webworkify-webpack":"^1.1.3"},engines:{node:">=4.0.0"},homepage:"https://github.com/mapbox/mapbox-gl-js#readme",license:"BSD-3-Clause",main:"js/mapbox-gl.js",name:"mapbox-gl",repository:{type:"git",url:"git://github.com/mapbox/mapbox-gl-js.git"},scripts:{build:"npm run build-docs # invoked by publisher when publishing docs on the mb-pages branch","build-dev":"browserify js/mapbox-gl.js --debug --standalone mapboxgl > dist/mapbox-gl-dev.js && tap --no-coverage test/build/dev.test.js","build-docs":"documentation build --github --format html -c documentation.yml --theme ./docs/_theme --output docs/api/","build-min":"browserify js/mapbox-gl.js --debug -t unassertify --plugin [minifyify --map mapbox-gl.js.map --output dist/mapbox-gl.js.map] --standalone mapboxgl > dist/mapbox-gl.js && tap --no-coverage test/build/min.test.js","build-token":"browserify debug/access-token-src.js --debug -t envify > debug/access-token.js",lint:"eslint --ignore-path .gitignore js test bench docs/_posts/examples/*.html","open-changed-examples":"git diff --name-only mb-pages HEAD -- docs/_posts/examples/*.html | awk '{print \"http://127.0.0.1:4000/mapbox-gl-js/example/\" substr($0,33,length($0)-37)}' | xargs open",start:"run-p build-token watch-dev watch-bench start-server","start-bench":"run-p build-token watch-bench start-server","start-debug":"run-p build-token watch-dev start-server","start-docs":"npm run build-min && npm run build-docs && jekyll serve -w","start-server":"st --no-cache --localhost --port 9966 --index index.html .",test:"npm run lint && tap --reporter dot test/js/*/*.js test/build/webpack.test.js","test-suite":"node test/render.test.js && node test/query.test.js","watch-bench":"node bench/download-data.js && watchify bench/index.js --plugin [minifyify --no-map] -t [babelify --presets react] -t unassertify -t envify -o bench/bench.js -v","watch-dev":"watchify js/mapbox-gl.js --debug --standalone mapboxgl -o dist/mapbox-gl-dev.js -v"},version:"0.22.1"}},{}],417:[function(t,e,r){"use strict";e.exports=function(t){for(var e=1<d[1][2]&&(g[0]=-g[0]),d[0][2]>d[2][0]&&(g[1]=-g[1]),d[1][0]>d[0][1]&&(g[2]=-g[2]),!0}},{"./normalize":419,"gl-mat4/clone":180,"gl-mat4/create":181,"gl-mat4/determinant":182,"gl-mat4/invert":186,"gl-mat4/transpose":196,"gl-vec3/cross":238,"gl-vec3/dot":239,"gl-vec3/length":240,"gl-vec3/normalize":242}],419:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}},{}],420:[function(t,e,r){var n=t("gl-vec3/lerp"),i=t("mat4-recompose"),a=t("mat4-decompose"),o=t("gl-mat4/determinant"),s=t("quat-slerp"),l=f(),c=f(),u=f();function f(){return{translate:h(),scale:h(1),skew:h(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function h(t){return[t||0,t||0,t||0]}e.exports=function(t,e,r,f){if(0===o(e)||0===o(r))return!1;var h=a(e,l.translate,l.scale,l.skew,l.perspective,l.quaternion),d=a(r,c.translate,c.scale,c.skew,c.perspective,c.quaternion);return!(!h||!d||(n(u.translate,l.translate,c.translate,f),n(u.skew,l.skew,c.skew,f),n(u.scale,l.scale,c.scale,f),n(u.perspective,l.perspective,c.perspective,f),s(u.quaternion,l.quaternion,c.quaternion,f),i(t,u.translate,u.scale,u.skew,u.perspective,u.quaternion),0))}},{"gl-mat4/determinant":182,"gl-vec3/lerp":241,"mat4-decompose":418,"mat4-recompose":421,"quat-slerp":471}],421:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":181,"gl-mat4/fromRotationTranslation":184,"gl-mat4/identity":185,"gl-mat4/multiply":188,"gl-mat4/scale":194,"gl-mat4/translate":195}],422:[function(t,e,r){"use strict";var n=t("binary-search-bounds"),i=t("mat4-interpolate"),a=t("gl-mat4/invert"),o=t("gl-mat4/rotateX"),s=t("gl-mat4/rotateY"),l=t("gl-mat4/rotateZ"),c=t("gl-mat4/lookAt"),u=t("gl-mat4/translate"),f=(t("gl-mat4/scale"),t("gl-vec3/normalize")),h=[0,0,0];function d(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}e.exports=function(t){return new d((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};var p=d.prototype;p.recalcMatrix=function(t){var e=this._time,r=n.le(e,t),o=this.computedMatrix;if(!(r<0)){var s=this._components;if(r===e.length-1)for(var l=16*r,c=0;c<16;++c)o[c]=s[l++];else{var u=e[r+1]-e[r],h=(l=16*r,this.prevMatrix),d=!0;for(c=0;c<16;++c)h[c]=s[l++];var p=this.nextMatrix;for(c=0;c<16;++c)p[c]=s[l++],d=d&&h[c]===p[c];if(u<1e-6||d)for(c=0;c<16;++c)o[c]=h[c];else i(o,h,p,(t-e[r])/u)}var m=this.computedUp;m[0]=o[1],m[1]=o[5],m[2]=o[9],f(m,m);var v=this.computedInverse;a(v,o);var g=this.computedEye,y=v[15];g[0]=v[12]/y,g[1]=v[13]/y,g[2]=v[14]/y;var b=this.computedCenter,x=Math.exp(this.computedRadius[0]);for(c=0;c<3;++c)b[c]=g[c]-o[2+4*c]*x}},p.idle=function(t){if(!(t1&&n(t[o[u-2]],t[o[u-1]],c)<=0;)u-=1,o.pop();for(o.push(l),u=s.length;u>1&&n(t[s[u-2]],t[s[u-1]],c)>=0;)u-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),f=0,i=0,h=o.length;i0;--d)r[f++]=s[d];return r};var n=t("robust-orientation")[3]},{"robust-orientation":495}],424:[function(t,e,r){"use strict";e.exports=function(t,e){e||(e=t,t=window);var r=0,i=0,a=0,o={shift:!1,alt:!1,control:!1,meta:!1},s=!1;function l(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==o.alt,o.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==o.shift,o.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==o.control,o.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==o.meta,o.meta=!!t.metaKey),e}function c(t,s){var c=n.x(s),u=n.y(s);"buttons"in s&&(t=0|s.buttons),(t!==r||c!==i||u!==a||l(s))&&(r=0|t,i=c||0,a=u||0,e&&e(r,i,a,o))}function u(t){c(0,t)}function f(){(r||i||a||o.shift||o.alt||o.meta||o.control)&&(i=a=0,r=0,o.shift=o.alt=o.control=o.meta=!1,e&&e(0,0,0,o))}function h(t){l(t)&&e&&e(r,i,a,o)}function d(t){0===n.buttons(t)?c(0,t):c(r,t)}function p(t){c(r|n.buttons(t),t)}function m(t){c(r&~n.buttons(t),t)}function v(){s||(s=!0,t.addEventListener("mousemove",d),t.addEventListener("mousedown",p),t.addEventListener("mouseup",m),t.addEventListener("mouseleave",u),t.addEventListener("mouseenter",u),t.addEventListener("mouseout",u),t.addEventListener("mouseover",u),t.addEventListener("blur",f),t.addEventListener("keyup",h),t.addEventListener("keydown",h),t.addEventListener("keypress",h),t!==window&&(window.addEventListener("blur",f),window.addEventListener("keyup",h),window.addEventListener("keydown",h),window.addEventListener("keypress",h)))}v();var g={element:t};return Object.defineProperties(g,{enabled:{get:function(){return s},set:function(e){e?v():s&&(s=!1,t.removeEventListener("mousemove",d),t.removeEventListener("mousedown",p),t.removeEventListener("mouseup",m),t.removeEventListener("mouseleave",u),t.removeEventListener("mouseenter",u),t.removeEventListener("mouseout",u),t.removeEventListener("mouseover",u),t.removeEventListener("blur",f),t.removeEventListener("keyup",h),t.removeEventListener("keydown",h),t.removeEventListener("keypress",h),t!==window&&(window.removeEventListener("blur",f),window.removeEventListener("keyup",h),window.removeEventListener("keydown",h),window.removeEventListener("keypress",h)))},enumerable:!0},buttons:{get:function(){return r},enumerable:!0},x:{get:function(){return i},enumerable:!0},y:{get:function(){return a},enumerable:!0},mods:{get:function(){return o},enumerable:!0}}),g};var n=t("mouse-event")},{"mouse-event":426}],425:[function(t,e,r){var n={left:0,top:0};e.exports=function(t,e,r){e=e||t.currentTarget||t.srcElement,Array.isArray(r)||(r=[0,0]);var i=t.clientX||0,a=t.clientY||0,o=(s=e,s===window||s===document||s===document.body?n:s.getBoundingClientRect());var s;return r[0]=i-o.left,r[1]=a-o.top,r}},{}],426:[function(t,e,r){"use strict";function n(t){return t.target||t.srcElement||window}r.buttons=function(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){if(2===(e=t.which))return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1< 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var S=t.getters||[],L=new Array(T),C=0;C=0?L[C]=!0:L[C]=!1;return function(t,e,r,T,E,S){var L=S.length,C=E.length;if(C<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var P="extractContour"+E.join("_"),z=[],O=[],D=[],I=0;I0&&j.push(l(I,E[R-1])+"*"+s(E[R-1])),O.push(p(I,E[R])+"=("+j.join("-")+")|0")}for(var I=0;I=0;--I)B.push(s(E[I]));O.push(w+"=("+B.join("*")+")|0",x+"=mallocUint32("+w+")",b+"=mallocUint32("+w+")",M+"=0"),O.push(m(0)+"=0");for(var R=1;R<1<0;k=k-1&p)w.push(b+"["+M+"+"+g(k)+"]");w.push(y(0));for(var k=0;k=0;--e)G(e,0);for(var r=[],e=0;e0){",d(E[e]),"=1;");t(e-1,r|1<=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var c=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(c=""),i>0){n.push("if(1");for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",c);for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",c);n.push(");")}for(var l=0;l1){dst.set(",s.join(),",",u,",0.5*(src.get(",h.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):n.push("if(s[",u,"]>1){diff(",f,",src.pick(",h.join(),")",c,",src.pick(",d.join(),")",c,");}else{zero(",f,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",u,",0);"):n.push("zero(",f,");");break;case"wrap":var p=s.slice(),m=s.slice();e[l]<0?(p[u]="s["+u+"]-2",m[u]="0"):(p[u]="s["+u+"]-1",m[u]="1"),0===i?n.push("if(s[",u,"]>2){dst.set(",s.join(),",",u,",0.5*(src.get(",p.join(),")-src.get(",m.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):n.push("if(s[",u,"]>2){diff(",f,",src.pick(",p.join(),")",c,",src.pick(",m.join(),")",c,");}else{zero(",f,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var s=0;s<1<>",rrshift:">>>"};!function(){for(var t in s){var e=s[t];r[t]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var l={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in l){var e=l[t];r[t]=o({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=o({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in c){var e=c[t];r[t]=o({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=o({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=o({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=o({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var u=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=n({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=n({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=n({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=o({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=o({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=o({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=n({args:["array","array"],pre:i,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":116}],434:[function(t,e,r){"use strict";var n=t("ndarray"),i=t("./doConvert.js");e.exports=function(t,e){for(var r=[],a=t,o=1;Array.isArray(a);)r.push(a.length),o*=a.length,a=a[0];return 0===r.length?n():(e||(e=n(new Float64Array(o),r)),i(e,t),e)}},{"./doConvert.js":435,ndarray:439}],435:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}",args:[{name:"_inline_1_arg0_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:4}],thisVars:[],localVars:["_inline_1_i","_inline_1_v"]},post:{body:"{}",args:[],thisVars:[],localVars:[]},funcName:"convert",blockSize:64})},{"cwise-compiler":116}],436:[function(t,e,r){"use strict";var n=t("typedarray-pool"),i=32;function a(t){switch(t){case"uint8":return[n.mallocUint8,n.freeUint8];case"uint16":return[n.mallocUint16,n.freeUint16];case"uint32":return[n.mallocUint32,n.freeUint32];case"int8":return[n.mallocInt8,n.freeInt8];case"int16":return[n.mallocInt16,n.freeInt16];case"int32":return[n.mallocInt32,n.freeInt32];case"float32":return[n.mallocFloat,n.freeFloat];case"float64":return[n.mallocDouble,n.freeDouble];default:return null}}function o(t){for(var e=[],r=0;r0?s.push(["d",p,"=s",p,"-d",f,"*n",f].join("")):s.push(["d",p,"=s",p].join("")),f=p),0!=(d=t.length-1-l)&&(h>0?s.push(["e",d,"=s",d,"-e",h,"*n",h,",f",d,"=",c[d],"-f",h,"*n",h].join("")):s.push(["e",d,"=s",d,",f",d,"=",c[d]].join("")),h=d)}r.push("var "+s.join(","));var m=["0","n0-1","data","offset"].concat(o(t.length));r.push(["if(n0<=",i,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var v=new Function("insertionSort","quickSort",r.join("\n")),g=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(o(t.length)),s=a(e),l=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var c=[],u=1;u1){for(r.push("dptr=0;sptr=ptr"),u=t.length-1;u>=0;--u)0!==(d=t[u])&&r.push(["for(i",d,"=0;i",d,"b){break __l}"].join("")),u=t.length-1;u>=1;--u)r.push("sptr+=e"+u,"dptr+=f"+u,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),u=t.length-1;u>=0;--u)0!==(d=t[u])&&r.push(["for(i",d,"=0;i",d,"=0;--u)0!==(d=t[u])&&r.push(["for(i",d,"=0;i",d,"scratch)){",h("cptr",f("cptr-s0")),"cptr-=s0","}",h("cptr","scratch"));return r.push("}"),t.length>1&&s&&r.push("free(scratch)"),r.push("} return "+n),s?new Function("malloc","free",r.join("\n"))(s[0],s[1]):new Function(r.join("\n"))()}(t,e);return v(g,function(t,e,r){var n=["'use strict'"],s=["ndarrayQuickSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(o(t.length)),c=a(e),u=0;n.push(["function ",s,"(",l.join(","),"){"].join(""));var f=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var h=[],d=1;d=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"1)for(a=0;a1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function y(e,r,i,a){if(1===r.length)n.push("ptr0="+p(r[0]));else{for(var o=0;o1)for(o=0;o=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function b(){t.length>1&&c&&n.push("free(pivot1)","free(pivot2)")}function x(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++u;y(o,[i,a],!1,["comp=",m("ptr0"),"-",m("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",m(p(i)),">",m(p(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function _(e,r){t.length>1?g([e,r],!1,v("ptr0",m("ptr1"))):n.push(v(p(e),m(p(r))))}function w(e,r,i){if(t.length>1){var a="__l"+ ++u;y(a,[r],!0,[e,"=",m("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",m(p(r)),"-pivot",i].join(""))}function M(e,r){t.length>1?g([e,r],!1,["tmp=",m("ptr0"),"\n",v("ptr0",m("ptr1")),"\n",v("ptr1","tmp")].join("")):n.push(["ptr0=",p(e),"\n","ptr1=",p(r),"\n","tmp=",m("ptr0"),"\n",v("ptr0",m("ptr1")),"\n",v("ptr1","tmp")].join(""))}function k(e,r,i){t.length>1?(g([e,r,i],!1,["tmp=",m("ptr0"),"\n",v("ptr0",m("ptr1")),"\n",v("ptr1",m("ptr2")),"\n",v("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",p(e),"\n","ptr1=",p(r),"\n","ptr2=",p(i),"\n","++",r,"\n","--",i,"\n","tmp=",m("ptr0"),"\n",v("ptr0",m("ptr1")),"\n",v("ptr1",m("ptr2")),"\n",v("ptr2","tmp")].join(""))}function A(t,e){M(t,e),n.push("--"+e)}function T(e,r,i){t.length>1?g([e,r],!0,[v("ptr0",m("ptr1")),"\n",v("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(v(p(e),m(p(r))),v(p(r),"pivot"+i))}function E(e,r){n.push(["if((",r,"-",e,")<=",i,"){\n","insertionSort(",e,",",r,",data,offset,",o(t.length).join(","),")\n","}else{\n",s,"(",e,",",r,",data,offset,",o(t.length).join(","),")\n","}"].join(""))}function S(e,r,i){t.length>1?(n.push(["__l",++u,":while(true){"].join("")),g([e],!0,["if(",m("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",u,"}"].join("")),n.push(i,"}")):n.push(["while(",m(p(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+f.join(",")),x(1,2),x(4,5),x(1,3),x(2,3),x(1,4),x(3,4),x(2,5),x(2,3),x(4,5),t.length>1?g(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",m("ptr1"),"\n","pivot2[pivot_ptr]=",m("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",m("ptr0"),"\n","y=",m("ptr2"),"\n","z=",m("ptr4"),"\n",v("ptr5","x"),"\n",v("ptr6","y"),"\n",v("ptr7","z")].join("")):n.push(["pivot1=",m(p("el2")),"\n","pivot2=",m(p("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",m(p("el1")),"\n","y=",m(p("el3")),"\n","z=",m(p("el5")),"\n",v(p("index1"),"x"),"\n",v(p("index3"),"y"),"\n",v(p("index5"),"z")].join("")),_("index2","left"),_("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),w("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),M("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),w("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),k("k","less","great"),n.push("break"),n.push("}else{"),A("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),w("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),M("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),w("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),w("comp","great",2),n.push("if(comp>0){"),n.push("if(--greatindex5){"),S("less",1,"++less"),S("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),w("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),M("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),w("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),w("comp","great",2),n.push("if(comp===0){"),n.push("if(--great1&&c?new Function("insertionSort","malloc","free",n.join("\n"))(r,c[0],c[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,g))}},{"typedarray-pool":534}],437:[function(t,e,r){"use strict";var n=t("./lib/compile_sort.js"),i={};e.exports=function(t){var e=t.order,r=t.dtype,a=[e,r].join(":"),o=i[a];return o||(i[a]=o=n(e,r)),o(t),t}},{"./lib/compile_sort.js":436}],438:[function(t,e,r){"use strict";var n=t("ndarray-linear-interpolate"),i=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=new Array(_inline_9_arg4_)}",args:[{name:"_inline_9_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_9_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_9_arg2_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_9_arg3_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_9_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_.apply(void 0,this_warped)}",args:[{name:"_inline_10_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_10_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg4_",lvalue:!1,rvalue:!1,count:0}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warpND",blockSize:64}),a=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0])}",args:[{name:"_inline_13_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_13_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp1D",blockSize:64}),o=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_16_arg2_(this_warped,_inline_16_arg0_),_inline_16_arg1_=_inline_16_arg3_(_inline_16_arg4_,this_warped[0],this_warped[1])}",args:[{name:"_inline_16_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_16_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp2D",blockSize:64}),s=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_19_arg2_(this_warped,_inline_19_arg0_),_inline_19_arg1_=_inline_19_arg3_(_inline_19_arg4_,this_warped[0],this_warped[1],this_warped[2])}",args:[{name:"_inline_19_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_19_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_19_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_19_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_19_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp3D",blockSize:64});e.exports=function(t,e,r){switch(e.shape.length){case 1:a(t,r,n.d1,e);break;case 2:o(t,r,n.d2,e);break;case 3:s(t,r,n.d3,e);break;default:i(t,r,n.bind(void 0,e),e.shape.length)}return t}},{"cwise/lib/wrapper":119,"ndarray-linear-interpolate":432}],439:[function(t,e,r){var n=t("iota-array"),i=t("is-buffer"),a="undefined"!=typeof Float64Array;function o(t,e){return t[0]-e[0]}function s(){var t,e=this.stride,r=new Array(e.length);for(t=0;tMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+l.join(",")+",v){"),i?a.push("return this.data.set("+u+",v)}"):a.push("return this.data["+u+"]=v}"),a.push("proto.get=function "+r+"_get("+l.join(",")+"){"),i?a.push("return this.data.get("+u+")}"):a.push("return this.data["+u+"]}"),a.push("proto.index=function "+r+"_index(",l.join(),"){return "+u+"}"),a.push("proto.hi=function "+r+"_hi("+l.join(",")+"){return new "+r+"(this.data,"+o.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+o.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var d=o.map(function(t){return"a"+t+"=this.shape["+t+"]"}),p=o.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+l.join(",")+"){var b=this.offset,d=0,"+d.join(",")+","+p.join(","));for(var m=0;m=0){d=i"+m+"|0;b+=c"+m+"*d;a"+m+"-=d}");a.push("return new "+r+"(this.data,"+o.map(function(t){return"a"+t}).join(",")+","+o.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+l.join(",")+"){var "+o.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+o.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(m=0;m=0){c=(c+this.stride["+m+"]*i"+m+")|0}else{a.push(this.shape["+m+"]);b.push(this.stride["+m+"])}");return a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+o.map(function(t){return"shape["+t+"]"}).join(",")+","+o.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",a.join("\n"))(c[t],s)}var c={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=function(t,e,r,n){if(void 0===t)return(0,c.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var o=e.length;if(void 0===r){r=new Array(o);for(var s=o-1,u=1;s>=0;--s)r[s]=u,u*=e[s]}if(void 0===n)for(n=0,s=0;s>>0;e.exports=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-i:i;var r=n.hi(t),o=n.lo(t);e>t==t>0?o===a?(r+=1,o=0):o+=1:0===o?(o=a,r-=1):o-=1;return n.pack(o,r)}},{"double-bits":131}],441:[function(t,e,r){var n=Math.PI,i=c(120);function a(t,e,r,n){return["C",t,e,r,n,r,n]}function o(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}function s(t,e,r,a,o,c,u,f,h,d){if(d)M=d[0],k=d[1],_=d[2],w=d[3];else{var p=l(t,e,-o);t=p.x,e=p.y;var m=(t-(f=(p=l(f,h,-o)).x))/2,v=(e-(h=p.y))/2,g=m*m/(r*r)+v*v/(a*a);g>1&&(r*=g=Math.sqrt(g),a*=g);var y=r*r,b=a*a,x=(c==u?-1:1)*Math.sqrt(Math.abs((y*b-y*v*v-b*m*m)/(y*v*v+b*m*m)));x==1/0&&(x=1);var _=x*r*v/a+(t+f)/2,w=x*-a*m/r+(e+h)/2,M=Math.asin(((e-w)/a).toFixed(9)),k=Math.asin(((h-w)/a).toFixed(9));M=t<_?n-M:M,k=f<_?n-k:k,M<0&&(M=2*n+M),k<0&&(k=2*n+k),u&&M>k&&(M-=2*n),!u&&k>M&&(k-=2*n)}if(Math.abs(k-M)>i){var A=k,T=f,E=h;k=M+i*(u&&k>M?1:-1);var S=s(f=_+r*Math.cos(k),h=w+a*Math.sin(k),r,a,o,0,u,T,E,[k,A,_,w])}var L=Math.tan((k-M)/4),C=4/3*r*L,P=4/3*a*L,z=[2*t-(t+C*Math.sin(M)),2*e-(e-P*Math.cos(M)),f+C*Math.sin(k),h-P*Math.cos(k),f,h];if(d)return z;S&&(z=z.concat(S));for(var O=0;O7&&(r.push(g.splice(0,7)),g.unshift("C"));break;case"S":var b=d,x=p;"C"!=e&&"S"!=e||(b+=b-n,x+=x-i),g=["C",b,x,g[1],g[2],g[3],g[4]];break;case"T":"Q"==e||"T"==e?(f=2*d-f,h=2*p-h):(f=d,h=p),g=o(d,p,f,h,g[1],g[2]);break;case"Q":f=g[1],h=g[2],g=o(d,p,g[1],g[2],g[3],g[4]);break;case"L":g=a(d,p,g[1],g[2]);break;case"H":g=a(d,p,g[1],p);break;case"V":g=a(d,p,d,g[1]);break;case"Z":g=a(d,p,l,u)}e=y,d=g[g.length-2],p=g[g.length-1],g.length>4?(n=g[g.length-4],i=g[g.length-3]):(n=d,i=p),r.push(g)}return r}},{}],442:[function(t,e,r){r.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa){var x=i[c],_=1/Math.sqrt(v*y);for(b=0;b<3;++b){var w=(b+1)%3,M=(b+2)%3;x[b]+=_*(g[w]*m[M]-g[M]*m[w])}}}for(o=0;oa)for(_=1/Math.sqrt(k),b=0;b<3;++b)x[b]*=_;else for(b=0;b<3;++b)x[b]=0}return i},r.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa?1/Math.sqrt(d):0;for(c=0;c<3;++c)h[c]*=d;i[o]=h}return i}},{}],443:[function(t,e,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(t){n[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var r,o,s=function(t){if(null===t||void 0===t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),l=1;l0){var f=Math.sqrt(u+1);t[0]=.5*(o-l)/f,t[1]=.5*(s-n)/f,t[2]=.5*(r-a)/f,t[3]=.5*f}else{var h=Math.max(e,a,c),f=Math.sqrt(2*h-u+1);e>=h?(t[0]=.5*f,t[1]=.5*(i+r)/f,t[2]=.5*(s+n)/f,t[3]=.5*(o-l)/f):a>=h?(t[0]=.5*(r+i)/f,t[1]=.5*f,t[2]=.5*(l+o)/f,t[3]=.5*(s-n)/f):(t[0]=.5*(n+s)/f,t[1]=.5*(o+l)/f,t[2]=.5*f,t[3]=.5*(r-i)/f)}return t}},{}],445:[function(t,e,r){"use strict";e.exports=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),u(r=[].slice.call(r,0,4),r);var i=new f(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};var n=t("filtered-vector"),i=t("gl-mat4/lookAt"),a=t("gl-mat4/fromQuat"),o=t("gl-mat4/invert"),s=t("./lib/quatFromFrame");function l(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function c(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function u(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=c(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function f(t,e,r){this.radius=n([r]),this.center=n(e),this.rotation=n(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var h=f.prototype;h.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},h.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;u(e,e);var r=this.computedMatrix;a(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;l<3;++l){for(var c=0,f=0;f<3;++f)c+=r[l+4*f]*i[f];r[12+l]=-c}},h.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},h.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},h.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},h.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],c=l(a,o,s);a/=c,o/=c,s/=c;var u=i[0],f=i[4],h=i[8],d=u*a+f*o+h*s,p=l(u-=a*d,f-=o*d,h-=s*d);u/=p,f/=p,h/=p;var m=i[2],v=i[6],g=i[10],y=m*a+v*o+g*s,b=m*u+v*f+g*h,x=l(m-=y*a+b*u,v-=y*o+b*f,g-=y*s+b*h);m/=x,v/=x,g/=x;var _=u*e+a*r,w=f*e+o*r,M=h*e+s*r;this.center.move(t,_,w,M);var k=Math.exp(this.computedRadius[0]);k=Math.max(1e-4,k+n),this.radius.set(t,Math.log(k))},h.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],u=i[1],f=i[5],h=i[9],d=i[2],p=i[6],m=i[10],v=e*a+r*u,g=e*o+r*f,y=e*s+r*h,b=-(p*y-m*g),x=-(m*v-d*y),_=-(d*g-p*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),M=c(b,x,_,w);M>1e-6?(b/=M,x/=M,_/=M,w/=M):(b=x=_=0,w=1);var k=this.computedRotation,A=k[0],T=k[1],E=k[2],S=k[3],L=A*w+S*b+T*_-E*x,C=T*w+S*x+E*b-A*_,P=E*w+S*_+A*x-T*b,z=S*w-A*b-T*x-E*_;if(n){b=d,x=p,_=m;var O=Math.sin(n)/l(b,x,_);b*=O,x*=O,_*=O,z=z*(w=Math.cos(e))-(L=L*w+z*b+C*_-P*x)*b-(C=C*w+z*x+P*b-L*_)*x-(P=P*w+z*_+L*x-C*b)*_}var D=c(L,C,P,z);D>1e-6?(L/=D,C/=D,P/=D,z/=D):(L=C=P=0,z=1),this.rotation.set(t,L,C,P,z)},h.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var a=this.computedMatrix;i(a,e,r,n);var o=this.computedRotation;s(o,a[0],a[1],a[2],a[4],a[5],a[6],a[8],a[9],a[10]),u(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var l=0,c=0;c<3;++c)l+=Math.pow(r[c]-e[c],2);this.radius.set(t,.5*Math.log(Math.max(l,1e-6))),this.center.set(t,r[0],r[1],r[2])},h.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},h.setMatrix=function(t,e){var r=this.computedRotation;s(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),u(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;o(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,l=n[13]/i,c=n[14]/i;this.recalcMatrix(t);var f=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*f,l-n[6]*f,c-n[10]*f),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},h.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},h.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},h.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},h.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},h.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":444,"filtered-vector":142,"gl-mat4/fromQuat":183,"gl-mat4/invert":186,"gl-mat4/lookAt":187}],446:[function(t,e,r){"use strict";var n=t("repeat-string");e.exports=function(t,e,r){return n(r=void 0!==r?r+"":" ",e)+t}},{"repeat-string":487}],447:[function(t,e,r){e.exports=function(t){var e=[];return t.replace(i,function(t,r,i){var o=r.toLowerCase();for(i=function(t){var e=t.match(a);return e?e.map(Number):[]}(i),"m"==o&&i.length>2&&(e.push([r].concat(i.splice(0,2))),o="l",r="m"==r?"l":"L");;){if(i.length==n[o])return i.unshift(r),e.push(i);if(i.length=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(t){return n.exec(t).slice(1)};function a(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!n;i--){var o=i>=0?arguments[i]:t.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(r=o+"/"+r,n="/"===o.charAt(0))}return r=e(a(r.split("/"),function(t){return!!t}),!n).join("/"),(n?"/":"")+r||"."},r.normalize=function(t){var n=r.isAbsolute(t),i="/"===o(t,-1);return(t=e(a(t.split("/"),function(t){return!!t}),!n).join("/"))||n||(t="."),t&&i&&(t+="/"),(n?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(a(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),a=n(e.split("/")),o=Math.min(i.length,a.length),s=o,l=0;l55295&&e<57344){if(!r){e>56319||a+1===n?i.push(239,191,189):r=e;continue}if(e<56320){i.push(239,191,189),r=e;continue}e=r-55296<<10|e-56320|65536,r=null}else r&&(i.push(239,191,189),r=null);e<128?i.push(e):e<2048?i.push(e>>6|192,63&e|128):e<65536?i.push(e>>12|224,e>>6&63|128,63&e|128):i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}return i}(n={readUInt32LE:function(t){return(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},writeUInt32LE:function(t,e){this[e]=t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24},readInt32LE:function(t){return(this[t]|this[t+1]<<8|this[t+2]<<16)+(this[t+3]<<24)},readFloatLE:function(t){return o.read(this,t,!0,23,4)},readDoubleLE:function(t){return o.read(this,t,!0,52,8)},writeFloatLE:function(t,e){return o.write(this,t,e,!0,23,4)},writeDoubleLE:function(t,e){return o.write(this,t,e,!0,52,8)},toString:function(t,e,r){var n="",i="";e=e||0,r=Math.min(this.length,r||this.length);for(var a=e;a>3,a=this.pos;t(i,e,this),this.pos===a&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=this.buf.readUInt32LE(this.pos);return this.pos+=4,t},readSFixed32:function(){var t=this.buf.readInt32LE(this.pos);return this.pos+=4,t},readFixed64:function(){var t=this.buf.readUInt32LE(this.pos)+4294967296*this.buf.readUInt32LE(this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=this.buf.readUInt32LE(this.pos)+4294967296*this.buf.readInt32LE(this.pos+4);return this.pos+=8,t},readFloat:function(){var t=this.buf.readFloatLE(this.pos);return this.pos+=4,t},readDouble:function(){var t=this.buf.readDoubleLE(this.pos);return this.pos+=8,t},readVarint:function(){var t,e,r=this.buf;return t=127&(e=r[this.pos++]),e<128?t:(t|=(127&(e=r[this.pos++]))<<7,e<128?t:(t|=(127&(e=r[this.pos++]))<<14,e<128?t:(t|=(127&(e=r[this.pos++]))<<21,e<128?t:function(t,e){var r,n=e.buf;if(r=n[e.pos++],t+=268435456*(127&r),r<128)return t;if(r=n[e.pos++],t+=34359738368*(127&r),r<128)return t;if(r=n[e.pos++],t+=4398046511104*(127&r),r<128)return t;if(r=n[e.pos++],t+=562949953421312*(127&r),r<128)return t;if(r=n[e.pos++],t+=72057594037927940*(127&r),r<128)return t;if(r=n[e.pos++],t+=0x8000000000000000*(127&r),r<128)return t;throw new Error("Expected varint not more than 10 bytes")}(t,this))))},readVarint64:function(){var t=this.pos,e=this.readVarint();if(e127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455?function(t,e){e.realloc(10);var r=e.pos+10;for(;t>=1;){if(e.pos>=r)throw new Error("Given varint doesn't fit into 10 bytes");var n=255&t;e.buf[e.pos++]=n|(t>=128?128:0),t/=128}}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t);var e=n.byteLength(t);this.writeVarint(e),this.realloc(e),this.buf.write(t,this.pos),this.pos+=e},writeFloat:function(t){this.realloc(4),this.buf.writeFloatLE(t,this.pos),this.pos+=4},writeDouble:function(t){this.realloc(8),this.buf.writeDoubleLE(t,this.pos),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&function(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,o,e)},writePackedSVarint:function(t,e){this.writeMessage(t,s,e)},writePackedBoolean:function(t,e){this.writeMessage(t,u,e)},writePackedFloat:function(t,e){this.writeMessage(t,l,e)},writePackedDouble:function(t,e){this.writeMessage(t,c,e)},writePackedFixed32:function(t,e){this.writeMessage(t,f,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,h,e)},writePackedFixed64:function(t,e){this.writeMessage(t,d,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,p,e)},writeBytesField:function(t,e){this.writeTag(t,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,i.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,i.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,i.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./buffer":450}],452:[function(t,e,r){"use strict";e.exports=function(t){var e=t.length;if(e0;--o)a=l[o],r=s[o],s[o]=s[a],s[a]=r,l[o]=l[r],l[r]=a,c=(c+r)*o;return n.freeUint32(l),n.freeUint32(s),c},r.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}},{"invert-permutation":260,"typedarray-pool":534}],454:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,a,o={};if("string"==typeof e&&(e=i(e)),Array.isArray(e)){var s={};for(a=0;a0){o=a[u][r][0],l=u;break}s=o[1^l];for(var f=0;f<2;++f)for(var h=a[f][r],d=0;d0&&(o=p,s=m,l=f)}return i?s:(o&&c(o,l),s)}function f(t,r){var i=a[r][t][0],o=[t];c(i,r);for(var s=i[1^r];;){for(;s!==t;)o.push(s),s=u(o[o.length-2],s,!1);if(a[0][t].length+a[1][t].length===0)break;var l=o[o.length-1],f=t,h=o[1],d=u(l,f,!0);if(n(e[l],e[f],e[h],e[d])<0)break;o.push(t),s=u(l,f)}return o}function h(t,e){return e[1]===e[e.length-1]}for(var o=0;o0;){a[0][o].length;var m=f(o,d);h(p,m)?p.push.apply(p,m):(p.length>0&&l.push(p),p=m)}p.length>0&&l.push(p)}return l};var n=t("compare-angle")},{"compare-angle":106}],456:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=n(t,e.length),i=new Array(e.length),a=new Array(e.length),o=[],s=0;s0;){var c=o.pop();i[c]=!1;for(var u=r[c],s=0;s0})).length,v=new Array(m),g=new Array(m),d=0;d0;){var j=N.pop(),B=L[j];l(B,function(t,e){return t-e});var U,V=B.length,q=F[j];if(0===q){var M=p[j];U=[M]}for(var d=0;d=0)&&(F[H]=1^q,N.push(H),0===q)){var M=p[H];R(M)||(M.reverse(),U.push(M))}}0===q&&r.push(U)}return r};var n=t("edges-to-adjacency-list"),i=t("planar-dual"),a=t("point-in-big-polygon"),o=t("two-product"),s=t("robust-sum"),l=t("uniq"),c=t("./lib/trim-leaves");function u(t,e){for(var r=new Array(t),n=0;n0&&e[i]===r[0]))return 1;a=t[i-1]}for(var s=1;a;){var l=a.key,c=n(r,l[0],l[1]);if(l[0][0]0))return 0;s=-1,a=a.right}else if(c>0)a=a.left;else{if(!(c<0))return 0;s=1,a=a.right}}return s}}(g.slabs,g.coordinates);return 0===a.length?y:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(l(a),y)};var n=t("robust-orientation")[3],i=t("slab-decomposition"),a=t("interval-tree-1d"),o=t("binary-search-bounds");function s(){return!0}function l(t){for(var e={},r=0;r=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-c)*(i-u)/(o-u)+c-n>t&&(s=!s),a=c,o=u}return s}};return e}},{}],463:[function(t,e,r){var n={toPolygon:function(t,e){function r(e){if(e.length<=0)return t.segments({inverted:!1,regions:[]});function r(e){var r=e.slice(0,e.length-1);return t.segments({inverted:!1,regions:[r]})}for(var n=r(e[0]),i=1;i0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,s=i.end,c=a.start,u=a.end;r&&r.checkIntersection(i,a);var f=e.linesIntersect(o,s,c,u);if(!1===f){if(!e.pointsCollinear(o,s,c))return!1;if(e.pointsSame(o,u)||e.pointsSame(s,c))return!1;var h=e.pointsSame(o,c),d=e.pointsSame(s,u);if(h&&d)return n;var p=!h&&e.pointBetween(o,c,u),m=!d&&e.pointBetween(s,c,u);if(h)return m?l(n,s):l(t,u),n;p&&(d||(m?l(n,s):l(t,u)),l(n,o))}else 0===f.alongA&&(-1===f.alongB?l(t,c):0===f.alongB?l(t,f.pt):1===f.alongB&&l(t,u)),0===f.alongB&&(-1===f.alongA?l(n,o):0===f.alongA?l(n,f.pt):1===f.alongA&&l(n,s));return!1}for(var f=[];!a.isEmpty();){var h=a.getHead();if(r&&r.vert(h.pt[0]),h.isStart){r&&r.segmentNew(h.seg,h.primary);var d=c(h),p=d.before?d.before.ev:null,m=d.after?d.after.ev:null;function v(){if(p){var t=u(h,p);if(t)return t}return!!m&&u(h,m)}r&&r.tempStatus(h.seg,!!p&&p.seg,!!m&&m.seg);var g,y,b=v();if(b)t?(y=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below)&&(b.seg.myFill.above=!b.seg.myFill.above):b.seg.otherFill=h.seg.myFill,r&&r.segmentUpdate(b.seg),h.other.remove(),h.remove();if(a.getHead()!==h){r&&r.rewind(h.seg);continue}t?(y=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below,h.seg.myFill.below=m?m.seg.myFill.above:i,h.seg.myFill.above=y?!h.seg.myFill.below:h.seg.myFill.below):null===h.seg.otherFill&&(g=m?h.primary===m.primary?m.seg.otherFill.above:m.seg.myFill.above:h.primary?o:i,h.seg.otherFill={above:g,below:g}),r&&r.status(h.seg,!!p&&p.seg,!!m&&m.seg),h.other.status=d.insert(n.node({ev:h}))}else{var x=h.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(s.exists(x.prev)&&s.exists(x.next)&&u(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!h.primary){var _=h.seg.myFill;h.seg.myFill=h.seg.otherFill,h.seg.otherFill=_}f.push(h.seg)}a.getHead().remove()}return r&&r.done(),f}return t?{addRegion:function(t){for(var n,i,a,o=t[t.length-1],l=0;l=c?(k=1,y=c+2*h+p):y=h*(k=-h/c)+p):(k=0,d>=0?(A=0,y=p):-d>=f?(A=1,y=f+2*d+p):y=d*(A=-d/f)+p);else if(A<0)A=0,h>=0?(k=0,y=p):-h>=c?(k=1,y=c+2*h+p):y=h*(k=-h/c)+p;else{var T=1/M;y=(k*=T)*(c*k+u*(A*=T)+2*h)+A*(u*k+f*A+2*d)+p}else k<0?(x=f+d)>(b=u+h)?(_=x-b)>=(w=c-2*u+f)?(k=1,A=0,y=c+2*h+p):y=(k=_/w)*(c*k+u*(A=1-k)+2*h)+A*(u*k+f*A+2*d)+p:(k=0,x<=0?(A=1,y=f+2*d+p):d>=0?(A=0,y=p):y=d*(A=-d/f)+p):A<0?(x=c+h)>(b=u+d)?(_=x-b)>=(w=c-2*u+f)?(A=1,k=0,y=f+2*d+p):y=(k=1-(A=_/w))*(c*k+u*A+2*h)+A*(u*k+f*A+2*d)+p:(A=0,x<=0?(k=1,y=c+2*h+p):h>=0?(k=0,y=p):y=h*(k=-h/c)+p):(_=f+d-u-h)<=0?(k=0,A=1,y=f+2*d+p):_>=(w=c-2*u+f)?(k=1,A=0,y=c+2*h+p):y=(k=_/w)*(c*k+u*(A=1-k)+2*h)+A*(u*k+f*A+2*d)+p;var E=1-k-A;for(l=0;l1)for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=u-f,M=Math.floor,k=String.fromCharCode;function A(t){throw new RangeError(_[t])}function T(t,e){for(var r=t.length,n=[];r--;)n[r]=e(t[r]);return n}function E(t,e){var r=t.split("@"),n="";return r.length>1&&(n=r[0]+"@",t=r[1]),n+T((t=t.replace(x,".")).split("."),e).join(".")}function S(t){for(var e,r,n=[],i=0,a=t.length;i=55296&&e<=56319&&i65535&&(e+=k((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+=k(t)}).join("")}function C(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,r){var n=0;for(t=r?M(t/p):t>>1,t+=M(t/e);t>w*h>>1;n+=u)t=M(t/w);return M(n+(w+1)*t/(t+d))}function z(t){var e,r,n,i,a,o,s,l,d,p,y,b=[],x=t.length,_=0,w=v,k=m;for((r=t.lastIndexOf(g))<0&&(r=0),n=0;n=128&&A("not-basic"),b.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=x&&A("invalid-input"),((l=(y=t.charCodeAt(i++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:u)>=u||l>M((c-_)/o))&&A("overflow"),_+=l*o,!(l<(d=s<=k?f:s>=k+h?h:s-k));s+=u)o>M(c/(p=u-d))&&A("overflow"),o*=p;k=P(_-a,e=b.length+1,0==a),M(_/e)>c-w&&A("overflow"),w+=M(_/e),_%=e,b.splice(_++,0,w)}return L(b)}function O(t){var e,r,n,i,a,o,s,l,d,p,y,b,x,_,w,T=[];for(b=(t=S(t)).length,e=v,r=0,a=m,o=0;o=e&&yM((c-r)/(x=n+1))&&A("overflow"),r+=(s-e)*x,e=s,o=0;oc&&A("overflow"),y==e){for(l=r,d=u;!(l<(p=d<=a?f:d>=a+h?h:d-a));d+=u)w=l-p,_=u-p,T.push(k(C(p+w%_,0))),l=M(w/_);T.push(k(C(l,0))),a=P(r,x,n==i),r=0,++n}++r,++e}return T.join("")}if(s={version:"1.4.1",ucs2:{decode:S,encode:L},decode:z,encode:O,toASCII:function(t){return E(t,function(t){return b.test(t)?"xn--"+O(t):t})},toUnicode:function(t){return E(t,function(t){return y.test(t)?z(t.slice(4).toLowerCase()):t})}},i&&a)if(e.exports==i)a.exports=s;else for(l in s)s.hasOwnProperty(l)&&(i[l]=s[l]);else n.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],471:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":213}],472:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,a){e=e||"&",r=r||"=";var o={};if("string"!=typeof t||0===t.length)return o;var s=/\+/g;t=t.split(e);var l=1e3;a&&"number"==typeof a.maxKeys&&(l=a.maxKeys);var c=t.length;l>0&&c>l&&(c=l);for(var u=0;u=0?(f=m.substr(0,v),h=m.substr(v+1)):(f=m,h=""),d=decodeURIComponent(f),p=decodeURIComponent(h),n(o,d)?i(o[d])?o[d].push(p):o[d]=[o[d],p]:o[d]=p}return o};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],473:[function(t,e,r){"use strict";var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};e.exports=function(t,e,r,s){return e=e||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?a(o(t),function(o){var s=encodeURIComponent(n(o))+r;return i(t[o])?a(t[o],function(t){return s+encodeURIComponent(n(t))}).join(e):s+encodeURIComponent(n(t[o]))}).join(e):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(t)):""};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)};function a(t,e){if(t.map)return t.map(e);for(var r=[],n=0;nn;){if(a-n>600){var s=a-n+1,l=r-n+1,c=Math.log(s),u=.5*Math.exp(2*c/3),f=.5*Math.sqrt(c*u*(s-u)/s)*(l-s/2<0?-1:1),h=Math.max(n,Math.floor(r-l*u/s+f)),d=Math.min(a,Math.floor(r+(s-l)*u/s+f));t(e,r,h,d,o)}var p=e[r],m=n,v=a;for(i(e,n,r),o(e[a],p)>0&&i(e,n,a);m0;)v--}0===o(e[n],p)?i(e,n,v):i(e,++v,a),v<=r&&(n=v+1),r<=v&&(a=v-1)}}(t,e,r||0,n||t.length-1,o||a)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function a(t,e){return te?1:0}e.exports=n,e.exports.default=n},{}],476:[function(t,e,r){"use strict";var n=t("big-rat/add");e.exports=function(t,e){for(var r=t.length,i=new Array(r),a=0;a0){var c=t[r-1];if(0===n(s,c)&&a(c)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}},{"cell-orientation":91,"compare-cell":107,"compare-oriented-cell":108}],481:[function(t,e,r){"use strict";var n=t("array-bounds"),i=t("color-normalize"),a=t("update-diff"),o=t("pick-by-alias"),s=t("object-assign"),l=t("flatten-vertex-data"),c=t("to-float32"),u=c.float32,f=c.fract32;e.exports=function(t,e){"function"==typeof t?(e||(e={}),e.regl=t):e=t;e.length&&(e.positions=e);if(!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");var r,c,d,p,m,v,g=t._gl,y={color:"black",capSize:5,lineWidth:1,opacity:1,viewport:null,range:null,offset:0,count:0,bounds:null,positions:[],errors:[]},b=[];return p=t.buffer({usage:"dynamic",type:"uint8",data:null}),c=t.buffer({usage:"dynamic",type:"float",data:null}),d=t.buffer({usage:"dynamic",type:"float",data:null}),m=t.buffer({usage:"dynamic",type:"float",data:null}),v=t.buffer({usage:"static",type:"float",data:h}),M(e),r=t({vert:"\n\t\tprecision highp float;\n\n\t\tattribute vec2 position, positionFract;\n\t\tattribute vec4 error;\n\t\tattribute vec4 color;\n\n\t\tattribute vec2 direction, lineOffset, capOffset;\n\n\t\tuniform vec4 viewport;\n\t\tuniform float lineWidth, capSize;\n\t\tuniform vec2 scale, scaleFract, translate, translateFract;\n\n\t\tvarying vec4 fragColor;\n\n\t\tvoid main() {\n\t\t\tfragColor = color / 255.;\n\n\t\t\tvec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset;\n\n\t\t\tvec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw;\n\n\t\t\tvec2 position = position + dxy;\n\n\t\t\tvec2 pos = (position + translate) * scale\n\t\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t\t+ (position + translate) * scaleFract\n\t\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n\t\t\tpos += pixelOffset / viewport.zw;\n\n\t\t\tgl_Position = vec4(pos * 2. - 1., 0, 1);\n\t\t}\n\t\t",frag:"\n\t\tprecision mediump float;\n\n\t\tvarying vec4 fragColor;\n\n\t\tuniform float opacity;\n\n\t\tvoid main() {\n\t\t\tgl_FragColor = fragColor;\n\t\t\tgl_FragColor.a *= opacity;\n\t\t}\n\t\t",uniforms:{range:t.prop("range"),lineWidth:t.prop("lineWidth"),capSize:t.prop("capSize"),opacity:t.prop("opacity"),scale:t.prop("scale"),translate:t.prop("translate"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{color:{buffer:p,offset:function(t,e){return 4*e.offset},divisor:1},position:{buffer:c,offset:function(t,e){return 8*e.offset},divisor:1},positionFract:{buffer:d,offset:function(t,e){return 8*e.offset},divisor:1},error:{buffer:m,offset:function(t,e){return 16*e.offset},divisor:1},direction:{buffer:v,stride:24,offset:0},lineOffset:{buffer:v,stride:24,offset:8},capOffset:{buffer:v,stride:24,offset:16}},primitive:"triangles",blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:!1},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport"),stencil:!1,instances:t.prop("count"),count:h.length}),s(x,{update:M,draw:_,destroy:k,regl:t,gl:g,canvas:g.canvas,groups:b}),x;function x(t){t?M(t):null===t&&k(),_()}function _(e){if("number"==typeof e)return w(e);e&&!Array.isArray(e)&&(e=[e]),t._refresh(),b.forEach(function(t,r){t&&(e&&(e[r]?t.draw=!0:t.draw=!1),t.draw?w(r):t.draw=!0)})}function w(t){"number"==typeof t&&(t=b[t]),null!=t&&t&&t.count&&t.color&&t.opacity&&t.positions&&t.positions.length>1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function M(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(b=t.map(function(t,c){var u=b[c];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=o(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),u||(b[c]=u={id:c,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=s({},y,t)),a(u,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=l(t),r+=t.length,t},positions:function(t,r){return t=l(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=n(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var a=0;a2&&(t._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&p(e),e.thickness&&e.color&&(e.scaleRatio=[e.scale[0]*e.viewport.width,e.scale[1]*e.viewport.height],e.scaleRatio[0]>k||e.scaleRatio[1]>k?d(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.positions.length>=A)?d(e):r(e),e.after&&e.after(e)))}function C(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0;if(E.lines=w=t.map(function(t,r){var o=w[r];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=s(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color stroke colors stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow",after:"after callback done pass"}),o||(w[r]=o={id:r,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,offset:0,dashLength:0,hole:!0},t=a({},_,t)),l(o,t,[{thickness:parseFloat,opacity:parseFloat,miterLimit:parseFloat,overlay:Boolean,join:function(t){return t},after:function(t){return t},hole:function(t){return t||[]},positions:function(t,r,n){t=c(t,"float64");var a=Math.floor(t.length/2),o=i(t,2);return r.range||n.range||(n.range=o),r.count=a,r.bounds=o,e+=a,t},fill:function(t){return t?n(t,"uint8"):null},dashes:function(t,e,r){var n,i=e.dashLength;if(!t||t.length<2)i=1,n=new Uint8Array([255,255,255,255,255,255,255,255]);else{i=0;for(var a=0;a=4&&e.positions[0]===e.positions[e.positions.length-2]&&e.positions[1]===e.positions[e.positions.length-1]},positions:function(t,e,r){if(e.fill&&t.length){for(var n=[],i={},a=0,o=0,s=0,l=e.count;o 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:v,divisor:0,stride:8,offset:0},lineTop:{buffer:v,divisor:0,stride:8,offset:4},aColor:{buffer:m,stride:4,offset:function(t,e){return 4*e.offset},divisor:1},bColor:{buffer:m,stride:4,offset:function(t,e){return 4*e.offset+4},divisor:1},prevCoord:{buffer:g,stride:8,offset:function(t,e){return 8*e.offset},divisor:1},aCoord:{buffer:g,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:g,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},nextCoord:{buffer:g,stride:8,offset:function(t,e){return 24+8*e.offset},divisor:1}}},T)),d=t(a({vert:o(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:v,divisor:0,stride:8,offset:0},lineTop:{buffer:v,divisor:0,stride:8,offset:4},aCoord:{buffer:g,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:g,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},aCoordFract:{buffer:y,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoordFract:{buffer:y,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},color:{buffer:m,stride:4,offset:function(t,e){return 4*e.offset},divisor:1}}},T)),p=t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:o(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:o(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:g,stride:8,offset:function(t,e){return 8+8*e.offset}},positionFract:{buffer:y,stride:8,offset:function(t,e){return 8+8*e.offset}}},blend:T.blend,depth:{enable:!1},scissor:T.scissor,stencil:T.stencil,viewport:T.viewport}),a(E,{update:C,draw:S,destroy:P,regl:t,gl:x,canvas:x.canvas,lines:w}),E};function h(t){var e=new Float32Array(t.length);e.set(t);for(var r=0,n=e.length;r 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]),vert:l(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float paletteSize = 4096., maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]),uniforms:{color:function(t,e){var r=e.color.length?e.color[0]:e.color;return k.slice(4*r,4*r+4).map(function(t){return t/255})},borderColor:function(t,e){var r=e.borderColor.length?e.borderColor[0]:e.borderColor;return k.slice(4*r,4*r+4).map(function(t){return t/255})},pixelRatio:t.context("pixelRatio"),palette:w,scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("marker")},attributes:{position:b,positionFract:x,size:z.attributes.size,borderSize:z.attributes.borderSize}}));else{var O=s({},z);O.frag=l(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]),O.vert=l(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute float colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float paletteSize = 4096., maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvoid main() {\n vec4 color = texture2D(palette, vec2((colorId + .5) / paletteSize, 0));\n vec4 borderColor = texture2D(palette, vec2((borderColorId + .5) / paletteSize, 0));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]),r=t(O);var D=s({},z);D.frag=l(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),D.vert=l(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute float colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float paletteSize = 4096., maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n vec4 color = texture2D(palette, vec2((colorId + .5) / paletteSize, 0));\n vec4 borderColor = texture2D(palette, vec2((borderColorId + .5) / paletteSize, 0));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]),p=t(D)}function I(t){t?j(t):null===t&&H(),R()}function R(t){if("number"==typeof t)return N(t);Array.isArray(t)?t.forEach(function(t,e){if(null!=t)return t.length?N(t,e):N(t)}):E.forEach(function(t,e){t&&N(e)})}function N(e,n){var i;if("number"==typeof e&&(e=E[e]),Array.isArray(e)&&(i=e,e=E[n]),e&&e.count&&e.opacity){var a;if(i){a=Array(e.count);for(var o=0;o1)){var m=p.offset,v=p.count+m,g=c.ge(u,n[0],m,v-1),y=c.lt(u,n[2],g,v-1)+1;if(!(y<=g))if(r){var b=x(t.data.subarray(g,y),r);o.push(s({},e,{elements:b,marker:S[f],offset:0,count:b.length}))}else o.push(s({},e,{elements:t.elements,marker:S[f],offset:g,count:y-g}))}}function x(t,e){for(var r=[],n=0,a=t.length;ni)){c.snap=!0;var h=c.x=Array(u),d=c.w=Array(u),p=void 0;if(n.length>1){p=Array(2*u);for(var m=0;m=0)return n;if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)r=e;else{r=new Uint8Array(e.length);for(var i=0,a=e.length;i4*C&&(t=t.slice(0,4*C)),w.subimage({width:Math.min(.25*t.length,C),height:1,data:t},0,0)}function H(){E.length=0,y.destroy(),b.destroy(),x.destroy(),_.destroy(),w.destroy()}return s(I,{update:j,draw:R,destroy:H,regl:t,gl:M,canvas:M.canvas,groups:E,markers:L,palette:k}),I}},{"array-bounds":48,"array-range":50,"binary-search-bounds":484,"color-id":97,"color-normalize":99,"flatten-vertex-data":143,glslify:485,"is-iexplorer":264,"object-assign":443,"pick-by-alias":454,"snap-points-2d":514,"to-float32":527,"update-diff":538}],484:[function(t,e,r){arguments[4][90][0].apply(r,arguments)},{dup:90}],485:[function(t,e,r){arguments[4][169][0].apply(r,arguments)},{dup:169}],486:[function(t,e,r){var n,i;n=this,i=function(){function t(t,e){this.id=U++,this.type=t,this.data=e}function e(t){return"["+function t(e){if(0===e.length)return[];var r=e.charAt(0),n=e.charAt(e.length-1);if(1>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function l(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=W[s(t)>>2]).length?e.pop():new ArrayBuffer(t)}function c(t){W[s(t.byteLength)>>2].push(t)}function u(t,e,r,n,i,a){for(var o=0;o(i=l)&&(i=n.buffer.byteLength,5123===f?i>>=1:5125===f&&(i>>=2)),n.vertCount=i,i=s,0>s&&(i=4,1===(s=n.buffer.dimension)&&(i=0),2===s&&(i=1),3===s&&(i=4)),n.primType=i}function s(t){n.elementsCount--,delete l[t.id],t.buffer.destroy(),t.buffer=null}var l={},c=0,u={uint8:5121,uint16:5123};e.oes_element_index_uint&&(u.uint32=5125),i.prototype.bind=function(){this.buffer.bind()};var f=[];return{create:function(t,e){function l(t){if(t)if("number"==typeof t)c(t),f.primType=4,f.vertCount=0|t,f.type=5121;else{var e=null,r=35044,n=-1,i=-1,s=0,h=0;Array.isArray(t)||G(t)||a(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=Q[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(i=0|t.count),"type"in t&&(h=u[t.type]),"length"in t?s=0|t.length:(s=i,5123===h||5122===h?s*=2:5125!==h&&5124!==h||(s*=4))),o(f,e,r,n,i,s,h)}else c(),f.primType=4,f.vertCount=0,f.type=5121;return l}var c=r.create(null,34963,!0),f=new i(c._buffer);return n.elementsCount++,l(t),l._reglType="elements",l._elements=f,l.subdata=function(t,e){return c.subdata(t,e),l},l.destroy=function(){s(f)},l},createStream:function(t){var e=f.pop();return e||(e=new i(r.create(null,34963,!0,!1)._buffer)),o(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){f.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof i?t._elements:null},clear:function(){Y(l).forEach(s)}}}function v(t){for(var e=X.allocType(5123,t.length),r=0;r>>31<<15,i=(a<<1>>>24)-127,a=a>>13&1023;e[r]=-24>i?n:-14>i?n+(a+1024>>-14-i):15>=i,r.height>>=i,d(r,n[i]),t.mipmask|=1<e;++e)t.images[e]=null;return t}function L(t){for(var e=t.images,r=0;re){for(var r=0;r=--this.refCount&&R(this)}}),s.profile&&(o.getTotalTextureSize=function(){var t=0;return Object.keys(ft).forEach(function(e){t+=ft[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=i.texInfo;C.call(r);var a=S();return"number"==typeof t?A(a,0|t,"number"==typeof e?0|e:0|t):t?(P(r,t),T(a,t)):A(a,1,1),r.genMipmaps&&(a.mipmask=(a.width<<1)-1),i.mipmask=a.mipmask,c(i,a),i.internalformat=a.internalformat,n.width=a.width,n.height=a.height,D(i),E(a,3553),z(r,3553),I(),L(a),s.profile&&(i.stats.size=M(i.internalformat,i.type,a.width,a.height,r.genMipmaps,!1)),n.format=$[i.internalformat],n.type=tt[i.type],n.mag=et[r.magFilter],n.min=rt[r.minFilter],n.wrapS=nt[r.wrapS],n.wrapT=nt[r.wrapT],n}var i=new O(3553);return ft[i.id]=i,o.textureCount++,n(e,r),n.subimage=function(t,e,r,a){e|=0,r|=0,a|=0;var o=m();return c(o,i),o.width=0,o.height=0,d(o,t),o.width=o.width||(i.width>>a)-e,o.height=o.height||(i.height>>a)-r,D(i),p(o,3553,e,r,a),I(),k(o),n},n.resize=function(e,r){var a=0|e,o=0|r||a;if(a===i.width&&o===i.height)return n;n.width=i.width=a,n.height=i.height=o,D(i);for(var l=0;i.mipmask>>l;++l)t.texImage2D(3553,l,i.format,a>>l,o>>l,0,i.format,i.type,null);return I(),s.profile&&(i.stats.size=M(i.internalformat,i.type,a,o,!1,!1)),n},n._reglType="texture2d",n._texture=i,s.profile&&(n.stats=i.stats),n.destroy=function(){i.decRef()},n},createCube:function(e,r,n,i,a,l){function f(t,e,r,n,i,a){var o,l=h.texInfo;for(C.call(l),o=0;6>o;++o)v[o]=S();if("number"!=typeof t&&t){if("object"==typeof t)if(e)T(v[0],t),T(v[1],e),T(v[2],r),T(v[3],n),T(v[4],i),T(v[5],a);else if(P(l,t),u(h,t),"faces"in t)for(t=t.faces,o=0;6>o;++o)c(v[o],h),T(v[o],t[o]);else for(o=0;6>o;++o)T(v[o],t)}else for(t=0|t||1,o=0;6>o;++o)A(v[o],t,t);for(c(h,v[0]),h.mipmask=l.genMipmaps?(v[0].width<<1)-1:v[0].mipmask,h.internalformat=v[0].internalformat,f.width=v[0].width,f.height=v[0].height,D(h),o=0;6>o;++o)E(v[o],34069+o);for(z(l,34067),I(),s.profile&&(h.stats.size=M(h.internalformat,h.type,f.width,f.height,l.genMipmaps,!0)),f.format=$[h.internalformat],f.type=tt[h.type],f.mag=et[l.magFilter],f.min=rt[l.minFilter],f.wrapS=nt[l.wrapS],f.wrapT=nt[l.wrapT],o=0;6>o;++o)L(v[o]);return f}var h=new O(34067);ft[h.id]=h,o.cubeCount++;var v=Array(6);return f(e,r,n,i,a,l),f.subimage=function(t,e,r,n,i){r|=0,n|=0,i|=0;var a=m();return c(a,h),a.width=0,a.height=0,d(a,e),a.width=a.width||(h.width>>i)-r,a.height=a.height||(h.height>>i)-n,D(h),p(a,34069+t,r,n,i),I(),k(a),f},f.resize=function(e){if((e|=0)!==h.width){f.width=h.width=e,f.height=h.height=e,D(h);for(var r=0;6>r;++r)for(var n=0;h.mipmask>>n;++n)t.texImage2D(34069+r,n,h.format,e>>n,e>>n,0,h.format,h.type,null);return I(),s.profile&&(h.stats.size=M(h.internalformat,h.type,f.width,f.height,!1,!0)),f}},f._reglType="textureCube",f._texture=h,s.profile&&(f.stats=h.stats),f.destroy=function(){h.decRef()},f},clear:function(){for(var e=0;er;++r)if(0!=(e.mipmask&1<>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);z(e.texInfo,e.target)})}}}function A(t,e,r,n,i,a){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function s(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function l(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function c(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function u(t){var e=3553,r=null,n=null,i=t;return"object"==typeof t&&(i=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=i._reglType)?r=i:"textureCube"===t?r=i:"renderbuffer"===t&&(n=i,e=36161),new o(e,r,n)}function f(t,e,r,a,s){return r?((t=n.create2D({width:t,height:e,format:a,type:s}))._texture.refCount=0,new o(3553,t,null)):((t=i.create({width:t,height:e,format:a}))._renderbuffer.refCount=0,new o(36161,null,t))}function h(t){return t&&(t.texture||t.renderbuffer)}function d(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r))}function p(){this.id=M++,k[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function m(t){t.colorAttachments.forEach(s),s(t.depthAttachment),s(t.stencilAttachment),s(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,a.framebufferCount--,delete k[e.id]}function g(e){var n;t.bindFramebuffer(36160,e.framebuffer);var i=e.colorAttachments;for(n=0;ni;++i){for(c=0;ct;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){Y(k).forEach(v)},restore:function(){Y(k).forEach(function(e){e.framebuffer=t.createFramebuffer(),g(e)})}})}function T(){this.w=this.z=this.y=this.x=this.state=0,this.buffer=null,this.size=0,this.normalized=!1,this.type=5126,this.divisor=this.stride=this.offset=0}function E(t,e,r,n){function i(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function a(t,e){for(var r=0;rt&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return h.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);Y(c).forEach(e),c={},Y(u).forEach(e),u={},h.forEach(function(e){t.deleteProgram(e.program)}),h.length=0,f={},r.shaderCount=0},program:function(t,e,n){var i=f[e];i||(i=f[e]={});var a=i[t];return a||(a=new s(e,t),r.shaderCount++,l(a),i[t]=a,h.push(a)),a},restore:function(){c={},u={};for(var t=0;t="+e+"?"+i+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",i,".buffer)){",u,"=",s,".createStream(",34962,",",i,".buffer);","}else{",u,"=",s,".getBuffer(",i,".buffer);","}",f,'="type" in ',i,"?",a.glTypes,"[",i,".type]:",u,".dtype;",l.normalized,"=!!",i,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",l.isStream,"){",s,".destroyStream(",u,");","}"),l})}),o}function A(t,e,r,n,i){var a=_(t),s=function(t,e,r){function n(t){if(t in i){var r=i[t];t=!0;var n,o,s=0|r.x,l=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new D(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var i=t.shared.context,a=n;"width"in r||(a=e.def(i,".","framebufferWidth","-",s));var c=o;return"height"in r||(c=e.def(i,".","framebufferHeight","-",l)),[s,l,a,c]})}if(t in a){var c=a[t];return t=N(c,function(t,e){var r=t.invoke(e,c),n=t.shared.context,i=e.def(r,".x|0"),a=e.def(r,".y|0");return[i,a,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",i,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",a,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new D(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var i=t.static,a=t.dynamic;if(t=n("viewport")){var o=t;t=new D(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,a),l=M(t),c=function(t,e){var r=t.static,n=t.dynamic,i={};return nt.forEach(function(t){function e(e,o){if(t in r){var s=e(r[t]);i[a]=R(function(){return s})}else if(t in n){var l=n[t];i[a]=N(l,function(t,e){return o(t,e,t.invoke(e,l))})}}var a=v(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return yt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[gt["srcRGB"in t?t.srcRGB:t.src],gt["dstRGB"in t?t.dstRGB:t.dst],gt["srcAlpha"in t?t.srcAlpha:t.src],gt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var i=n("src","RGB"),a=n("dst","RGB"),o=(i=e.def(t,"[",i,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[i,a=e.def(t,"[",a,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[J[t],J[t]]:"object"==typeof t?[J[t.rgb],J[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,i=e.def(),a=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(i,"=",a,"=",n,"[",r,"];"),t.else(i,"=",n,"[",r,".rgb];",a,"=",n,"[",r,".alpha];"),e(t),[i,a]});case"blend.color":return e(function(t){return o(4,function(e){return+t[e]})},function(t,e,r){return o(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[yt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,bt[e.fail||"keep"],bt[e.zfail||"keep"],bt[e.zpass||"keep"]]},function(e,r,n){function i(t){return r.def('"',t,'" in ',n,"?",a,"[",n,".",t,"]:",7680)}var a=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,i("fail"),i("zfail"),i("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return xt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return o(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),i}(t),u=w(t),f=s.viewport;return f&&(c.viewport=f),(s=s[f=v("scissor.box")])&&(c[f]=s),(a={framebuffer:a,draw:l,shader:u,state:c,dirty:s=0>1)",s],");")}function e(){r(l,".drawArraysInstancedANGLE(",[p,m,v,s],");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(u+".drawElements("+[p,v,g,m+"<<(("+g+"-5121)>>1)"]+");")}function e(){r(u+".drawArrays("+[p,m,v]+");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}var s,l,c=t.shared,u=c.gl,f=c.draw,h=n.draw,d=function(){var i=h.elements,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(f,".","elements"),i&&a("if("+i+")"+u+".bindBuffer(34963,"+i+".buffer.buffer);"),i}(),p=i("primitive"),m=i("offset"),v=function(){var i=h.count,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(f,".","count"),i}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");Q&&(s=i("instances"),l=t.instancing);var g=d+".type",y=h.elements&&I(h.elements);Q&&("number"!=typeof s||0<=s)?"string"==typeof s?(r("if(",s,">0){"),a(),r("}else if(",s,"<0){"),o(),r("}")):a():o()}function q(t,e,r,n,i){return i=(e=x()).proc("body",i),Q&&(e.instancing=i.def(e.shared.extensions,".angle_instanced_arrays")),t(e,i,r,n),e.compile().body}function H(t,e,r,n){C(t,e),j(t,e,r,n.attributes,function(){return!0}),B(t,e,r,n.uniforms,function(){return!0}),U(t,e,e,r)}function G(t,e,r,n){function i(){return!0}t.batchId="a1",C(t,e),j(t,e,r,n.attributes,i),B(t,e,r,n.uniforms,i),U(t,e,e,r)}function Y(t,e,r,n){function i(t){return t.contextDep&&o||t.propDep}function a(t){return!i(t)}C(t,e);var o=r.contextDep,s=e.def(),l=e.def();t.shared.props=l,t.batchId=s;var c=t.scope(),u=t.scope();e(c.entry,"for(",s,"=0;",s,"<","a1",";++",s,"){",l,"=","a0","[",s,"];",u,"}",c.exit),r.needsContext&&T(t,u,r.context),r.needsFramebuffer&&E(t,u,r.framebuffer),L(t,u,r.state,i),r.profile&&i(r.profile)&&F(t,u,r,!1,!0),n?(j(t,c,r,n.attributes,a),j(t,u,r,n.attributes,i),B(t,c,r,n.uniforms,a),B(t,u,r,n.uniforms,i),U(t,c,u,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,u),l=u.def(n,".id"),c=u.def(e,"[",l,"]"),u(t.shared.gl,".useProgram(",n,".program);","if(!",c,"){",c,"=",e,"[",l,"]=",t.link(function(e){return q(G,t,r,e,2)}),"(",n,");}",c,".call(this,a0[",s,"],",s,");"))}function W(t,r){function n(e){var n=r.shader[e];n&&i.set(a.shader,"."+e,n.append(t,i))}var i=t.proc("scope",3);t.batchId="a2";var a=t.shared,o=a.current;T(t,i,r.context),r.framebuffer&&r.framebuffer.append(t,i),O(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,i);g(n)?n.forEach(function(r,n){i.set(t.next[e],"["+n+"]",r)}):i.set(a.next,"."+e,n)}),F(t,i,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&i.set(a.draw,"."+e,""+n.append(t,i))}),Object.keys(r.uniforms).forEach(function(n){i.set(a.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,i))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,i),a=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){i.set(a,"."+t,n[t])})}),n("vert"),n("frag"),0=--this.refCount&&o(this)},i.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(u).forEach(function(e){t+=u[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,a=0,u=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(a=e.shape)[0],a=0|a[1]):("radius"in e&&(n=a=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(a=0|e.height)),"format"in e&&(u=s[e.format])):"number"==typeof e?(n=0|e,a="number"==typeof r?0|r:n):e||(n=a=1),n!==c.width||a!==c.height||u!==c.format)return o.width=c.width=n,o.height=c.height=a,c.format=u,t.bindRenderbuffer(36161,c.renderbuffer),t.renderbufferStorage(36161,u,n,a),i.profile&&(c.stats.size=ft[c.format]*c.width*c.height),o.format=l[c.format],o}var c=new a(t.createRenderbuffer());return u[c.id]=c,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,a=0|r||n;return n===c.width&&a===c.height?o:(o.width=c.width=n,o.height=c.height=a,t.bindRenderbuffer(36161,c.renderbuffer),t.renderbufferStorage(36161,c.format,n,a),i.profile&&(c.stats.size=ft[c.format]*c.width*c.height),o)},o._reglType="renderbuffer",o._renderbuffer=c,i.profile&&(o.stats=c.stats),o.destroy=function(){c.decRef()},o},clear:function(){Y(u).forEach(o)},restore:function(){Y(u).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},dt=[];dt[6408]=4;var pt=[];pt[5121]=1,pt[5126]=4,pt[36193]=2;var mt=["x","y","z","w"],vt="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),gt={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},yt={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},bt={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},xt={cw:2304,ccw:2305},_t=new D(!1,!1,!1,function(){});return function(t){function e(){if(0===X.length)w&&w.update(),Q=null;else{Q=q.next(e),f();for(var t=X.length-1;0<=t;--t){var r=X[t];r&&r(P,null,0)}v.flush(),w&&w.update()}}function r(){!Q&&0=X.length&&n()}}}}function u(){var t=Y.viewport,e=Y.scissor_box;t[0]=t[1]=e[0]=e[1]=0,P.viewportWidth=P.framebufferWidth=P.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,P.viewportHeight=P.framebufferHeight=P.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function f(){P.tick+=1,P.time=d(),u(),G.procs.poll()}function h(){u(),G.procs.refresh(),w&&w.update()}function d(){return(H()-M)/1e3}if(!(t=i(t)))return null;var v=t.gl,g=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},i=0;ie;++e)$(B({framebuffer:t.framebuffer.faces[e]},t),l);else $(t,l);else l(0,t)},prop:V.define.bind(null,1),context:V.define.bind(null,2),this:V.define.bind(null,3),draw:s({}),buffer:function(t){return O.create(t,34962,!1,!1)},elements:function(t){return D.create(t,!1)},texture:R.create2D,cube:R.createCube,renderbuffer:N.create,framebuffer:U.create,framebufferCube:U.createCube,attributes:g,frame:c,on:function(t,e){var r;switch(t){case"frame":return c(e);case"lost":r=Z;break;case"restore":r=J;break;case"destroy":r=K}return r.push(e),{cancel:function(){for(var t=0;t=r)return i.substr(0,r);for(;r>i.length&&e>1;)1&e&&(i+=t),e>>=1,t+=t;return i=(i+=t).substr(0,r)}},{}],488:[function(t,e,r){var n,i;n=this,i=function(){return function(){var t=arguments.length;if(0===t)throw new Error("resolveUrl requires at least one argument; got none.");var e=document.createElement("base");if(e.href=arguments[0],1===t)return e.href;var r=document.getElementsByTagName("head")[0];r.insertBefore(e,r.firstChild);for(var n,i=document.createElement("a"),a=1;a=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var c=0,i=n;i>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function u(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",c(function(t){for(var e=new Array(t),r=0;r>1;return["sum(",c(t.slice(0,e)),",",c(t.slice(e)),")"].join("")}function u(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return u(e,t)}function f(t){if(2===t.length)return[["diff(",u(t[0][0],t[1][1]),",",u(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0&&r.push(","),r.push("[");for(var o=0;o0&&r.push(","),o===i?r.push("+b[",a,"]"):r.push("+A[",a,"][",o,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var s=new Function("det",r.join(""));return s(t<6?n[t]:n)}var o=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];!function(){for(;o.length>1;return["sum(",c(t.slice(0,e)),",",c(t.slice(e)),")"].join("")}function u(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:h(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],c=r[1]-n[1],u=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],p=a*c,m=o*l,v=o*s,g=i*c,y=i*l,b=a*s,x=u*(p-m)+f*(v-g)+h*(y-b),_=7.771561172376103e-16*((Math.abs(p)+Math.abs(m))*Math.abs(u)+(Math.abs(v)+Math.abs(g))*Math.abs(f)+(Math.abs(y)+Math.abs(b))*Math.abs(h));return x>_||-x>_?x:d(t,e,r,n)}];!function(){for(;p.length<=s;)p.push(f(p.length));for(var t=[],r=["slow"],n=0;n<=s;++n)t.push("a"+n),r.push("o"+n);var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(n=2;n<=s;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i0&&o>0||a<0&&o<0)return!1;var s=n(r,t,e),l=n(i,t,e);if(s>0&&l>0||s<0&&l<0)return!1;if(0===a&&0===o&&0===s&&0===l)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),c=r[i],u=n[i],f=Math.min(c,u),h=Math.max(c,u);if(h=n?(i=f,(l+=1)=n?(i=f,(l+=1)0){for(var s=0,l=0,c=0;cn.h||t>n.free||rs)&&(l=2*Math.max(t,s)),(aa)&&(o=2*Math.max(r,a)),this.resize(l,o),this.packOne(t,r)):null},t.prototype.clear=function(){this.shelves=[],this.stats={}},t.prototype.resize=function(t,e){this.w=t,this.h=e;for(var r=0;rthis.free||e>this.h)return null;var r=this.x;return this.x+=t,this.free-=t,{x:r,y:this.y,w:t,h:e,width:t,height:e}},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t},"object"==typeof r&&void 0!==e?e.exports=i():n.ShelfPack=i()},{}],502:[function(t,e,r){"use strict";e.exports=function(t){return t<0?-1:t>0?1:0}},{}],503:[function(t,e,r){"use strict";e.exports=function(t){return i(n(t))};var n=t("boundary-cells"),i=t("reduce-simplicial-complex")},{"boundary-cells":74,"reduce-simplicial-complex":480}],504:[function(t,e,r){"use strict";e.exports=function(t,e,r,s){r=r||0,void 0===s&&(s=function(t){for(var e=t.length,r=0,n=0;n>1,v=E[2*m+1];","if(v===b){return m}","if(b0&&l.push(","),l.push("[");for(var n=0;n0&&l.push(","),l.push("B(C,E,c[",i[0],"],c[",i[1],"])")}l.push("]")}l.push(");")}}for(var a=t+1;a>1;--a){a>1,s=a(t[o],e);s<=0?(0===s&&(i=o),r=o+1):s>0&&(n=o-1)}return i}function u(t,e){for(var r=new Array(t.length),i=0,o=r.length;i=t.length||0!==a(t[v],s)););}return r}function f(t,e){if(e<0)return[];for(var r=[],i=(1<>>u&1&&c.push(i[u]);e.push(c)}return s(e)},r.skeleton=f,r.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function b(t){for(var e=g(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n0;){var r=y(t);if(r>=0){var n=g(r);if(e0){var t=k[0];return v(0,E-1),E-=1,b(0),t}return-1}function w(t,e){var r=k[t];return c[r]===e?t:(c[r]=-1/0,x(t),_(),c[r]=e,x((E+=1)-1))}function M(t){if(!u[t]){u[t]=!0;var e=s[t],r=l[t];s[r]>=0&&(s[r]=e),l[e]>=0&&(l[e]=r),A[e]>=0&&w(A[e],m(e)),A[r]>=0&&w(A[r],m(r))}}for(var k=[],A=new Array(a),f=0;f>1;f>=0;--f)b(f);for(;;){var S=_();if(S<0||c[S]>r)break;M(S)}for(var L=[],f=0;f=0&&r>=0&&e!==r){var n=A[e],i=A[r];n!==i&&P.push([n,i])}}),i.unique(i.normalize(P)),{positions:L,edges:P}};var n=t("robust-orientation"),i=t("simplicial-complex")},{"robust-orientation":495,"simplicial-complex":508}],511:[function(t,e,r){"use strict";e.exports=function(t,e){var r,a,o,s;if(e[0][0]e[1][0]))return i(e,t);r=e[1],a=e[0]}if(t[0][0]t[1][0]))return-i(t,e);o=t[1],s=t[0]}var l=n(r,a,s),c=n(r,a,o);if(l<0){if(c<=0)return l}else if(l>0){if(c>=0)return l}else if(c)return c;if(l=n(s,o,a),c=n(s,o,r),l<0){if(c<=0)return l}else if(l>0){if(c>=0)return l}else if(c)return c;return a[0]-s[0]};var n=t("robust-orientation");function i(t,e){var r,i,a,o;if(e[0][0]e[1][0])){var s=Math.min(t[0][1],t[1][1]),l=Math.max(t[0][1],t[1][1]),c=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return lu?s-u:l-u}r=e[1],i=e[0]}t[0][1]0)if(e[0]!==o[1][0])r=t,t=t.right;else{if(l=c(t.right,e))return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l;if(l=c(t.right,e))return l;t=t.left}}return r}function u(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function f(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}s.prototype.castUp=function(t){var e=n.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=c(this.slabs[e],t),i=-1;if(r&&(i=r.value),this.coordinates[e]===t[0]){var s=null;if(r&&(s=r.key),e>0){var u=c(this.slabs[e-1],t);u&&(s?o(u.key,s)>0&&(s=u.key,i=u.value):(i=u.value,s=u.key))}var f=this.horizontal[e];if(f.length>0){var h=n.ge(f,t[1],l);if(h=f.length)return i;d=f[h]}}if(d.start)if(s){var p=a(s[0],s[1],[t[0],d.y]);s[0][0]>s[1][0]&&(p=-p),p>0&&(i=d.index)}else i=d.index;else d.y!==t[1]&&(i=d.index)}}}return i}},{"./lib/order-segments":511,"binary-search-bounds":70,"functional-red-black-tree":144,"robust-orientation":495}],513:[function(t,e,r){"use strict";e.exports=function(t,e,r,f,h){h<=4*n?i(0,h-1,t,e,r,f):function t(e,r,f,h,d,p){var m=(r-e+1)/6|0,v=e+m,g=r-m,y=e+r>>1,b=y-m,x=y+m,_=v,w=b,M=y,k=x,A=g,T=e+1,E=r-1,S=0;c(_,w,f,h,d)&&(S=_,_=w,w=S);c(k,A,f,h,d)&&(S=k,k=A,A=S);c(_,M,f,h,d)&&(S=_,_=M,M=S);c(w,M,f,h,d)&&(S=w,w=M,M=S);c(_,k,f,h,d)&&(S=_,_=k,k=S);c(M,k,f,h,d)&&(S=M,M=k,k=S);c(w,A,f,h,d)&&(S=w,w=A,A=S);c(w,M,f,h,d)&&(S=w,w=M,M=S);c(k,A,f,h,d)&&(S=k,k=A,A=S);var L=f[w];var C=h[2*w];var P=h[2*w+1];var z=d[w];var O=p[w];var D=f[k];var I=h[2*k];var R=h[2*k+1];var N=d[k];var F=p[k];var j=_;var B=M;var U=A;var V=v;var q=y;var H=g;var G=f[j];var Y=f[B];var W=f[U];f[V]=G;f[q]=Y;f[H]=W;for(var X=0;X<2;++X){var Z=h[2*j+X],J=h[2*B+X],K=h[2*U+X];h[2*V+X]=Z,h[2*q+X]=J,h[2*H+X]=K}var Q=d[j];var $=d[B];var tt=d[U];d[V]=Q;d[q]=$;d[H]=tt;var et=p[j];var rt=p[B];var nt=p[U];p[V]=et;p[q]=rt;p[H]=nt;o(b,e,f,h,d,p);o(x,r,f,h,d,p);for(var it=T;it<=E;++it)if(u(it,L,C,P,z,f,h,d))it!==T&&a(it,T,f,h,d,p),++T;else if(!u(it,D,I,R,N,f,h,d))for(;;){if(u(E,D,I,R,N,f,h,d)){u(E,L,C,P,z,f,h,d)?(s(it,T,E,f,h,d,p),++T,--E):(a(it,E,f,h,d,p),--E);break}if(--Et;){var d=r[h-1],p=n[2*(h-1)];if((d-s||l-p)>=0)break;r[h]=d,n[2*h]=p,n[2*h+1]=n[2*h-1],i[h]=i[h-1],a[h]=a[h-1],h-=1}r[h]=s,n[2*h]=l,n[2*h+1]=c,i[h]=u,a[h]=f}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],c=i[t],u=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=c,a[e]=u}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],c=i[2*t+1],u=a[t],f=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=c,a[r]=u,o[r]=f}function l(t,e,r,n,i,a,o,s,l,c,u){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],c[t]=c[e],u[t]=u[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,c[e]=a,u[e]=o}function c(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function u(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}},{}],514:[function(t,e,r){"use strict";var n=t("./lib/sort"),i=t("array-bounds");function a(t,e,r,n,i,a,o,s){for(var l=r,c=r;c>>1;if(l<1)return[];e||(e=Array(l));r||(r=Array(l));s||(s=[]);for(var c=0;c=s[2]||s[1]>=s[3]){var u=i(t,2);u[0]===u[2]&&(u[2]+=1),u[1]===u[3]&&(u[3]+=1),s[0]=u[0],s[1]=u[1],s[2]=u[2],s[3]=u[3]}var f=s[0],h=s[1],d=s[2],p=s[3],m=1/(d-f),v=1/(p-h),g=Math.max(d-f,p-h),y=new Int32Array(l),b=0;(function n(i,o,s,l,c,u){var f=.5*s;var h=l+1;var d=c-l;r[b]=d;y[b++]=u;for(var p=0;p<2;++p)for(var m=0;m<2;++m){var v=i+p*f,g=o+m*f,x=a(t,e,h,c,v,g,v+f,g+f);if(x!==h){if(x-h>=Math.max(.9*d,32)){var _=c+l>>>1;n(v,g,f,h,_,u+1),h=_}n(v,g,f,h,x,u+1),h=x}}})(f,h,g,0,l,0),n(y,t,e,r,l);for(var x=[],_=0,w=l,b=l-1;b>=0;--b){t[2*b]=(t[2*b]-f)*m,t[2*b+1]=(t[2*b+1]-h)*v;var M=y[b];M!==_&&(x.push(new o(g*Math.pow(.5,M),b+1,w-(b+1))),w=b+1,_=M)}return x.push(new o(g*Math.pow(.5,M+1),0,w)),x}},{"./lib/sort":513,"array-bounds":48}],515:[function(t,e,r){"use strict";var n=t("robust-dot-product"),i=t("robust-sum");function a(t,e){var r=i(n(t,e),[e[e.length-1]]);return r[r.length-1]}function o(t,e,r,n){var i=-e/(n-e);i<0?i=0:i>1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l0||i>0&&u<0){var f=o(s,u,l,i);r.push(f),n.push(f.slice())}u<0?n.push(l.slice()):u>0?r.push(l.slice()):(r.push(l.slice()),n.push(l.slice())),i=u}return{positive:r,negative:n}},e.exports.positive=function(t,e){for(var r=[],n=a(t[t.length-1],e),i=t[t.length-1],s=t[0],l=0;l0||n>0&&c<0)&&r.push(o(i,c,s,n)),c>=0&&r.push(s.slice()),n=c}return r},e.exports.negative=function(t,e){for(var r=[],n=a(t[t.length-1],e),i=t[t.length-1],s=t[0],l=0;l0||n>0&&c<0)&&r.push(o(i,c,s,n)),c<=0&&r.push(s.slice()),n=c}return r}},{"robust-dot-product":492,"robust-sum":500}],516:[function(t,e,r){!function(){"use strict";var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};function e(r){return function(r,n){var i,a,o,s,l,c,u,f,h,d=1,p=r.length,m="";for(a=0;a=0),s[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s[6]?parseInt(s[6]):0);break;case"e":i=s[7]?parseFloat(i).toExponential(s[7]):parseFloat(i).toExponential();break;case"f":i=s[7]?parseFloat(i).toFixed(s[7]):parseFloat(i);break;case"g":i=s[7]?String(Number(i.toPrecision(s[7]))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s[7]?i.substring(0,s[7]):i;break;case"t":i=String(!!i),i=s[7]?i.substring(0,s[7]):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s[7]?i.substring(0,s[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s[7]?i.substring(0,s[7]):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s[8])?m+=i:(!t.number.test(s[8])||f&&!s[3]?h="":(h=f?"+":"-",i=i.toString().replace(t.sign,"")),c=s[4]?"0"===s[4]?"0":s[4].charAt(1):" ",u=s[6]-(h+i).length,l=s[6]&&u>0?c.repeat(u):"",m+=s[5]?h+i+l:"0"===c?h+l+i:l+h+i)}return m}(function(e){if(i[e])return i[e];var r,n=e,a=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))a.push(r[0]);else if(null!==(r=t.modulo.exec(n)))a.push("%");else{if(null===(r=t.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],c=[];if(null===(c=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(c[1]);""!==(l=l.substring(c[0].length));)if(null!==(c=t.key_access.exec(l)))s.push(c[1]);else{if(null===(c=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(c[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push(r)}n=n.substring(r[0].length)}return i[e]=a}(r),arguments)}function n(t,r){return e.apply(null,[t].concat(r||[]))}var i=Object.create(null);void 0!==r&&(r.sprintf=e,r.vsprintf=n),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=n)}()},{}],517:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=new Array(e),a=new Array(e),o=new Array(e),s=new Array(e),l=0;l0;){e=c[c.length-1];var d=t[e];if(a[e]=0&&s[e].push(o[m])}a[e]=p}else{if(n[e]===r[e]){for(var v=[],g=[],y=0,p=l.length-1;p>=0;--p){var b=l[p];if(i[b]=!1,v.push(b),g.push(s[b]),y+=s[b].length,o[b]=f.length,b===e){l.length=p;break}}f.push(v);for(var x=new Array(y),p=0;p=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return f(f({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function c(t){return t/360+.5}function u(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function f(t,e){for(var r in e)t[r]=e[r];return t}function h(t){return t.x}function d(t){return t.y}e.exports=function(t){return new i(t)},i.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var i=t.map(o);e&&console.timeEnd(r);for(var a=this.options.maxZoom;a>=this.options.minZoom;a--){var s=+Date.now();this.trees[a+1]=n(i,h,d,this.options.nodeSize,Float32Array),i=this._cluster(i,a),e&&console.log("z%d: %d clusters in %dms",a,i.length,+Date.now()-s)}return this.trees[this.options.minZoom]=n(i,h,d,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(c(t[0]),u(t[3]),c(t[2]),u(t[1])),i=[],a=0;a c)|0 },"),"generic"===e&&a.push("getters:[0],");for(var s=[],l=[],c=0;c>>7){");for(var c=0;c<1<<(1<128&&c%128==0){f.length>0&&h.push("}}");var d="vExtra"+f.length;a.push("case ",c>>>7,":",d,"(m&0x7f,",l.join(),");break;"),h=["function ",d,"(m,",l.join(),"){switch(m){"],f.push(h)}h.push("case ",127&c,":");for(var p=new Array(r),m=new Array(r),v=new Array(r),g=new Array(r),y=0,b=0;bb)&&!(c&1<<_)!=!(c&1<0&&(A="+"+v[x]+"*c");var T=p[x].length/y*.5,E=.5+g[x]/y*.5;k.push("d"+x+"-"+E+"-"+T+"*("+p[x].join("+")+A+")/("+m[x].join("+")+")")}h.push("a.push([",k.join(),"]);","break;")}a.push("}},"),f.length>0&&h.push("}}");for(var S=[],c=0;c<1<1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)};r.default=function(t){var e=t.px,r=t.py,l=t.cx,c=t.cy,u=t.rx,f=t.ry,h=t.xAxisRotation,d=void 0===h?0:h,p=t.largeArcFlag,m=void 0===p?0:p,v=t.sweepFlag,g=void 0===v?0:v,y=[];if(0===u||0===f)return[];var b=Math.sin(d*i/360),x=Math.cos(d*i/360),_=x*(e-l)/2+b*(r-c)/2,w=-b*(e-l)/2+x*(r-c)/2;if(0===_&&0===w)return[];u=Math.abs(u),f=Math.abs(f);var M=Math.pow(_,2)/Math.pow(u,2)+Math.pow(w,2)/Math.pow(f,2);M>1&&(u*=Math.sqrt(M),f*=Math.sqrt(M));var k=function(t,e,r,n,a,o,l,c,u,f,h,d){var p=Math.pow(a,2),m=Math.pow(o,2),v=Math.pow(h,2),g=Math.pow(d,2),y=p*m-p*g-m*v;y<0&&(y=0),y/=p*g+m*v;var b=(y=Math.sqrt(y)*(l===c?-1:1))*a/o*d,x=y*-o/a*h,_=f*b-u*x+(t+r)/2,w=u*b+f*x+(e+n)/2,M=(h-b)/a,k=(d-x)/o,A=(-h-b)/a,T=(-d-x)/o,E=s(1,0,M,k),S=s(M,k,A,T);return 0===c&&S>0&&(S-=i),1===c&&S<0&&(S+=i),[_,w,E,S]}(e,r,l,c,u,f,m,g,b,x,_,w),A=n(k,4),T=A[0],E=A[1],S=A[2],L=A[3],C=Math.max(Math.ceil(Math.abs(L)/(i/4)),1);L/=C;for(var P=0;Pe[2]&&(e[2]=c[u+0]),c[u+1]>e[3]&&(e[3]=c[u+1]);return e}},{"abs-svg-path":43,assert:51,"is-svg-path":267,"normalize-svg-path":523,"parse-svg-path":447}],523:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=[],o=0,s=0,l=0,c=0,u=null,f=null,h=0,d=0,p=0,m=t.length;p4?(o=v[v.length-4],s=v[v.length-3]):(o=h,s=d),r.push(v)}return r};var n=t("svg-arc-to-cubic-bezier");function i(t,e,r,n){return["C",t,e,r,n,r,n]}function a(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}},{"svg-arc-to-cubic-bezier":521}],524:[function(t,e,r){(function(r){"use strict";var n=t("svg-path-bounds"),i=t("parse-svg-path"),a=t("draw-svg-path"),o=t("is-svg-path"),s=t("bitmap-sdf"),l=document.createElement("canvas"),c=l.getContext("2d");e.exports=function(t,e){if(!o(t))throw Error("Argument should be valid svg path string");e||(e={});var u,f;e.shape?(u=e.shape[0],f=e.shape[1]):(u=l.width=e.w||e.width||200,f=l.height=e.h||e.height||200);var h=Math.min(u,f),d=e.stroke||0,p=e.viewbox||e.viewBox||n(t),m=[u/(p[2]-p[0]),f/(p[3]-p[1])],v=Math.min(m[0]||0,m[1]||0)/2;c.fillStyle="black",c.fillRect(0,0,u,f),c.fillStyle="white",d&&("number"!=typeof d&&(d=1),c.strokeStyle=d>0?"white":"black",c.lineWidth=Math.abs(d));if(c.translate(.5*u,.5*f),c.scale(v,v),r.Path2D){var g=new Path2D(t);c.fill(g),d&&c.stroke(g)}else{var y=i(t);a(c,y),c.fill(),d&&c.stroke()}return c.setTransform(1,0,0,1,0,0),s(c,{cutoff:null!=e.cutoff?e.cutoff:.5,radius:null!=e.radius?e.radius:.5*h})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"bitmap-sdf":72,"draw-svg-path":132,"is-svg-path":267,"parse-svg-path":447,"svg-path-bounds":522}],525:[function(t,e,r){(function(r){"use strict";e.exports=function t(e,r,i){var i=i||{};var o=a[e];o||(o=a[e]={" ":{data:new Float32Array(0),shape:.2}});var s=o[r];if(!s)if(r.length<=1||!/\d/.test(r))s=o[r]=function(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;o0&&(f+=.02);for(var d=new Float32Array(u),p=0,m=-.5*f,h=0;h1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=C(t,360),e=C(e,100),r=C(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(e.h,l,u),f=!0,h="hsl"),e.hasOwnProperty("a")&&(a=e.a));var d,p,m;return a=L(a),{ok:f,format:e.format||h,r:o(255,s(i.r,0)),g:o(255,s(i.g,0)),b:o(255,s(i.b,0)),a:a}}(e);this._originalInput=e,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=l.format||u.format,this._gradientType=l.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=i++}function u(t,e,r){t=C(t,255),e=C(e,255),r=C(r,255);var n,i,a=s(t,e,r),l=o(t,e,r),c=(a+l)/2;if(a==l)n=i=0;else{var u=a-l;switch(i=c>.5?u/(2-a-l):u/(a+l),a){case t:n=(e-r)/u+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(c(n));return a}function T(t,e){e=e||6;for(var r=c(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(c({h:n,s:i,v:a})),a=(a+s)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=L(t),this._roundA=a(100*this._a)/100,this},toHsv:function(){var t=f(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=f(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return h(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[O(a(t).toString(16)),O(a(e).toString(16)),O(a(r).toString(16)),O(I(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*C(this._r,255))+"%",g:a(100*C(this._g,255))+"%",b:a(100*C(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*C(this._r,255))+"%, "+a(100*C(this._g,255))+"%, "+a(100*C(this._b,255))+"%)":"rgba("+a(100*C(this._r,255))+"%, "+a(100*C(this._g,255))+"%, "+a(100*C(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(S[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+d(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=c(t);r="#"+d(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(g,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(b,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(m,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(x,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(k,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(M,arguments)}},c.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:D(t[n]));t=r}return c(t,e)},c.equals=function(t,e){return!(!t||!e)&&c(t).toRgbString()==c(e).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(t,e,r){r=0===r?0:r||50;var n=c(t).toRgb(),i=c(e).toRgb(),a=r/100;return c({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},c.readability=function(e,r){var n=c(e),i=c(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},c.isReadable=function(t,e,r){var n,i,a=c.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},c.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var u=0;ul&&(l=n,s=c(e[u]));return c.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,c.mostReadable(t,["#fff","#000"],r))};var E=c.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},S=c.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(E);function L(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function C(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=o(r,s(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return o(1,s(0,t))}function z(t){return parseInt(t,16)}function O(t){return 1==t.length?"0"+t:""+t}function D(t){return t<=1&&(t=100*t+"%"),t}function I(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return z(t)/255}var N,F,j,B=(F="[\\s|\\(]+("+(N="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+N+")[,|\\s]+("+N+")\\s*\\)?",j="[\\s|\\(]+("+N+")[,|\\s]+("+N+")[,|\\s]+("+N+")[,|\\s]+("+N+")\\s*\\)?",{CSS_UNIT:new RegExp(N),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function U(t){return!!B.CSS_UNIT.exec(t)}void 0!==e&&e.exports?e.exports=c:window.tinycolor=c}(Math)},{}],527:[function(t,e,r){"use strict";function n(t){if(t instanceof Float32Array)return t;if("number"==typeof t)return new Float32Array([t])[0];var e=new Float32Array(t);return e.set(t),e}e.exports=n,e.exports.float32=e.exports.float=n,e.exports.fract32=e.exports.fract=function(t){if("number"==typeof t)return n(t-n(t));for(var e=n(t),r=0,i=e.length;rf&&(f=l[0]),l[1]h&&(h=l[1])}function i(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(i);break;case"Point":n(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(n)}}if(!e){var a,o,s=r(t),l=new Array(2),c=1/0,u=c,f=-c,h=-c;for(o in t.arcs.forEach(function(t){for(var e=-1,r=t.length;++ef&&(f=l[0]),l[1]h&&(h=l[1])}),t.objects)i(t.objects[o]);e=t.bbox=[c,u,f,h]}return e},i=function(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r};function a(t,e){var r=e.id,n=e.bbox,i=null==e.properties?{}:e.properties,a=o(t,e);return null==r&&null==n?{type:"Feature",properties:i,geometry:a}:null==n?{type:"Feature",id:r,properties:i,geometry:a}:{type:"Feature",id:r,bbox:n,properties:i,geometry:a}}function o(t,e){var n=r(t),a=t.arcs;function o(t,e){e.length&&e.pop();for(var r=a[t<0?~t:t],o=0,s=r.length;o1)n=function(t,e,r){var n,i=[],a=[];function o(t){var e=t<0?~t:t;(a[e]||(a[e]=[])).push({i:t,g:n})}function s(t){t.forEach(o)}function l(t){t.forEach(s)}return function t(e){switch(n=e,e.type){case"GeometryCollection":e.geometries.forEach(t);break;case"LineString":s(e.arcs);break;case"MultiLineString":case"Polygon":l(e.arcs);break;case"MultiPolygon":e.arcs.forEach(l)}}(e),a.forEach(null==r?function(t){i.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&i.push(t[0].i)}),i}(0,e,r);else for(i=0,n=new Array(a=t.arcs.length);i1)for(var a,o,c=1,u=l(i[0]);cu&&(o=i[0],i[0]=i[c],i[c]=o,u=a);return i})}}var u=function(t,e){for(var r=0,n=t.length;r>>1;t[i]=2))throw new Error("n must be \u22652");if(t.transform)throw new Error("already quantized");var r,i=n(t),a=i[0],o=(i[2]-a)/(e-1)||1,s=i[1],l=(i[3]-s)/(e-1)||1;function c(t){t[0]=Math.round((t[0]-a)/o),t[1]=Math.round((t[1]-s)/l)}function u(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(u);break;case"Point":c(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(c)}}for(r in t.arcs.forEach(function(t){for(var e,r,n,i=1,c=1,u=t.length,f=t[0],h=f[0]=Math.round((f[0]-a)/o),d=f[1]=Math.round((f[1]-s)/l);iMath.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,l=0;l<3;++l)a+=t[l]*t[l],o+=i[l]*t[l];for(l=0;l<3;++l)i[l]-=o/a*t[l];return s(i,i),i}function h(t,e,r,i,a,o,s,l){this.center=n(r),this.up=n(i),this.right=n(a),this.radius=n([o]),this.angle=n([s,l]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var c=0;c<16;++c)this.computedMatrix[c]=.5;this.recalcMatrix(0)}var d=h.prototype;d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var l=Math.sqrt(n),u=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,u+=r[a]*r[a],e[a]/=l;var f=Math.sqrt(u);for(a=0;a<3;++a)r[a]/=f;var h=this.computedToward;o(h,e,r),s(h,h);var d=Math.exp(this.computedRadius[0]),p=this.computedAngle[0],m=this.computedAngle[1],v=Math.cos(p),g=Math.sin(p),y=Math.cos(m),b=Math.sin(m),x=this.computedCenter,_=v*y,w=g*y,M=b,k=-v*b,A=-g*b,T=y,E=this.computedEye,S=this.computedMatrix;for(a=0;a<3;++a){var L=_*r[a]+w*h[a]+M*e[a];S[4*a+1]=k*r[a]+A*h[a]+T*e[a],S[4*a+2]=L,S[4*a+3]=0}var C=S[1],P=S[5],z=S[9],O=S[2],D=S[6],I=S[10],R=P*I-z*D,N=z*O-C*I,F=C*D-P*O,j=c(R,N,F);R/=j,N/=j,F/=j,S[0]=R,S[4]=N,S[8]=F;for(a=0;a<3;++a)E[a]=x[a]+S[2+4*a]*d;for(a=0;a<3;++a){u=0;for(var B=0;B<3;++B)u+=S[a+4*B]*E[B];S[12+a]=-u}S[15]=1},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var p=[0,0,0];d.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;p[0]=i[2],p[1]=i[6],p[2]=i[10];for(var o=this.computedUp,s=this.computedRight,l=this.computedToward,c=0;c<3;++c)i[4*c]=o[c],i[4*c+1]=s[c],i[4*c+2]=l[c];a(i,i,n,p);for(c=0;c<3;++c)o[c]=i[4*c],s[c]=i[4*c+1];this.up.set(t,o[0],o[1],o[2]),this.right.set(t,s[0],s[1],s[2])}},d.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=c(a,o,s);a/=l,o/=l,s/=l;var u=i[0],f=i[4],h=i[8],d=u*a+f*o+h*s,p=c(u-=a*d,f-=o*d,h-=s*d),m=(u/=p)*e+a*r,v=(f/=p)*e+o*r,g=(h/=p)*e+s*r;this.center.move(t,m,v,g);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+n),this.radius.set(t,Math.log(y))},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e,r,n){var a=1;"number"==typeof r&&(a=0|r),(a<0||a>3)&&(a=1);var o=(a+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var s=e[a],l=e[a+4],f=e[a+8];if(n){var h=Math.abs(s),d=Math.abs(l),p=Math.abs(f),m=Math.max(h,d,p);h===m?(s=s<0?-1:1,l=f=0):p===m?(f=f<0?-1:1,s=l=0):(l=l<0?-1:1,s=f=0)}else{var v=c(s,l,f);s/=v,l/=v,f/=v}var g,y,b=e[o],x=e[o+4],_=e[o+8],w=b*s+x*l+_*f,M=c(b-=s*w,x-=l*w,_-=f*w),k=l*(_/=M)-f*(x/=M),A=f*(b/=M)-s*_,T=s*x-l*b,E=c(k,A,T);if(k/=E,A/=E,T/=E,this.center.jump(t,H,G,Y),this.radius.idle(t),this.up.jump(t,s,l,f),this.right.jump(t,b,x,_),2===a){var S=e[1],L=e[5],C=e[9],P=S*b+L*x+C*_,z=S*k+L*A+C*T;g=R<0?-Math.PI/2:Math.PI/2,y=Math.atan2(z,P)}else{var O=e[2],D=e[6],I=e[10],R=O*s+D*l+I*f,N=O*b+D*x+I*_,F=O*k+D*A+I*T;g=Math.asin(u(R)),y=Math.atan2(F,N)}this.angle.jump(t,y,g),this.recalcMatrix(t);var j=e[2],B=e[6],U=e[10],V=this.computedMatrix;i(V,e);var q=V[15],H=V[12]/q,G=V[13]/q,Y=V[14]/q,W=Math.exp(this.computedRadius[0]);this.center.jump(t,H-j*W,G-B*W,Y-U*W)},d.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},d.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},d.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=c(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],f=e[1]-r[1],h=e[2]-r[2],d=c(l,f,h);if(!(d<1e-6)){l/=d,f/=d,h/=d;var p=this.computedRight,m=p[0],v=p[1],g=p[2],y=i*m+a*v+o*g,b=c(m-=y*i,v-=y*a,g-=y*o);if(!(b<.01&&(b=c(m=a*h-o*f,v=o*l-i*h,g=i*f-a*l))<1e-6)){m/=b,v/=b,g/=b,this.up.set(t,i,a,o),this.right.set(t,m,v,g),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(d));var x=a*g-o*v,_=o*m-i*g,w=i*v-a*m,M=c(x,_,w),k=i*l+a*f+o*h,A=m*l+v*f+g*h,T=(x/=M)*l+(_/=M)*f+(w/=M)*h,E=Math.asin(u(k)),S=Math.atan2(T,A),L=this.angle._state,C=L[L.length-1],P=L[L.length-2];C%=2*Math.PI;var z=Math.abs(C+2*Math.PI-S),O=Math.abs(C-S),D=Math.abs(C-2*Math.PI-S);z0?r.pop():new ArrayBuffer(t)}function h(t){return new Uint8Array(f(t),0,t)}function d(t){return new Uint16Array(f(2*t),0,t)}function p(t){return new Uint32Array(f(4*t),0,t)}function m(t){return new Int8Array(f(t),0,t)}function v(t){return new Int16Array(f(2*t),0,t)}function g(t){return new Int32Array(f(4*t),0,t)}function y(t){return new Float32Array(f(4*t),0,t)}function b(t){return new Float64Array(f(8*t),0,t)}function x(t){return o?new Uint8ClampedArray(f(t),0,t):h(t)}function _(t){return new DataView(f(t),0,t)}function w(t){t=i.nextPow2(t);var e=i.log2(t),r=c[e];return r.length>0?r.pop():new n(t)}r.free=function(t){if(n.isBuffer(t))c[i.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|i.log2(e);l[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=function(t){u(t.buffer)},r.freeArrayBuffer=u,r.freeBuffer=function(t){c[i.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return f(t);switch(e){case"uint8":return h(t);case"uint16":return d(t);case"uint32":return p(t);case"int8":return m(t);case"int16":return v(t);case"int32":return g(t);case"float":case"float32":return y(t);case"double":case"float64":return b(t);case"uint8_clamped":return x(t);case"buffer":return w(t);case"data":case"dataview":return _(t);default:return null}return null},r.mallocArrayBuffer=f,r.mallocUint8=h,r.mallocUint16=d,r.mallocUint32=p,r.mallocInt8=m,r.mallocInt16=v,r.mallocInt32=g,r.mallocFloat32=r.mallocFloat=y,r.mallocFloat64=r.mallocDouble=b,r.mallocUint8Clamped=x,r.mallocDataView=_,r.mallocBuffer=w,r.clearCache=function(){for(var t=0;t<32;++t)s.UINT8[t].length=0,s.UINT16[t].length=0,s.UINT32[t].length=0,s.INT8[t].length=0,s.INT16[t].length=0,s.INT32[t].length=0,s.FLOAT[t].length=0,s.DOUBLE[t].length=0,s.UINT8C[t].length=0,l[t].length=0,c[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":71,buffer:83,dup:134}],535:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;en)return n;for(;ra?r=i:n=i,i=.5*(n-r)+r}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},{}],538:[function(t,e,r){"use strict";e.exports=function(t,e,r){Array.isArray(r)||(r=[].slice.call(arguments,2));for(var n=0,i=r.length;n",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(c),f=["%","/","?",";","#"].concat(u),h=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=t("querystring");function b(t,e,r){if(t&&i.isObject(t)&&t instanceof a)return t;var n=new a;return n.parse(t,e,r),n}a.prototype.parse=function(t,e,r){if(!i.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var a=t.indexOf("?"),s=-1!==a&&a127?O+="x":O+=z[D];if(!O.match(d)){var R=C.slice(0,E),N=C.slice(E+1),F=z.match(p);F&&(R.push(F[1]),N.unshift(F[2])),N.length&&(b="/"+N.join(".")+b),this.hostname=R.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),L||(this.hostname=n.toASCII(this.hostname));var j=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+j,this.href+=this.host,L&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b))}if(!m[w])for(E=0,P=u.length;E0)&&r.host.split("@"))&&(r.auth=L.shift(),r.host=r.hostname=L.shift());return r.search=t.search,r.query=t.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!M.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var A=M.slice(-1)[0],T=(r.host||t.host||M.length>1)&&("."===A||".."===A)||""===A,E=0,S=M.length;S>=0;S--)"."===(A=M[S])?M.splice(S,1):".."===A?(M.splice(S,1),E++):E&&(M.splice(S,1),E--);if(!_&&!w)for(;E--;E)M.unshift("..");!_||""===M[0]||M[0]&&"/"===M[0].charAt(0)||M.unshift(""),T&&"/"!==M.join("/").substr(-1)&&M.push("");var L,C=""===M[0]||M[0]&&"/"===M[0].charAt(0);k&&(r.hostname=r.host=C?"":M.length?M.shift():"",(L=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=L.shift(),r.host=r.hostname=L.shift()));return(_=_||r.host&&M.length)&&!C&&M.unshift(""),M.length?r.pathname=M.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},a.prototype.parseHost=function(){var t=this.host,e=s.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":540,punycode:470,querystring:474}],540:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],541:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],542:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],543:[function(t,e,r){(function(e,n){var i=/%[sdj%]/g;r.format=function(t){if(!g(t)){for(var e=[],r=0;r=a)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),l=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(e)?n.showHidden=e:e&&r._extend(n,e),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=l),u(n,t,n.depth)}function l(t,e){var r=s.styles[e];return r?"\x1b["+s.colors[r][0]+"m"+t+"\x1b["+s.colors[r][1]+"m":t}function c(t,e){return t}function u(t,e,n){if(t.customInspect&&e&&M(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return g(i)||(i=u(t,i,n)),i}var a=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(v(e))return t.stylize(""+e,"number");if(p(e))return t.stylize(""+e,"boolean");if(m(e))return t.stylize("null","null")}(t,e);if(a)return a;var o=Object.keys(e),s=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),w(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return f(e);if(0===o.length){if(M(e)){var l=e.name?": "+e.name:"";return t.stylize("[Function"+l+"]","special")}if(b(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_(e))return t.stylize(Date.prototype.toString.call(e),"date");if(w(e))return f(e)}var c,x="",k=!1,A=["{","}"];(d(e)&&(k=!0,A=["[","]"]),M(e))&&(x=" [Function"+(e.name?": "+e.name:"")+"]");return b(e)&&(x=" "+RegExp.prototype.toString.call(e)),_(e)&&(x=" "+Date.prototype.toUTCString.call(e)),w(e)&&(x=" "+f(e)),0!==o.length||k&&0!=e.length?n<0?b(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),c=k?function(t,e,r,n,i){for(var a=[],o=0,s=e.length;o=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(c,x,A)):A[0]+x+A[1]}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function h(t,e,r,n,i,a){var o,s,l;if((l=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),E(n,i)||(o="["+i+"]"),s||(t.seen.indexOf(l.value)<0?(s=m(r)?u(t,l.value,null):u(t,l.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n")):s=t.stylize("[Circular]","special")),y(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function d(t){return Array.isArray(t)}function p(t){return"boolean"==typeof t}function m(t){return null===t}function v(t){return"number"==typeof t}function g(t){return"string"==typeof t}function y(t){return void 0===t}function b(t){return x(t)&&"[object RegExp]"===k(t)}function x(t){return"object"==typeof t&&null!==t}function _(t){return x(t)&&"[object Date]"===k(t)}function w(t){return x(t)&&("[object Error]"===k(t)||t instanceof Error)}function M(t){return"function"==typeof t}function k(t){return Object.prototype.toString.call(t)}function A(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(y(a)&&(a=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!o[t])if(new RegExp("\\b"+t+"\\b","i").test(a)){var n=e.pid;o[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else o[t]=function(){};return o[t]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=m,r.isNullOrUndefined=function(t){return null==t},r.isNumber=v,r.isString=g,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=y,r.isRegExp=b,r.isObject=x,r.isDate=_,r.isError=w,r.isFunction=M,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t("./support/isBuffer");var T=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function E(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[A(t.getHours()),A(t.getMinutes()),A(t.getSeconds())].join(":"),[t.getDate(),T[t.getMonth()],e].join(" ")),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":542,_process:469,inherits:541}],544:[function(t,e,r){e.exports.VectorTile=t("./lib/vectortile.js"),e.exports.VectorTileFeature=t("./lib/vectortilefeature.js"),e.exports.VectorTileLayer=t("./lib/vectortilelayer.js")},{"./lib/vectortile.js":545,"./lib/vectortilefeature.js":546,"./lib/vectortilelayer.js":547}],545:[function(t,e,r){"use strict";var n=t("./vectortilelayer");function i(t,e,r){if(3===t){var i=new n(r,r.readVarint()+r.pos);i.length&&(e[i.name]=i)}}e.exports=function(t,e){this.layers=t.readFields(i,{},e)}},{"./vectortilelayer":547}],546:[function(t,e,r){"use strict";var n=t("point-geometry");function i(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(a,this,e)}function a(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){var r=t.readVarint()+t.pos;for(;t.pos>3}if(a--,1===i||2===i)o+=t.readSVarint(),s+=t.readSVarint(),1===i&&(e&&l.push(e),e=[]),e.push(new n(o,s));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&l.push(e),l},i.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,l=1/0,c=-1/0;t.pos>3}if(n--,1===r||2===r)i+=t.readSVarint(),a+=t.readSVarint(),is&&(s=i),ac&&(c=a);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,s,c]},i.prototype.toGeoJSON=function(t,e,r){var n,a,s=this.extent*Math.pow(2,r),l=this.extent*t,c=this.extent*e,u=this.loadGeometry(),f=i.types[this.type];function h(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new n(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":546}],548:[function(t,e,r){"use strict";e.exports=function(t,e){"object"==typeof e&&null!==e||(e={});return n(t,e.canvas||i,e.context||a,e)};var n=t("./lib/vtext"),i=null,a=null;"undefined"!=typeof document&&((i=document.createElement("canvas")).width=8192,i.height=1024,a=i.getContext("2d"))},{"./lib/vtext":549}],549:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var a=n.size||64,o=n.font||"normal";return r.font=a+"px "+o,r.textAlign="start",r.textBaseline="alphabetic",r.direction="ltr",f(function(t,e,r,n){var a=0|Math.ceil(e.measureText(r).width+2*n);if(a>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var o=3*n;t.height>31}function u(t){for(var e=[],r=0,n=0,i=t.length,a=0;a=0?e[a]:i})},has___:{value:b(function(e){var n=y(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:b(function(n,i){var a,o=y(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:b(function(n){var i,a,o=y(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};m.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof r?function(){function n(){this instanceof m||x();var e,n=new r,i=void 0,a=!1;return e=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new m),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new m),i.set___(t,e)}else n.set(t,e);return this},Object.create(m.prototype,{get___:{value:b(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:b(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:b(e)},delete___:{value:b(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:b(function(t){if(t!==v)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),n.prototype=m.prototype,e.exports=n,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=m)}function v(t){t.permitHostObjects___&&t.permitHostObjects___(v)}function g(t){return!(t.substr(0,l.length)==l&&"___"===t.substr(t.length-3))}function y(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[c];if(e&&e.key===t)return e;if(s(t)){e={key:t};try{return o(t,c,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function b(t){return t.prototype=null,Object.freeze(t)}function x(){d||"undefined"==typeof console||(d=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}()},{}],554:[function(t,e,r){var n=t("./hidden-store.js");e.exports=function(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:n(e,t)}}},{"./hidden-store.js":555}],555:[function(t,e,r){e.exports=function(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}},{}],556:[function(t,e,r){var n=t("./create-store.js");e.exports=function(){var t=n();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){return t(e).value=r,this},has:function(e){return"value"in t(e)},delete:function(e){return delete t(e).value}}}},{"./create-store.js":554}],557:[function(t,e,r){var n=t("get-canvas-context");e.exports=function(t){return n("webgl",t)}},{"get-canvas-context":156}],558:[function(t,e,r){var n=arguments[3],i=arguments[4],a=arguments[5],o=JSON.stringify;e.exports=function(t,e){for(var r,s=Object.keys(a),l=0,c=s.length;l2111)throw e.replace(/\{0\}/,this.local.name);return t},toMonthIndex:function(t,e,r){var i=this.intercalaryMonth(t);if(r&&e!==i||e<1||e>12)throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return i?!r&&e<=i?e-1:e:e-1},toChineseMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);if(e<0||e>(r?12:11))throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return r?e>13},isIntercalaryMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);return!!r&&r===e},leapYear:function(t){return 0!==this.intercalaryMonth(t)},weekOfYear:function(t,e,r){var i,o=this._validateYear(t,n.local.invalidyear),s=h[o-h[0]],l=s>>9&4095,c=s>>5&15,u=31&s;(i=a.newDate(l,c,u)).add(4-(i.dayOfWeek()||7),"d");var f=this.toJD(t,e,r)-i.toJD();return 1+Math.floor(f/7)},monthsInYear:function(t){return this.leapYear(t)?13:12},daysInMonth:function(t,e){t.year&&(e=t.month(),t=t.year()),t=this._validateYear(t);var r=f[t-f[0]];if(e>(r>>13?12:11))throw n.local.invalidMonth.replace(/\{0\}/,this.local.name);return r&1<<12-e?30:29},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,s,r,n.local.invalidDate);t=this._validateYear(i.year()),e=i.month(),r=i.day();var o=this.isIntercalaryMonth(t,e),s=this.toChineseMonth(t,e),l=function(t,e,r,n,i){var a,o,s;if("object"==typeof t)o=t,a=e||{};else{var l="number"==typeof t&&t>=1888&&t<=2111;if(!l)throw new Error("Lunar year outside range 1888-2111");var c="number"==typeof e&&e>=1&&e<=12;if(!c)throw new Error("Lunar month outside range 1 - 12");var u,d="number"==typeof r&&r>=1&&r<=30;if(!d)throw new Error("Lunar day outside range 1 - 30");"object"==typeof n?(u=!1,a=n):(u=!!n,a=i||{}),o={year:t,month:e,day:r,isIntercalary:u}}s=o.day-1;var p,m=f[o.year-f[0]],v=m>>13;p=v?o.month>v?o.month:o.isIntercalary?o.month:o.month-1:o.month-1;for(var g=0;g>9&4095,(b>>5&15)-1,(31&b)+s);return a.year=x.getFullYear(),a.month=1+x.getMonth(),a.day=x.getDate(),a}(t,s,r,o);return a.toJD(l.year,l.month,l.day)},fromJD:function(t){var e=a.fromJD(t),r=function(t,e,r,n){var i,a;if("object"==typeof t)i=t,a=e||{};else{var o="number"==typeof t&&t>=1888&&t<=2111;if(!o)throw new Error("Solar year outside range 1888-2111");var s="number"==typeof e&&e>=1&&e<=12;if(!s)throw new Error("Solar month outside range 1 - 12");var l="number"==typeof r&&r>=1&&r<=31;if(!l)throw new Error("Solar day outside range 1 - 31");i={year:t,month:e,day:r},a=n||{}}var c=h[i.year-h[0]],u=i.year<<9|i.month<<5|i.day;a.year=u>=c?i.year:i.year-1,c=h[a.year-h[0]];var d,p=new Date(c>>9&4095,(c>>5&15)-1,31&c),m=new Date(i.year,i.month-1,i.day);d=Math.round((m-p)/864e5);var v,g=f[a.year-f[0]];for(v=0;v<13;v++){var y=g&1<<12-v?30:29;if(d>13;!b||v=2&&n<=6},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return{century:o[Math.floor((i.year()-1)/100)+1]||""}},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year()+(i.year()<0?1:0),e=i.month(),(r=i.day())+(e>1?16:0)+(e>2?32*(e-2):0)+400*(t-1)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t+.5)-Math.floor(this.jdEpoch)-1;var e=Math.floor(t/400)+1;t-=400*(e-1),t+=t>15?16:0;var r=Math.floor(t/32)+1,n=t-32*(r-1)+1;return this.newDate(e<=0?e-1:e,r,n)}});var o={20:"Fruitbat",21:"Anchovy"};n.calendars.discworld=a},{"../main":575,"object-assign":443}],564:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Ethiopian",jdEpoch:1724220.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Ethiopian",epochs:["BEE","EE"],monthNames:["Meskerem","Tikemet","Hidar","Tahesas","Tir","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehase","Pagume"],monthNamesShort:["Mes","Tik","Hid","Tah","Tir","Yek","Meg","Mia","Gen","Sen","Ham","Neh","Pag"],dayNames:["Ehud","Segno","Maksegno","Irob","Hamus","Arb","Kidame"],dayNamesShort:["Ehu","Seg","Mak","Iro","Ham","Arb","Kid"],dayNamesMin:["Eh","Se","Ma","Ir","Ha","Ar","Ki"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==3||t%4==-1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear||n.regionalOptions[""].invalidYear),13},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(13===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return(t=i.year())<0&&t++,i.day()+30*(i.month()-1)+365*(t-1)+Math.floor(t/4)+this.jdEpoch-1},fromJD:function(t){var e=Math.floor(t)+.5-this.jdEpoch,r=Math.floor((e-Math.floor((e+366)/1461))/365)+1;r<=0&&r--,e=Math.floor(t)+.5-this.newDate(r,1,1).toJD();var n=Math.floor(e/30)+1,i=e-30*(n-1)+1;return this.newDate(r,n,i)}}),n.calendars.ethiopian=a},{"../main":575,"object-assign":443}],565:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function o(t,e){return t-e*Math.floor(t/e)}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Hebrew",jdEpoch:347995.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29,29],hasYearZero:!1,minMonth:1,firstMonth:7,minDay:1,regionalOptions:{"":{name:"Hebrew",epochs:["BAM","AM"],monthNames:["Nisan","Iyar","Sivan","Tammuz","Av","Elul","Tishrei","Cheshvan","Kislev","Tevet","Shevat","Adar","Adar II"],monthNamesShort:["Nis","Iya","Siv","Tam","Av","Elu","Tis","Che","Kis","Tev","She","Ada","Ad2"],dayNames:["Yom Rishon","Yom Sheni","Yom Shlishi","Yom Revi'i","Yom Chamishi","Yom Shishi","Yom Shabbat"],dayNamesShort:["Ris","She","Shl","Rev","Cha","Shi","Sha"],dayNamesMin:["Ri","She","Shl","Re","Ch","Shi","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return this._leapYear(e.year())},_leapYear:function(t){return o(7*(t=t<0?t+1:t)+1,19)<7},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),this._leapYear(t.year?t.year():t)?13:12},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year(),this.toJD(-1===t?1:t+1,7,1)-this.toJD(t,7,1)},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,n.local.invalidMonth),12===e&&this.leapYear(t)?30:8===e&&5===o(this.daysInYear(t),10)?30:9===e&&3===o(this.daysInYear(t),10)?29:this.daysPerMonth[e-1]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return{yearType:(this.leapYear(i)?"embolismic":"common")+" "+["deficient","regular","complete"][this.daysInYear(i)%10-3]}},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=t<=0?t+1:t,o=this.jdEpoch+this._delay1(a)+this._delay2(a)+r+1;if(e<7){for(var s=7;s<=this.monthsInYear(t);s++)o+=this.daysInMonth(t,s);for(s=1;s=this.toJD(-1===e?1:e+1,7,1);)e++;for(var r=tthis.toJD(e,r,this.daysInMonth(e,r));)r++;var n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),n.calendars.hebrew=a},{"../main":575,"object-assign":443}],566:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Islamic",jdEpoch:1948439.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Islamic",epochs:["BH","AH"],monthNames:["Muharram","Safar","Rabi' al-awwal","Rabi' al-thani","Jumada al-awwal","Jumada al-thani","Rajab","Sha'aban","Ramadan","Shawwal","Dhu al-Qi'dah","Dhu al-Hijjah"],monthNamesShort:["Muh","Saf","Rab1","Rab2","Jum1","Jum2","Raj","Sha'","Ram","Shaw","DhuQ","DhuH"],dayNames:["Yawm al-ahad","Yawm al-ithnayn","Yawm ath-thulaathaa'","Yawm al-arbi'aa'","Yawm al-kham\u012bs","Yawm al-jum'a","Yawm as-sabt"],dayNamesShort:["Aha","Ith","Thu","Arb","Kha","Jum","Sab"],dayNamesMin:["Ah","It","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!1}},leapYear:function(t){return(11*this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year()+14)%30<11},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return this.leapYear(t)?355:354},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year(),e=i.month(),r=i.day(),t=t<=0?t+1:t,r+Math.ceil(29.5*(e-1))+354*(t-1)+Math.floor((3+11*t)/30)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t)+.5;var e=Math.floor((30*(t-this.jdEpoch)+10646)/10631);e=e<=0?e-1:e;var r=Math.min(12,Math.ceil((t-29-this.toJD(e,1,1))/29.5)+1),n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),n.calendars.islamic=a},{"../main":575,"object-assign":443}],567:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Julian",jdEpoch:1721423.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Julian",epochs:["BC","AD"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"mm/dd/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return(t=e.year()<0?e.year()+1:e.year())%4==0},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(4-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return t=i.year(),e=i.month(),r=i.day(),t<0&&t++,e<=2&&(t--,e+=12),Math.floor(365.25*(t+4716))+Math.floor(30.6001*(e+1))+r-1524.5},fromJD:function(t){var e=Math.floor(t+.5)+1524,r=Math.floor((e-122.1)/365.25),n=Math.floor(365.25*r),i=Math.floor((e-n)/30.6001),a=i-Math.floor(i<14?1:13),o=r-Math.floor(a>2?4716:4715),s=e-n-Math.floor(30.6001*i);return o<=0&&o--,this.newDate(o,a,s)}}),n.calendars.julian=a},{"../main":575,"object-assign":443}],568:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function o(t,e){return t-e*Math.floor(t/e)}function s(t,e){return o(t-1,e)+1}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Mayan",jdEpoch:584282.5,hasYearZero:!0,minMonth:0,firstMonth:0,minDay:0,regionalOptions:{"":{name:"Mayan",epochs:["",""],monthNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],monthNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],dayNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesMin:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],digits:null,dateFormat:"YYYY.m.d",firstDay:0,isRTL:!1,haabMonths:["Pop","Uo","Zip","Zotz","Tzec","Xul","Yaxkin","Mol","Chen","Yax","Zac","Ceh","Mac","Kankin","Muan","Pax","Kayab","Cumku","Uayeb"],tzolkinMonths:["Imix","Ik","Akbal","Kan","Chicchan","Cimi","Manik","Lamat","Muluc","Oc","Chuen","Eb","Ben","Ix","Men","Cib","Caban","Etznab","Cauac","Ahau"]}},leapYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),!1},formatYear:function(t){t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year();var e=Math.floor(t/400);return t%=400,t+=t<0?400:0,e+"."+Math.floor(t/20)+"."+t%20},forYear:function(t){if((t=t.split(".")).length<3)throw"Invalid Mayan year";for(var e=0,r=0;r19||r>0&&n<0)throw"Invalid Mayan year";e=20*e+n}return e},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),18},weekOfYear:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate),0},daysInYear:function(t){return this._validate(t,this.minMonth,this.minDay,n.local.invalidYear),360},daysInMonth:function(t,e){return this._validate(t,e,this.minDay,n.local.invalidMonth),20},daysInWeek:function(){return 5},dayOfWeek:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate).day()},weekDay:function(t,e,r){return this._validate(t,e,r,n.local.invalidDate),!0},extraInfo:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate).toJD(),a=this._toHaab(i),o=this._toTzolkin(i);return{haabMonthName:this.local.haabMonths[a[0]-1],haabMonth:a[0],haabDay:a[1],tzolkinDayName:this.local.tzolkinMonths[o[0]-1],tzolkinDay:o[0],tzolkinTrecena:o[1]}},_toHaab:function(t){var e=o((t-=this.jdEpoch)+8+340,365);return[Math.floor(e/20)+1,o(e,20)]},_toTzolkin:function(t){return[s((t-=this.jdEpoch)+20,20),s(t+4,13)]},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);return i.day()+20*i.month()+360*i.year()+this.jdEpoch},fromJD:function(t){t=Math.floor(t)+.5-this.jdEpoch;var e=Math.floor(t/360);t%=360,t+=t<0?360:0;var r=Math.floor(t/20),n=t%20;return this.newDate(e,r,n)}}),n.calendars.mayan=a},{"../main":575,"object-assign":443}],569:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar;var o=n.instance("gregorian");i(a.prototype,{name:"Nanakshahi",jdEpoch:2257673.5,daysPerMonth:[31,31,31,31,31,30,30,30,30,30,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Nanakshahi",epochs:["BN","AN"],monthNames:["Chet","Vaisakh","Jeth","Harh","Sawan","Bhadon","Assu","Katak","Maghar","Poh","Magh","Phagun"],monthNamesShort:["Che","Vai","Jet","Har","Saw","Bha","Ass","Kat","Mgr","Poh","Mgh","Pha"],dayNames:["Somvaar","Mangalvar","Budhvaar","Veervaar","Shukarvaar","Sanicharvaar","Etvaar"],dayNamesShort:["Som","Mangal","Budh","Veer","Shukar","Sanichar","Et"],dayNamesMin:["So","Ma","Bu","Ve","Sh","Sa","Et"],digits:null,dateFormat:"dd-mm-yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear||n.regionalOptions[""].invalidYear);return o.leapYear(e.year()+(e.year()<1?1:0)+1469)},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(1-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidMonth);(t=i.year())<0&&t++;for(var a=i.day(),s=1;s=this.toJD(e+1,1,1);)e++;for(var r=t-Math.floor(this.toJD(e,1,1)+.5)+1,n=1;r>this.daysInMonth(e,n);)r-=this.daysInMonth(e,n),n++;return this.newDate(e,n,r)}}),n.calendars.nanakshahi=a},{"../main":575,"object-assign":443}],570:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"Nepali",jdEpoch:1700709.5,daysPerMonth:[31,31,32,32,31,30,30,29,30,29,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,daysPerYear:365,regionalOptions:{"":{name:"Nepali",epochs:["BBS","ABS"],monthNames:["Baisakh","Jestha","Ashadh","Shrawan","Bhadra","Ashwin","Kartik","Mangsir","Paush","Mangh","Falgun","Chaitra"],monthNamesShort:["Bai","Je","As","Shra","Bha","Ash","Kar","Mang","Pau","Ma","Fal","Chai"],dayNames:["Aaitabaar","Sombaar","Manglbaar","Budhabaar","Bihibaar","Shukrabaar","Shanibaar"],dayNamesShort:["Aaita","Som","Mangl","Budha","Bihi","Shukra","Shani"],dayNamesMin:["Aai","So","Man","Bu","Bi","Shu","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:1,isRTL:!1}},leapYear:function(t){return this.daysInYear(t)!==this.daysPerYear},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){if(t=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear).year(),void 0===this.NEPALI_CALENDAR_DATA[t])return this.daysPerYear;for(var e=0,r=this.minMonth;r<=12;r++)e+=this.NEPALI_CALENDAR_DATA[t][r];return e},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,n.local.invalidMonth),void 0===this.NEPALI_CALENDAR_DATA[t]?this.daysPerMonth[e-1]:this.NEPALI_CALENDAR_DATA[t][e]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=n.instance(),o=0,s=e,l=t;this._createMissingCalendarData(t);var c=t-(s>9||9===s&&r>=this.NEPALI_CALENDAR_DATA[l][0]?56:57);for(9!==e&&(o=r,s--);9!==s;)s<=0&&(s=12,l--),o+=this.NEPALI_CALENDAR_DATA[l][s],s--;return 9===e?(o+=r-this.NEPALI_CALENDAR_DATA[l][0])<0&&(o+=a.daysInYear(c)):o+=this.NEPALI_CALENDAR_DATA[l][9]-this.NEPALI_CALENDAR_DATA[l][0],a.newDate(c,1,1).add(o,"d").toJD()},fromJD:function(t){var e=n.instance().fromJD(t),r=e.year(),i=e.dayOfYear(),a=r+56;this._createMissingCalendarData(a);for(var o=9,s=this.NEPALI_CALENDAR_DATA[a][0],l=this.NEPALI_CALENDAR_DATA[a][o]-s+1;i>l;)++o>12&&(o=1,a++),l+=this.NEPALI_CALENDAR_DATA[a][o];var c=this.NEPALI_CALENDAR_DATA[a][o]-(l-i);return this.newDate(a,o,c)},_createMissingCalendarData:function(t){var e=this.daysPerMonth.slice(0);e.unshift(17);for(var r=t-1;r0?474:473))%2820+474+38)%2816<682},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-(n.dayOfWeek()+1)%7,"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=i.year(),e=i.month(),r=i.day();var a=t-(t>=0?474:473),s=474+o(a,2820);return r+(e<=7?31*(e-1):30*(e-1)+6)+Math.floor((682*s-110)/2816)+365*(s-1)+1029983*Math.floor(a/2820)+this.jdEpoch-1},fromJD:function(t){var e=(t=Math.floor(t)+.5)-this.toJD(475,1,1),r=Math.floor(e/1029983),n=o(e,1029983),i=2820;if(1029982!==n){var a=Math.floor(n/366),s=o(n,366);i=Math.floor((2134*a+2816*s+2815)/1028522)+a+1}var l=i+2820*r+474;l=l<=0?l-1:l;var c=t-this.toJD(l,1,1)+1,u=c<=186?Math.ceil(c/31):Math.ceil((c-6)/30),f=t-this.toJD(l,u,1)+1;return this.newDate(l,u,f)}}),n.calendars.persian=a,n.calendars.jalali=a},{"../main":575,"object-assign":443}],572:[function(t,e,r){var n=t("../main"),i=t("object-assign"),a=n.instance();function o(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}o.prototype=new n.baseCalendar,i(o.prototype,{name:"Taiwan",jdEpoch:2419402.5,yearsOffset:1911,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Taiwan",epochs:["BROC","ROC"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:1,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(e.year());return a.leapYear(t)},weekOfYear:function(t,e,r){var i=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(i.year());return a.weekOfYear(t,i.month(),i.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=this._t2gYear(i.year());return a.toJD(t,i.month(),i.day())},fromJD:function(t){var e=a.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)},_g2tYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)}}),n.calendars.taiwan=o},{"../main":575,"object-assign":443}],573:[function(t,e,r){var n=t("../main"),i=t("object-assign"),a=n.instance();function o(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}o.prototype=new n.baseCalendar,i(o.prototype,{name:"Thai",jdEpoch:1523098.5,yearsOffset:543,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Thai",epochs:["BBE","BE"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(e.year());return a.leapYear(t)},weekOfYear:function(t,e,r){var i=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);t=this._t2gYear(i.year());return a.weekOfYear(t,i.month(),i.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,n.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate);t=this._t2gYear(i.year());return a.toJD(t,i.month(),i.day())},fromJD:function(t){var e=a.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)},_g2tYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)}}),n.calendars.thai=o},{"../main":575,"object-assign":443}],574:[function(t,e,r){var n=t("../main"),i=t("object-assign");function a(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}a.prototype=new n.baseCalendar,i(a.prototype,{name:"UmmAlQura",hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Umm al-Qura",epochs:["BH","AH"],monthNames:["Al-Muharram","Safar","Rabi' al-awwal","Rabi' Al-Thani","Jumada Al-Awwal","Jumada Al-Thani","Rajab","Sha'aban","Ramadan","Shawwal","Dhu al-Qi'dah","Dhu al-Hijjah"],monthNamesShort:["Muh","Saf","Rab1","Rab2","Jum1","Jum2","Raj","Sha'","Ram","Shaw","DhuQ","DhuH"],dayNames:["Yawm al-Ahad","Yawm al-Ithnain","Yawm al-Thal\u0101th\u0101\u2019","Yawm al-Arba\u2018\u0101\u2019","Yawm al-Kham\u012bs","Yawm al-Jum\u2018a","Yawm al-Sabt"],dayNamesMin:["Ah","Ith","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!0}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,n.local.invalidYear);return 355===this.daysInYear(e.year())},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){for(var e=0,r=1;r<=12;r++)e+=this.daysInMonth(t,r);return e},daysInMonth:function(t,e){for(var r=this._validate(t,e,this.minDay,n.local.invalidMonth).toJD()-24e5+.5,i=0,a=0;ar)return o[i]-o[i-1];i++}return 30},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var i=this._validate(t,e,r,n.local.invalidDate),a=12*(i.year()-1)+i.month()-15292;return i.day()+o[a-1]-1+24e5-.5},fromJD:function(t){for(var e=t-24e5+.5,r=0,n=0;ne);n++)r++;var i=r+15292,a=Math.floor((i-1)/12),s=a+1,l=i-12*a,c=e-o[r-1]+1;return this.newDate(s,l,c)},isValid:function(t,e,r){var i=n.baseCalendar.prototype.isValid.apply(this,arguments);return i&&(i=(t=null!=t.year?t.year:t)>=1276&&t<=1500),i},_validate:function(t,e,r,i){var a=n.baseCalendar.prototype._validate.apply(this,arguments);if(a.year<1276||a.year>1500)throw i.replace(/\{0\}/,this.local.name);return a}}),n.calendars.ummalqura=a;var o=[20,50,79,109,138,168,197,227,256,286,315,345,374,404,433,463,492,522,551,581,611,641,670,700,729,759,788,818,847,877,906,936,965,995,1024,1054,1083,1113,1142,1172,1201,1231,1260,1290,1320,1350,1379,1409,1438,1468,1497,1527,1556,1586,1615,1645,1674,1704,1733,1763,1792,1822,1851,1881,1910,1940,1969,1999,2028,2058,2087,2117,2146,2176,2205,2235,2264,2294,2323,2353,2383,2413,2442,2472,2501,2531,2560,2590,2619,2649,2678,2708,2737,2767,2796,2826,2855,2885,2914,2944,2973,3003,3032,3062,3091,3121,3150,3180,3209,3239,3268,3298,3327,3357,3386,3416,3446,3476,3505,3535,3564,3594,3623,3653,3682,3712,3741,3771,3800,3830,3859,3889,3918,3948,3977,4007,4036,4066,4095,4125,4155,4185,4214,4244,4273,4303,4332,4362,4391,4421,4450,4480,4509,4539,4568,4598,4627,4657,4686,4716,4745,4775,4804,4834,4863,4893,4922,4952,4981,5011,5040,5070,5099,5129,5158,5188,5218,5248,5277,5307,5336,5366,5395,5425,5454,5484,5513,5543,5572,5602,5631,5661,5690,5720,5749,5779,5808,5838,5867,5897,5926,5956,5985,6015,6044,6074,6103,6133,6162,6192,6221,6251,6281,6311,6340,6370,6399,6429,6458,6488,6517,6547,6576,6606,6635,6665,6694,6724,6753,6783,6812,6842,6871,6901,6930,6960,6989,7019,7048,7078,7107,7137,7166,7196,7225,7255,7284,7314,7344,7374,7403,7433,7462,7492,7521,7551,7580,7610,7639,7669,7698,7728,7757,7787,7816,7846,7875,7905,7934,7964,7993,8023,8053,8083,8112,8142,8171,8201,8230,8260,8289,8319,8348,8378,8407,8437,8466,8496,8525,8555,8584,8614,8643,8673,8702,8732,8761,8791,8821,8850,8880,8909,8938,8968,8997,9027,9056,9086,9115,9145,9175,9205,9234,9264,9293,9322,9352,9381,9410,9440,9470,9499,9529,9559,9589,9618,9648,9677,9706,9736,9765,9794,9824,9853,9883,9913,9943,9972,10002,10032,10061,10090,10120,10149,10178,10208,10237,10267,10297,10326,10356,10386,10415,10445,10474,10504,10533,10562,10592,10621,10651,10680,10710,10740,10770,10799,10829,10858,10888,10917,10947,10976,11005,11035,11064,11094,11124,11153,11183,11213,11242,11272,11301,11331,11360,11389,11419,11448,11478,11507,11537,11567,11596,11626,11655,11685,11715,11744,11774,11803,11832,11862,11891,11921,11950,11980,12010,12039,12069,12099,12128,12158,12187,12216,12246,12275,12304,12334,12364,12393,12423,12453,12483,12512,12542,12571,12600,12630,12659,12688,12718,12747,12777,12807,12837,12866,12896,12926,12955,12984,13014,13043,13072,13102,13131,13161,13191,13220,13250,13280,13310,13339,13368,13398,13427,13456,13486,13515,13545,13574,13604,13634,13664,13693,13723,13752,13782,13811,13840,13870,13899,13929,13958,13988,14018,14047,14077,14107,14136,14166,14195,14224,14254,14283,14313,14342,14372,14401,14431,14461,14490,14520,14550,14579,14609,14638,14667,14697,14726,14756,14785,14815,14844,14874,14904,14933,14963,14993,15021,15051,15081,15110,15140,15169,15199,15228,15258,15287,15317,15347,15377,15406,15436,15465,15494,15524,15553,15582,15612,15641,15671,15701,15731,15760,15790,15820,15849,15878,15908,15937,15966,15996,16025,16055,16085,16114,16144,16174,16204,16233,16262,16292,16321,16350,16380,16409,16439,16468,16498,16528,16558,16587,16617,16646,16676,16705,16734,16764,16793,16823,16852,16882,16912,16941,16971,17001,17030,17060,17089,17118,17148,17177,17207,17236,17266,17295,17325,17355,17384,17414,17444,17473,17502,17532,17561,17591,17620,17650,17679,17709,17738,17768,17798,17827,17857,17886,17916,17945,17975,18004,18034,18063,18093,18122,18152,18181,18211,18241,18270,18300,18330,18359,18388,18418,18447,18476,18506,18535,18565,18595,18625,18654,18684,18714,18743,18772,18802,18831,18860,18890,18919,18949,18979,19008,19038,19068,19098,19127,19156,19186,19215,19244,19274,19303,19333,19362,19392,19422,19452,19481,19511,19540,19570,19599,19628,19658,19687,19717,19746,19776,19806,19836,19865,19895,19924,19954,19983,20012,20042,20071,20101,20130,20160,20190,20219,20249,20279,20308,20338,20367,20396,20426,20455,20485,20514,20544,20573,20603,20633,20662,20692,20721,20751,20780,20810,20839,20869,20898,20928,20957,20987,21016,21046,21076,21105,21135,21164,21194,21223,21253,21282,21312,21341,21371,21400,21430,21459,21489,21519,21548,21578,21607,21637,21666,21696,21725,21754,21784,21813,21843,21873,21902,21932,21962,21991,22021,22050,22080,22109,22138,22168,22197,22227,22256,22286,22316,22346,22375,22405,22434,22464,22493,22522,22552,22581,22611,22640,22670,22700,22730,22759,22789,22818,22848,22877,22906,22936,22965,22994,23024,23054,23083,23113,23143,23173,23202,23232,23261,23290,23320,23349,23379,23408,23438,23467,23497,23527,23556,23586,23616,23645,23674,23704,23733,23763,23792,23822,23851,23881,23910,23940,23970,23999,24029,24058,24088,24117,24147,24176,24206,24235,24265,24294,24324,24353,24383,24413,24442,24472,24501,24531,24560,24590,24619,24648,24678,24707,24737,24767,24796,24826,24856,24885,24915,24944,24974,25003,25032,25062,25091,25121,25150,25180,25210,25240,25269,25299,25328,25358,25387,25416,25446,25475,25505,25534,25564,25594,25624,25653,25683,25712,25742,25771,25800,25830,25859,25888,25918,25948,25977,26007,26037,26067,26096,26126,26155,26184,26214,26243,26272,26302,26332,26361,26391,26421,26451,26480,26510,26539,26568,26598,26627,26656,26686,26715,26745,26775,26805,26834,26864,26893,26923,26952,26982,27011,27041,27070,27099,27129,27159,27188,27218,27248,27277,27307,27336,27366,27395,27425,27454,27484,27513,27542,27572,27602,27631,27661,27691,27720,27750,27779,27809,27838,27868,27897,27926,27956,27985,28015,28045,28074,28104,28134,28163,28193,28222,28252,28281,28310,28340,28369,28399,28428,28458,28488,28517,28547,28577,28607,28636,28665,28695,28724,28754,28783,28813,28843,28872,28901,28931,28960,28990,29019,29049,29078,29108,29137,29167,29196,29226,29255,29285,29315,29345,29375,29404,29434,29463,29492,29522,29551,29580,29610,29640,29669,29699,29729,29759,29788,29818,29847,29876,29906,29935,29964,29994,30023,30053,30082,30112,30141,30171,30200,30230,30259,30289,30318,30348,30378,30408,30437,30467,30496,30526,30555,30585,30614,30644,30673,30703,30732,30762,30791,30821,30850,30880,30909,30939,30968,30998,31027,31057,31086,31116,31145,31175,31204,31234,31263,31293,31322,31352,31381,31411,31441,31471,31500,31530,31559,31589,31618,31648,31676,31706,31736,31766,31795,31825,31854,31884,31913,31943,31972,32002,32031,32061,32090,32120,32150,32180,32209,32239,32268,32298,32327,32357,32386,32416,32445,32475,32504,32534,32563,32593,32622,32652,32681,32711,32740,32770,32799,32829,32858,32888,32917,32947,32976,33006,33035,33065,33094,33124,33153,33183,33213,33243,33272,33302,33331,33361,33390,33420,33450,33479,33509,33539,33568,33598,33627,33657,33686,33716,33745,33775,33804,33834,33863,33893,33922,33952,33981,34011,34040,34069,34099,34128,34158,34187,34217,34247,34277,34306,34336,34365,34395,34424,34454,34483,34512,34542,34571,34601,34631,34660,34690,34719,34749,34778,34808,34837,34867,34896,34926,34955,34985,35015,35044,35074,35103,35133,35162,35192,35222,35251,35280,35310,35340,35370,35399,35429,35458,35488,35517,35547,35576,35605,35635,35665,35694,35723,35753,35782,35811,35841,35871,35901,35930,35960,35989,36019,36048,36078,36107,36136,36166,36195,36225,36254,36284,36314,36343,36373,36403,36433,36462,36492,36521,36551,36580,36610,36639,36669,36698,36728,36757,36786,36816,36845,36875,36904,36934,36963,36993,37022,37052,37081,37111,37141,37170,37200,37229,37259,37288,37318,37347,37377,37406,37436,37465,37495,37524,37554,37584,37613,37643,37672,37701,37731,37760,37790,37819,37849,37878,37908,37938,37967,37997,38027,38056,38085,38115,38144,38174,38203,38233,38262,38292,38322,38351,38381,38410,38440,38469,38499,38528,38558,38587,38617,38646,38676,38705,38735,38764,38794,38823,38853,38882,38912,38941,38971,39001,39030,39059,39089,39118,39148,39178,39208,39237,39267,39297,39326,39355,39385,39414,39444,39473,39503,39532,39562,39592,39621,39650,39680,39709,39739,39768,39798,39827,39857,39886,39916,39946,39975,40005,40035,40064,40094,40123,40153,40182,40212,40241,40271,40300,40330,40359,40389,40418,40448,40477,40507,40536,40566,40595,40625,40655,40685,40714,40744,40773,40803,40832,40862,40892,40921,40951,40980,41009,41039,41068,41098,41127,41157,41186,41216,41245,41275,41304,41334,41364,41393,41422,41452,41481,41511,41540,41570,41599,41629,41658,41688,41718,41748,41777,41807,41836,41865,41894,41924,41953,41983,42012,42042,42072,42102,42131,42161,42190,42220,42249,42279,42308,42337,42367,42397,42426,42456,42485,42515,42545,42574,42604,42633,42662,42692,42721,42751,42780,42810,42839,42869,42899,42929,42958,42988,43017,43046,43076,43105,43135,43164,43194,43223,43253,43283,43312,43342,43371,43401,43430,43460,43489,43519,43548,43578,43607,43637,43666,43696,43726,43755,43785,43814,43844,43873,43903,43932,43962,43991,44021,44050,44080,44109,44139,44169,44198,44228,44258,44287,44317,44346,44375,44405,44434,44464,44493,44523,44553,44582,44612,44641,44671,44700,44730,44759,44788,44818,44847,44877,44906,44936,44966,44996,45025,45055,45084,45114,45143,45172,45202,45231,45261,45290,45320,45350,45380,45409,45439,45468,45498,45527,45556,45586,45615,45644,45674,45704,45733,45763,45793,45823,45852,45882,45911,45940,45970,45999,46028,46058,46088,46117,46147,46177,46206,46236,46265,46295,46324,46354,46383,46413,46442,46472,46501,46531,46560,46590,46620,46649,46679,46708,46738,46767,46797,46826,46856,46885,46915,46944,46974,47003,47033,47063,47092,47122,47151,47181,47210,47240,47269,47298,47328,47357,47387,47417,47446,47476,47506,47535,47565,47594,47624,47653,47682,47712,47741,47771,47800,47830,47860,47890,47919,47949,47978,48008,48037,48066,48096,48125,48155,48184,48214,48244,48273,48303,48333,48362,48392,48421,48450,48480,48509,48538,48568,48598,48627,48657,48687,48717,48746,48776,48805,48834,48864,48893,48922,48952,48982,49011,49041,49071,49100,49130,49160,49189,49218,49248,49277,49306,49336,49365,49395,49425,49455,49484,49514,49543,49573,49602,49632,49661,49690,49720,49749,49779,49809,49838,49868,49898,49927,49957,49986,50016,50045,50075,50104,50133,50163,50192,50222,50252,50281,50311,50340,50370,50400,50429,50459,50488,50518,50547,50576,50606,50635,50665,50694,50724,50754,50784,50813,50843,50872,50902,50931,50960,50990,51019,51049,51078,51108,51138,51167,51197,51227,51256,51286,51315,51345,51374,51403,51433,51462,51492,51522,51552,51582,51611,51641,51670,51699,51729,51758,51787,51816,51846,51876,51906,51936,51965,51995,52025,52054,52083,52113,52142,52171,52200,52230,52260,52290,52319,52349,52379,52408,52438,52467,52497,52526,52555,52585,52614,52644,52673,52703,52733,52762,52792,52822,52851,52881,52910,52939,52969,52998,53028,53057,53087,53116,53146,53176,53205,53235,53264,53294,53324,53353,53383,53412,53441,53471,53500,53530,53559,53589,53619,53648,53678,53708,53737,53767,53796,53825,53855,53884,53913,53943,53973,54003,54032,54062,54092,54121,54151,54180,54209,54239,54268,54297,54327,54357,54387,54416,54446,54476,54505,54535,54564,54593,54623,54652,54681,54711,54741,54770,54800,54830,54859,54889,54919,54948,54977,55007,55036,55066,55095,55125,55154,55184,55213,55243,55273,55302,55332,55361,55391,55420,55450,55479,55508,55538,55567,55597,55627,55657,55686,55716,55745,55775,55804,55834,55863,55892,55922,55951,55981,56011,56040,56070,56100,56129,56159,56188,56218,56247,56276,56306,56335,56365,56394,56424,56454,56483,56513,56543,56572,56601,56631,56660,56690,56719,56749,56778,56808,56837,56867,56897,56926,56956,56985,57015,57044,57074,57103,57133,57162,57192,57221,57251,57280,57310,57340,57369,57399,57429,57458,57487,57517,57546,57576,57605,57634,57664,57694,57723,57753,57783,57813,57842,57871,57901,57930,57959,57989,58018,58048,58077,58107,58137,58167,58196,58226,58255,58285,58314,58343,58373,58402,58432,58461,58491,58521,58551,58580,58610,58639,58669,58698,58727,58757,58786,58816,58845,58875,58905,58934,58964,58994,59023,59053,59082,59111,59141,59170,59200,59229,59259,59288,59318,59348,59377,59407,59436,59466,59495,59525,59554,59584,59613,59643,59672,59702,59731,59761,59791,59820,59850,59879,59909,59939,59968,59997,60027,60056,60086,60115,60145,60174,60204,60234,60264,60293,60323,60352,60381,60411,60440,60469,60499,60528,60558,60588,60618,60648,60677,60707,60736,60765,60795,60824,60853,60883,60912,60942,60972,61002,61031,61061,61090,61120,61149,61179,61208,61237,61267,61296,61326,61356,61385,61415,61445,61474,61504,61533,61563,61592,61621,61651,61680,61710,61739,61769,61799,61828,61858,61888,61917,61947,61976,62006,62035,62064,62094,62123,62153,62182,62212,62242,62271,62301,62331,62360,62390,62419,62448,62478,62507,62537,62566,62596,62625,62655,62685,62715,62744,62774,62803,62832,62862,62891,62921,62950,62980,63009,63039,63069,63099,63128,63157,63187,63216,63246,63275,63305,63334,63363,63393,63423,63453,63482,63512,63541,63571,63600,63630,63659,63689,63718,63747,63777,63807,63836,63866,63895,63925,63955,63984,64014,64043,64073,64102,64131,64161,64190,64220,64249,64279,64309,64339,64368,64398,64427,64457,64486,64515,64545,64574,64603,64633,64663,64692,64722,64752,64782,64811,64841,64870,64899,64929,64958,64987,65017,65047,65076,65106,65136,65166,65195,65225,65254,65283,65313,65342,65371,65401,65431,65460,65490,65520,65549,65579,65608,65638,65667,65697,65726,65755,65785,65815,65844,65874,65903,65933,65963,65992,66022,66051,66081,66110,66140,66169,66199,66228,66258,66287,66317,66346,66376,66405,66435,66465,66494,66524,66553,66583,66612,66641,66671,66700,66730,66760,66789,66819,66849,66878,66908,66937,66967,66996,67025,67055,67084,67114,67143,67173,67203,67233,67262,67292,67321,67351,67380,67409,67439,67468,67497,67527,67557,67587,67617,67646,67676,67705,67735,67764,67793,67823,67852,67882,67911,67941,67971,68e3,68030,68060,68089,68119,68148,68177,68207,68236,68266,68295,68325,68354,68384,68414,68443,68473,68502,68532,68561,68591,68620,68650,68679,68708,68738,68768,68797,68827,68857,68886,68916,68946,68975,69004,69034,69063,69092,69122,69152,69181,69211,69240,69270,69300,69330,69359,69388,69418,69447,69476,69506,69535,69565,69595,69624,69654,69684,69713,69743,69772,69802,69831,69861,69890,69919,69949,69978,70008,70038,70067,70097,70126,70156,70186,70215,70245,70274,70303,70333,70362,70392,70421,70451,70481,70510,70540,70570,70599,70629,70658,70687,70717,70746,70776,70805,70835,70864,70894,70924,70954,70983,71013,71042,71071,71101,71130,71159,71189,71218,71248,71278,71308,71337,71367,71397,71426,71455,71485,71514,71543,71573,71602,71632,71662,71691,71721,71751,71781,71810,71839,71869,71898,71927,71957,71986,72016,72046,72075,72105,72135,72164,72194,72223,72253,72282,72311,72341,72370,72400,72429,72459,72489,72518,72548,72577,72607,72637,72666,72695,72725,72754,72784,72813,72843,72872,72902,72931,72961,72991,73020,73050,73080,73109,73139,73168,73197,73227,73256,73286,73315,73345,73375,73404,73434,73464,73493,73523,73552,73581,73611,73640,73669,73699,73729,73758,73788,73818,73848,73877,73907,73936,73965,73995,74024,74053,74083,74113,74142,74172,74202,74231,74261,74291,74320,74349,74379,74408,74437,74467,74497,74526,74556,74586,74615,74645,74675,74704,74733,74763,74792,74822,74851,74881,74910,74940,74969,74999,75029,75058,75088,75117,75147,75176,75206,75235,75264,75294,75323,75353,75383,75412,75442,75472,75501,75531,75560,75590,75619,75648,75678,75707,75737,75766,75796,75826,75856,75885,75915,75944,75974,76003,76032,76062,76091,76121,76150,76180,76210,76239,76269,76299,76328,76358,76387,76416,76446,76475,76505,76534,76564,76593,76623,76653,76682,76712,76741,76771,76801,76830,76859,76889,76918,76948,76977,77007,77036,77066,77096,77125,77155,77185,77214,77243,77273,77302,77332,77361,77390,77420,77450,77479,77509,77539,77569,77598,77627,77657,77686,77715,77745,77774,77804,77833,77863,77893,77923,77952,77982,78011,78041,78070,78099,78129,78158,78188,78217,78247,78277,78307,78336,78366,78395,78425,78454,78483,78513,78542,78572,78601,78631,78661,78690,78720,78750,78779,78808,78838,78867,78897,78926,78956,78985,79015,79044,79074,79104,79133,79163,79192,79222,79251,79281,79310,79340,79369,79399,79428,79458,79487,79517,79546,79576,79606,79635,79665,79695,79724,79753,79783,79812,79841,79871,79900,79930,79960,79990]},{"../main":575,"object-assign":443}],575:[function(t,e,r){var n=t("object-assign");function i(){this.regionalOptions=[],this.regionalOptions[""]={invalidCalendar:"Calendar {0} not found",invalidDate:"Invalid {0} date",invalidMonth:"Invalid {0} month",invalidYear:"Invalid {0} year",differentCalendars:"Cannot mix {0} and {1} dates"},this.local=this.regionalOptions[""],this.calendars={},this._localCals={}}function a(t,e,r,n){if(this._calendar=t,this._year=e,this._month=r,this._day=n,0===this._calendar._validateLevel&&!this._calendar.isValid(this._year,this._month,this._day))throw(c.local.invalidDate||c.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name)}function o(t,e){return"000000".substring(0,e-(t=""+t).length)+t}function s(){this.shortYearCutoff="+10"}function l(t){this.local=this.regionalOptions[t]||this.regionalOptions[""]}n(i.prototype,{instance:function(t,e){t=(t||"gregorian").toLowerCase(),e=e||"";var r=this._localCals[t+"-"+e];if(!r&&this.calendars[t]&&(r=new this.calendars[t](e),this._localCals[t+"-"+e]=r),!r)throw(this.local.invalidCalendar||this.regionalOptions[""].invalidCalendar).replace(/\{0\}/,t);return r},newDate:function(t,e,r,n,i){return(n=(null!=t&&t.year?t.calendar():"string"==typeof n?this.instance(n,i):n)||this.instance()).newDate(t,e,r)},substituteDigits:function(t){return function(e){return(e+"").replace(/[0-9]/g,function(e){return t[e]})}},substituteChineseDigits:function(t,e){return function(r){for(var n="",i=0;r>0;){var a=r%10;n=(0===a?"":t[a]+e[i])+n,i++,r=Math.floor(r/10)}return 0===n.indexOf(t[1]+e[1])&&(n=n.substr(1)),n||t[0]}}}),n(a.prototype,{newDate:function(t,e,r){return this._calendar.newDate(null==t?this:t,e,r)},year:function(t){return 0===arguments.length?this._year:this.set(t,"y")},month:function(t){return 0===arguments.length?this._month:this.set(t,"m")},day:function(t){return 0===arguments.length?this._day:this.set(t,"d")},date:function(t,e,r){if(!this._calendar.isValid(t,e,r))throw(c.local.invalidDate||c.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name);return this._year=t,this._month=e,this._day=r,this},leapYear:function(){return this._calendar.leapYear(this)},epoch:function(){return this._calendar.epoch(this)},formatYear:function(){return this._calendar.formatYear(this)},monthOfYear:function(){return this._calendar.monthOfYear(this)},weekOfYear:function(){return this._calendar.weekOfYear(this)},daysInYear:function(){return this._calendar.daysInYear(this)},dayOfYear:function(){return this._calendar.dayOfYear(this)},daysInMonth:function(){return this._calendar.daysInMonth(this)},dayOfWeek:function(){return this._calendar.dayOfWeek(this)},weekDay:function(){return this._calendar.weekDay(this)},extraInfo:function(){return this._calendar.extraInfo(this)},add:function(t,e){return this._calendar.add(this,t,e)},set:function(t,e){return this._calendar.set(this,t,e)},compareTo:function(t){if(this._calendar.name!==t._calendar.name)throw(c.local.differentCalendars||c.regionalOptions[""].differentCalendars).replace(/\{0\}/,this._calendar.local.name).replace(/\{1\}/,t._calendar.local.name);var e=this._year!==t._year?this._year-t._year:this._month!==t._month?this.monthOfYear()-t.monthOfYear():this._day-t._day;return 0===e?0:e<0?-1:1},calendar:function(){return this._calendar},toJD:function(){return this._calendar.toJD(this)},fromJD:function(t){return this._calendar.fromJD(t)},toJSDate:function(){return this._calendar.toJSDate(this)},fromJSDate:function(t){return this._calendar.fromJSDate(t)},toString:function(){return(this.year()<0?"-":"")+o(Math.abs(this.year()),4)+"-"+o(this.month(),2)+"-"+o(this.day(),2)}}),n(s.prototype,{_validateLevel:0,newDate:function(t,e,r){return null==t?this.today():(t.year&&(this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),r=t.day(),e=t.month(),t=t.year()),new a(this,t,e,r))},today:function(){return this.fromJSDate(new Date)},epoch:function(t){return this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear).year()<0?this.local.epochs[0]:this.local.epochs[1]},formatYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear);return(e.year()<0?"-":"")+o(Math.abs(e.year()),4)},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear),12},monthOfYear:function(t,e){var r=this._validate(t,e,this.minDay,c.local.invalidMonth||c.regionalOptions[""].invalidMonth);return(r.month()+this.monthsInYear(r)-this.firstMonth)%this.monthsInYear(r)+this.minMonth},fromMonthOfYear:function(t,e){var r=(e+this.firstMonth-2*this.minMonth)%this.monthsInYear(t)+this.minMonth;return this._validate(t,r,this.minDay,c.local.invalidMonth||c.regionalOptions[""].invalidMonth),r},daysInYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,c.local.invalidYear||c.regionalOptions[""].invalidYear);return this.leapYear(e)?366:365},dayOfYear:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);return n.toJD()-this.newDate(n.year(),this.fromMonthOfYear(n.year(),this.minMonth),this.minDay).toJD()+1},daysInWeek:function(){return 7},dayOfWeek:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate);return(Math.floor(this.toJD(n))+2)%this.daysInWeek()},extraInfo:function(t,e,r){return this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),{}},add:function(t,e,r){return this._validate(t,this.minMonth,this.minDay,c.local.invalidDate||c.regionalOptions[""].invalidDate),this._correctAdd(t,this._add(t,e,r),e,r)},_add:function(t,e,r){if(this._validateLevel++,"d"===r||"w"===r){var n=t.toJD()+e*("w"===r?this.daysInWeek():1),i=t.calendar().fromJD(n);return this._validateLevel--,[i.year(),i.month(),i.day()]}try{var a=t.year()+("y"===r?e:0),o=t.monthOfYear()+("m"===r?e:0);i=t.day();"y"===r?(t.month()!==this.fromMonthOfYear(a,o)&&(o=this.newDate(a,t.month(),this.minDay).monthOfYear()),o=Math.min(o,this.monthsInYear(a)),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o)))):"m"===r&&(!function(t){for(;oe-1+t.minMonth;)a++,o-=e,e=t.monthsInYear(a)}(this),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o))));var s=[a,this.fromMonthOfYear(a,o),i];return this._validateLevel--,s}catch(t){throw this._validateLevel--,t}},_correctAdd:function(t,e,r,n){if(!(this.hasYearZero||"y"!==n&&"m"!==n||0!==e[0]&&t.year()>0==e[0]>0)){var i={y:[1,1,"y"],m:[1,this.monthsInYear(-1),"m"],w:[this.daysInWeek(),this.daysInYear(-1),"d"],d:[1,this.daysInYear(-1),"d"]}[n],a=r<0?-1:1;e=this._add(t,r*i[0]+a*i[1],i[2])}return t.date(e[0],e[1],e[2])},set:function(t,e,r){this._validate(t,this.minMonth,this.minDay,c.local.invalidDate||c.regionalOptions[""].invalidDate);var n="y"===r?e:t.year(),i="m"===r?e:t.month(),a="d"===r?e:t.day();return"y"!==r&&"m"!==r||(a=Math.min(a,this.daysInMonth(n,i))),t.date(n,i,a)},isValid:function(t,e,r){this._validateLevel++;var n=this.hasYearZero||0!==t;if(n){var i=this.newDate(t,e,this.minDay);n=e>=this.minMonth&&e-this.minMonth=this.minDay&&r-this.minDay13.5?13:1),c=i-(l>2.5?4716:4715);return c<=0&&c--,this.newDate(c,l,s)},toJSDate:function(t,e,r){var n=this._validate(t,e,r,c.local.invalidDate||c.regionalOptions[""].invalidDate),i=new Date(n.year(),n.month()-1,n.day());return i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.setHours(i.getHours()>12?i.getHours()+2:0),i},fromJSDate:function(t){return this.newDate(t.getFullYear(),t.getMonth()+1,t.getDate())}});var c=e.exports=new i;c.cdate=a,c.baseCalendar=s,c.calendars.gregorian=l},{"object-assign":443}],576:[function(t,e,r){var n=t("object-assign"),i=t("./main");n(i.regionalOptions[""],{invalidArguments:"Invalid arguments",invalidFormat:"Cannot format a date from another calendar",missingNumberAt:"Missing number at position {0}",unknownNameAt:"Unknown name at position {0}",unexpectedLiteralAt:"Unexpected literal at position {0}",unexpectedText:"Additional text found at end"}),i.local=i.regionalOptions[""],n(i.cdate.prototype,{formatDate:function(t,e){return"string"!=typeof t&&(e=t,t=""),this._calendar.formatDate(t||"",this,e)}}),n(i.baseCalendar.prototype,{UNIX_EPOCH:i.instance().newDate(1970,1,1).toJD(),SECS_PER_DAY:86400,TICKS_EPOCH:i.instance().jdEpoch,TICKS_PER_DAY:864e9,ATOM:"yyyy-mm-dd",COOKIE:"D, dd M yyyy",FULL:"DD, MM d, yyyy",ISO_8601:"yyyy-mm-dd",JULIAN:"J",RFC_822:"D, d M yy",RFC_850:"DD, dd-M-yy",RFC_1036:"D, d M yy",RFC_1123:"D, d M yyyy",RFC_2822:"D, d M yyyy",RSS:"D, d M yy",TICKS:"!",TIMESTAMP:"@",W3C:"yyyy-mm-dd",formatDate:function(t,e,r){if("string"!=typeof t&&(r=e,e=t,t=""),!e)return"";if(e.calendar()!==this)throw i.local.invalidFormat||i.regionalOptions[""].invalidFormat;t=t||this.local.dateFormat;for(var n,a,o,s,l=(r=r||{}).dayNamesShort||this.local.dayNamesShort,c=r.dayNames||this.local.dayNames,u=r.monthNumbers||this.local.monthNumbers,f=r.monthNamesShort||this.local.monthNamesShort,h=r.monthNames||this.local.monthNames,d=(r.calculateWeek||this.local.calculateWeek,function(e,r){for(var n=1;w+n1}),p=function(t,e,r,n){var i=""+e;if(d(t,n))for(;i.length1},b=function(t,r){var n=y(t,r),a=[2,3,n?4:2,n?4:2,10,11,20]["oyYJ@!".indexOf(t)+1],o=new RegExp("^-?\\d{1,"+a+"}"),s=e.substring(A).match(o);if(!s)throw(i.local.missingNumberAt||i.regionalOptions[""].missingNumberAt).replace(/\{0\}/,A);return A+=s[0].length,parseInt(s[0],10)},x=this,_=function(){if("function"==typeof l){y("m");var t=l.call(x,e.substring(A));return A+=t.length,t}return b("m")},w=function(t,r,n,a){for(var o=y(t,a)?n:r,s=0;s-1){d=1,p=m;for(var S=this.daysInMonth(h,d);p>S;S=this.daysInMonth(h,d))d++,p-=S}return f>-1?this.fromJD(f):this.newDate(h,d,p)},determineDate:function(t,e,r,n,i){r&&"object"!=typeof r&&(i=n,n=r,r=null),"string"!=typeof n&&(i=n,n="");var a=this;return e=e?e.newDate():null,t=null==t?e:"string"==typeof t?function(t){try{return a.parseDate(n,t,i)}catch(t){}for(var e=((t=t.toLowerCase()).match(/^c/)&&r?r.newDate():null)||a.today(),o=/([+-]?[0-9]+)\s*(d|w|m|y)?/g,s=o.exec(t);s;)e.add(parseInt(s[1],10),s[2]||"d"),s=o.exec(t);return e}(t):"number"==typeof t?isNaN(t)||t===1/0||t===-1/0?e:a.today().add(t,"d"):a.newDate(t)}})},{"./main":575,"object-assign":443}],577:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array",{offset:[1],array:0},"scalar","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\n var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":116}],578:[function(t,e,r){"use strict";e.exports=function(t,e){var r=[];return e=+e||0,n(t.hi(t.shape[0]-1),r,e),r};var n=t("./lib/zc-core")},{"./lib/zc-core":577}],579:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("./common_defaults"),o=t("./attributes");e.exports=function(t,e,r,s,l){function c(r,i){return n.coerce(t,e,o,r,i)}s=s||{};var u=c("visible",!(l=l||{}).itemIsNotPlainObject),f=c("clicktoshow");if(!u&&!f)return e;a(t,e,r,c);for(var h=e.showarrow,d=["x","y"],p=[-10,-30],m={_fullLayout:r},v=0;v<2;v++){var g=d[v],y=i.coerceRef(t,e,m,g,"","paper");if(i.coercePosition(e,m,c,y,g,.5),h){var b="a"+g,x=i.coerceRef(t,e,m,b,"pixel");"pixel"!==x&&x!==y&&(x=e[b]="pixel");var _="pixel"===x?p[v]:.4;i.coercePosition(e,m,c,x,b,_)}c(g+"anchor"),c(g+"shift")}if(n.noneOrAll(t,e,["x","y"]),h&&n.noneOrAll(t,e,["ax","ay"]),f){var w=c("xclick"),M=c("yclick");e._xclick=void 0===w?e.x:i.cleanPosition(w,m,e.xref),e._yclick=void 0===M?e.y:i.cleanPosition(M,m,e.yref)}return e}},{"../../lib":724,"../../plots/cartesian/axes":770,"./attributes":581,"./common_defaults":584}],580:[function(t,e,r){"use strict";e.exports=[{path:"",backoff:0},{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0,noRotate:!0},{path:"M2,2V-2H-2V2Z",backoff:0,noRotate:!0}]},{}],581:[function(t,e,r){"use strict";var n=t("./arrow_paths"),i=t("../../plots/font_attributes"),a=t("../../plots/cartesian/constants");e.exports={_isLinkedToArray:"annotation",visible:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},text:{valType:"string",editType:"calcIfAutorange+arraydraw"},textangle:{valType:"angle",dflt:0,editType:"calcIfAutorange+arraydraw"},font:i({editType:"calcIfAutorange+arraydraw",colorEditType:"arraydraw"}),width:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},height:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},align:{valType:"enumerated",values:["left","center","right"],dflt:"center",editType:"arraydraw"},valign:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle",editType:"arraydraw"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},borderpad:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},borderwidth:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},showarrow:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},arrowcolor:{valType:"color",editType:"arraydraw"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},startarrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},arrowside:{valType:"flaglist",flags:["end","start"],extras:["none"],dflt:"end",editType:"arraydraw"},arrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},startarrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},arrowwidth:{valType:"number",min:.1,editType:"calcIfAutorange+arraydraw"},standoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},startstandoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},ax:{valType:"any",editType:"calcIfAutorange+arraydraw"},ay:{valType:"any",editType:"calcIfAutorange+arraydraw"},axref:{valType:"enumerated",dflt:"pixel",values:["pixel",a.idRegex.x.toString()],editType:"calc"},ayref:{valType:"enumerated",dflt:"pixel",values:["pixel",a.idRegex.y.toString()],editType:"calc"},xref:{valType:"enumerated",values:["paper",a.idRegex.x.toString()],editType:"calc"},x:{valType:"any",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},xshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},yref:{valType:"enumerated",values:["paper",a.idRegex.y.toString()],editType:"calc"},y:{valType:"any",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},yshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},clicktoshow:{valType:"enumerated",values:[!1,"onoff","onout"],dflt:!1,editType:"arraydraw"},xclick:{valType:"any",editType:"arraydraw"},yclick:{valType:"any",editType:"arraydraw"},hovertext:{valType:"string",editType:"arraydraw"},hoverlabel:{bgcolor:{valType:"color",editType:"arraydraw"},bordercolor:{valType:"color",editType:"arraydraw"},font:i({editType:"arraydraw"}),editType:"arraydraw"},captureevents:{valType:"boolean",editType:"arraydraw"},editType:"calc",_deprecated:{ref:{valType:"string",editType:"calc"}}}},{"../../plots/cartesian/constants":775,"../../plots/font_attributes":797,"./arrow_paths":580}],582:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("./draw").draw;function o(t){var e=t._fullLayout;n.filterVisible(e.annotations).forEach(function(e){var r,n,a,o,s=i.getFromId(t,e.xref),l=i.getFromId(t,e.yref),c=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;s&&s.autorange&&(r=c+e.xshift,n=c-e.xshift,a=u+e.xshift,o=u-e.xshift,e.axref===e.xref?(i.expand(s,[s.r2c(e.x)],{ppadplus:r,ppadminus:n}),i.expand(s,[s.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,a),ppadminus:Math.max(e._xpadminus,o)})):(a=e.ax?a+e.ax:a,o=e.ax?o-e.ax:o,i.expand(s,[s.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,a),ppadminus:Math.max(e._xpadminus,n,o)}))),l&&l.autorange&&(r=c-e.yshift,n=c+e.yshift,a=u-e.yshift,o=u+e.yshift,e.ayref===e.yref?(i.expand(l,[l.r2c(e.y)],{ppadplus:r,ppadminus:n}),i.expand(l,[l.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,a),ppadminus:Math.max(e._ypadminus,o)})):(a=e.ay?a+e.ay:a,o=e.ay?o-e.ay:o,i.expand(l,[l.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,a),ppadminus:Math.max(e._ypadminus,n,o)})))})}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.annotations);if(r.length&&t._fullData.length){var s={};for(var l in r.forEach(function(t){s[t.xref]=1,s[t.yref]=1}),s){var c=i.getFromId(t,l);if(c&&c.autorange)return n.syncOrAsync([a,o],t)}}}},{"../../lib":724,"../../plots/cartesian/axes":770,"./draw":587}],583:[function(t,e,r){"use strict";var n=t("../../plotly");function i(t,e){var r,n,i,o,s,l,c,u=t._fullLayout.annotations,f=[],h=[],d=[],p=(e||[]).length;for(r=0;r0||r.explicitOff.length>0},onClick:function(t,e){var r,a=i(t,e),o=a.on,s=a.off.concat(a.explicitOff),l={};if(!o.length&&!s.length)return;for(r=0;r2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}e._w=I,e._h=N;for(var U=!1,V=["x","y"],q=0;q1)&&(K===J?((ot=Q.r2fraction(e["a"+Z]))<0||ot>1)&&(U=!0):U=!0,U))continue;H=Q._offset+Q.r2p(e[Z]),W=.5}else"x"===Z?(Y=e[Z],H=b.l+b.w*Y):(Y=1-e[Z],H=b.t+b.h*Y),W=e.showarrow?.5:Y;if(e.showarrow){at.head=H;var st=e["a"+Z];X=tt*B(.5,e.xanchor)-et*B(.5,e.yanchor),K===J?(at.tail=Q._offset+Q.r2p(st),G=X):(at.tail=H+st,G=X+st),at.text=at.tail+X;var lt=y["x"===Z?"width":"height"];if("paper"===J&&(at.head=o.constrain(at.head,1,lt-1)),"pixel"===K){var ct=-Math.max(at.tail-3,at.text),ut=Math.min(at.tail+3,at.text)-lt;ct>0?(at.tail+=ct,at.text+=ct):ut>0&&(at.tail-=ut,at.text-=ut)}at.tail+=it,at.head+=it}else G=X=rt*B(W,nt),at.text=H+X;at.text+=it,X+=it,G+=it,e["_"+Z+"padplus"]=rt/2+G,e["_"+Z+"padminus"]=rt/2-G,e["_"+Z+"size"]=rt,e["_"+Z+"shift"]=X}if(U)S.remove();else{var ft=0,ht=0;if("left"!==e.align&&(ft=(I-E)*("center"===e.align?.5:1)),"top"!==e.valign&&(ht=(N-C)*("middle"===e.valign?.5:1)),u)n.select("svg").attr({x:P+ft-1,y:P+ht}).call(c.setClipUrl,O?_:null);else{var dt=P+ht-v.top,pt=P+ft-v.left;R.call(f.positionText,pt,dt).call(c.setClipUrl,O?_:null)}D.select("rect").call(c.setRect,P,P,I,N),z.call(c.setRect,L/2,L/2,F-L,j-L),S.call(c.setTranslate,Math.round(w.x.text-F/2),Math.round(w.y.text-j/2)),A.attr({transform:"rotate("+M+","+w.x.text+","+w.y.text+")"});var mt,vt,gt=function(r,n){k.selectAll(".annotation-arrow-g").remove();var u=w.x.head,f=w.y.head,h=w.x.tail+r,v=w.y.tail+n,y=w.x.text+r,_=w.y.text+n,T=o.rotationXYMatrix(M,y,_),E=o.apply2DTransform(T),L=o.apply2DTransform2(T),C=+z.attr("width"),P=+z.attr("height"),O=y-.5*C,D=O+C,I=_-.5*P,R=I+P,N=[[O,I,O,R],[O,R,D,R],[D,R,D,I],[D,I,O,I]].map(L);if(!N.reduce(function(t,e){return t^!!o.segmentsIntersect(u,f,u+1e6,f+1e6,e[0],e[1],e[2],e[3])},!1)){N.forEach(function(t){var e=o.segmentsIntersect(h,v,u,f,t[0],t[1],t[2],t[3]);e&&(h=e.x,v=e.y)});var F=e.arrowwidth,j=e.arrowcolor,B=e.arrowside,U=k.append("g").style({opacity:l.opacity(j)}).classed("annotation-arrow-g",!0),V=U.append("path").attr("d","M"+h+","+v+"L"+u+","+f).style("stroke-width",F+"px").call(l.stroke,l.rgb(j));if(p(V,B,e),x.annotationPosition&&V.node().parentNode&&!a){var q=u,H=f;if(e.standoff){var G=Math.sqrt(Math.pow(u-h,2)+Math.pow(f-v,2));q+=e.standoff*(h-u)/G,H+=e.standoff*(v-f)/G}var Y,W,X,Z=U.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(h-q)+","+(v-H),transform:"translate("+q+","+H+")"}).style("stroke-width",F+6+"px").call(l.stroke,"rgba(0,0,0,0)").call(l.fill,"rgba(0,0,0,0)");d.init({element:Z.node(),gd:t,prepFn:function(){var t=c.getTranslate(S);W=t.x,X=t.y,Y={},s&&s.autorange&&(Y[s._name+".autorange"]=!0),m&&m.autorange&&(Y[m._name+".autorange"]=!0)},moveFn:function(t,r){var n=E(W,X),i=n[0]+t,a=n[1]+r;S.call(c.setTranslate,i,a),Y[g+".x"]=s?s.p2r(s.r2p(e.x)+t):e.x+t/b.w,Y[g+".y"]=m?m.p2r(m.r2p(e.y)+r):e.y-r/b.h,e.axref===e.xref&&(Y[g+".ax"]=s.p2r(s.r2p(e.ax)+t)),e.ayref===e.yref&&(Y[g+".ay"]=m.p2r(m.r2p(e.ay)+r)),U.attr("transform","translate("+t+","+r+")"),A.attr({transform:"rotate("+M+","+i+","+a+")"})},doneFn:function(){i.relayout(t,Y);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&>(0,0),T)d.init({element:S.node(),gd:t,prepFn:function(){vt=A.attr("transform"),mt={}},moveFn:function(t,r){var n="pointer";if(e.showarrow)e.axref===e.xref?mt[g+".ax"]=s.p2r(s.r2p(e.ax)+t):mt[g+".ax"]=e.ax+t,e.ayref===e.yref?mt[g+".ay"]=m.p2r(m.r2p(e.ay)+r):mt[g+".ay"]=e.ay+r,gt(t,r);else{if(a)return;if(s)mt[g+".x"]=e.x+t/s._m;else{var i=e._xsize/b.w,o=e.x+(e._xshift-e.xshift)/b.w-i/2;mt[g+".x"]=d.align(o+t/b.w,i,0,1,e.xanchor)}if(m)mt[g+".y"]=e.y+r/m._m;else{var l=e._ysize/b.h,c=e.y-(e._yshift+e.yshift)/b.h-l/2;mt[g+".y"]=d.align(c-r/b.h,l,0,1,e.yanchor)}s&&m||(n=d.getCursor(s?.5:mt[g+".x"],m?.5:mt[g+".y"],e.xanchor,e.yanchor))}A.attr({transform:"translate("+t+","+r+")"+vt}),h(S,n)},doneFn:function(){h(S),i.relayout(t,mt);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}e.exports={draw:function(t){var e=t._fullLayout;e._infolayer.selectAll(".annotation").remove();for(var r=0;r=0,v=e.indexOf("end")>=0,g=f.backoff*d+r.standoff,y=h.backoff*p+r.startstandoff;if("line"===u.nodeName){o={x:+t.attr("x1"),y:+t.attr("y1")},s={x:+t.attr("x2"),y:+t.attr("y2")};var b=o.x-s.x,x=o.y-s.y;if(c=(l=Math.atan2(x,b))+Math.PI,g&&y&&g+y>Math.sqrt(b*b+x*x))return void P();if(g){if(g*g>b*b+x*x)return void P();var _=g*Math.cos(l),w=g*Math.sin(l);s.x+=_,s.y+=w,t.attr({x2:s.x,y2:s.y})}if(y){if(y*y>b*b+x*x)return void P();var M=y*Math.cos(l),k=y*Math.sin(l);o.x-=M,o.y-=k,t.attr({x1:o.x,y1:o.y})}}else if("path"===u.nodeName){var A=u.getTotalLength(),T="";if(A1){c=!0;break}}c?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+s+'"]').remove():(l._pdata=i(t.glplot.cameraParams,[e.xaxis.r2l(l.x)*r[0],e.yaxis.r2l(l.y)*r[1],e.zaxis.r2l(l.z)*r[2]]),n(t.graphDiv,l,s,t.id,l._xa,l._ya))}}},{"../../plots/gl3d/project":822,"../annotations/draw":587}],594:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib");e.exports={moduleType:"component",name:"annotations3d",schema:{subplots:{scene:{annotations:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),includeBasePlot:function(t,e){var r=n.subplotsRegistry.gl3d;if(!r)return;for(var a=r.attrRegex,o=Object.keys(t),s=0;s=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return a?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}a.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},a.rgb=function(t){return a.tinyRGB(n(t))},a.opacity=function(t){return t?n(t).getAlpha():0},a.addOpacity=function(t,e){var r=n(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},a.combine=function(t,e){var r=n(t).toRgb();if(1===r.a)return n(t).toRgbString();var i=n(e||l).toRgb(),a=1===i.a?i:{r:255*(1-i.a)+i.r*i.a,g:255*(1-i.a)+i.g*i.a,b:255*(1-i.a)+i.b*i.a},o={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return n(o).toRgbString()},a.contrast=function(t,e,r){var i=n(t);return 1!==i.getAlpha()&&(i=n(a.combine(t,l))),(i.isDark()?e?i.lighten(e):l:r?i.darken(r):s).toString()},a.stroke=function(t,e){var r=n(e);t.style({stroke:a.tinyRGB(r),"stroke-opacity":r.getAlpha()})},a.fill=function(t,e){var r=n(e);t.style({fill:a.tinyRGB(r),"fill-opacity":r.getAlpha()})},a.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,o=Object.keys(t);for(e=0;e0?T>=O:T<=O));E++)T>I&&T0?T>=O:T<=O));E++)T>S[0]&&T1){var it=Math.pow(10,Math.floor(Math.log(nt)/Math.LN10));et*=it*u.roundUp(nt/it,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&($.tick0=0)}$.dtick=et}$.domain=[Z+Y,Z+q-Y],$.setScale();var at=_._infolayer.selectAll("g."+e).data([0]);at.enter().append("g").classed(e,!0).classed(w.colorbar,!0).each(function(){var t=n.select(this);t.append("rect").classed(w.cbbg,!0),t.append("g").classed(w.cbfills,!0),t.append("g").classed(w.cblines,!0),t.append("g").classed(w.cbaxis,!0).classed(w.crisp,!0),t.append("g").classed(w.cbtitleunshift,!0).append("g").classed(w.cbtitle,!0),t.append("rect").classed(w.cboutline,!0),t.select(".cbtitle").datum(0)}),at.attr("transform","translate("+Math.round(A.l)+","+Math.round(A.t)+")");var ot=at.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(A.l)+",-"+Math.round(A.t)+")");$._axislayer=at.select(".cbaxis");var st=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var lt,ct=A.l+(r.x+H)*A.w,ut=$.titlefont.size;lt="top"===r.titleside?(1-(Z+q-Y))*A.h+A.t+3+.75*ut:(1-(Z+Y))*A.h+A.t-3-.25*ut,vt($._id+"title",{attributes:{x:ct,y:lt,"text-anchor":"start"}})}var ft,ht,dt,pt=u.syncOrAsync([o.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var e=at.select(".cbtitle"),a=e.select("text"),o=[-r.outlinewidth/2,r.outlinewidth/2],s=e.select(".h"+$._id+"title-math-group").node(),c=15.6;if(a.node()&&(c=parseInt(a.node().style.fontSize,10)*g),s?(st=d.bBox(s).height)>c&&(o[1]-=(st-c)/2):a.node()&&!a.classed(w.jsPlaceholder)&&(st=d.bBox(a.node()).height),st){if(st+=5,"top"===r.titleside)$.domain[1]-=st/A.h,o[1]*=-1;else{$.domain[0]+=st/A.h;var f=v.lineCount(a);o[1]+=(1-f)*c}e.attr("transform","translate("+o+")"),$.setScale()}}at.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(A.h*(1-$.domain[1]))+")"),$._axislayer.attr("transform","translate(0,"+Math.round(-A.t)+")");var h=at.select(".cbfills").selectAll("rect.cbfill").data(C);h.enter().append("rect").classed(w.cbfill,!0).style("stroke","none"),h.exit().remove(),h.each(function(t,e){var r=[0===e?S[0]:(C[e]+C[e-1])/2,e===C.length-1?S[1]:(C[e]+C[e+1])/2].map($.c2p).map(Math.round);e!==C.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=z(t).replace("e-",""),o=i(a).toHexString();n.select(this).attr({x:W,width:Math.max(B,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var p=at.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?L:[]);return p.enter().append("path").classed(w.cbline,!0),p.exit().remove(),p.each(function(t){n.select(this).attr("d","M"+W+","+(Math.round($.c2p(t))+r.line.width/2%1)+"h"+B).call(d.lineGroupStyle,r.line.width,P(t),r.line.dash)}),$._axislayer.selectAll("g."+$._id+"tick,path").remove(),$._pos=W+B+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),$.side="right",u.syncOrAsync([function(){return l.doTicks(t,$,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var e=$.titlefont.size,i=$._offset+$._length/2,a=A.l+($.position||0)*A.w+("right"===$.side?10+e*($.showticklabels?1:.5):-10-e*($.showticklabels?.5:0));vt("h"+$._id+"title",{avoid:{selection:n.select(t).selectAll("g."+$._id+"tick"),side:r.titleside,offsetLeft:A.l,offsetTop:0,maxShift:_.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},o.previousPromises,function(){var n=B+r.outlinewidth/2+d.bBox($._axislayer.node()).width;if((N=ot.select("text")).node()&&!N.classed(w.jsPlaceholder)){var i,a=ot.select(".h"+$._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(r.titleside)?d.bBox(a).width:d.bBox(ot.node()).right-W-A.l,n=Math.max(n,i)}var s=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,l=J-K;at.select(".cbbg").attr({x:W-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:K-G,width:Math.max(s,2),height:Math.max(l+2*G,2)}).call(p.fill,r.bgcolor).call(p.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),at.selectAll(".cboutline").attr({x:W,y:K+r.ypad+("top"===r.titleside?st:0),width:Math.max(B,2),height:Math.max(l-2*r.ypad-st,2)}).call(p.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*s;at.attr("transform","translate("+(A.l-c)+","+A.t+")"),o.autoMargin(t,e,{x:r.x,y:r.y,l:s*({right:1,center:.5}[r.xanchor]||0),r:s*({left:1,center:.5}[r.xanchor]||0),t:l*({bottom:1,middle:.5}[r.yanchor]||0),b:l*({top:1,middle:.5}[r.yanchor]||0)})}],t);if(pt&&pt.then&&(t._promises||[]).push(pt),t._context.edits.colorbarPosition)c.init({element:at.node(),gd:t,prepFn:function(){ft=at.attr("transform"),h(at)},moveFn:function(t,e){at.attr("transform",ft+" translate("+t+","+e+")"),ht=c.align(X+t/A.w,U,0,1,r.xanchor),dt=c.align(Z-e/A.h,q,0,1,r.yanchor);var n=c.getCursor(ht,dt,r.xanchor,r.yanchor);h(at,n)},doneFn:function(){h(at),void 0!==ht&&void 0!==dt&&a.restyle(t,{"colorbar.x":ht,"colorbar.y":dt},k().index)}});return pt}function mt(t,e){return u.coerce(Q,$,x,t,e)}function vt(e,r){var n,i=k();n=s.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var a={propContainer:$,propName:n,traceIndex:i.index,placeholder:_._dfltTitle.colorbar,containerGroup:at.select(".cbtitle")},o="h"===e.charAt(0)?e.substr(1):"h"+e;at.selectAll("."+o+",."+o+"-math-group").remove(),m.draw(t,e,f(a,r||{}))}_._infolayer.selectAll("g."+e).remove()}function k(){var r,n,i=e.substr(2);for(r=0;r=0?i.Reds:i.Blues,l.colorscale=m,s.reversescale&&(m=a(m)),s.colorscale=m)}},{"../../lib":724,"./flip_scale":610,"./scales":617}],606:[function(t,e,r){"use strict";var n=t("./attributes"),i=t("../../lib/extend").extendFlat;t("./scales.js");e.exports=function(t,e,r){return{color:{valType:"color",arrayOk:!0,editType:e||"style"},colorscale:i({},n.colorscale,{}),cauto:i({},n.zauto,{impliedEdits:{cmin:void 0,cmax:void 0}}),cmax:i({},n.zmax,{editType:e||n.zmax.editType,impliedEdits:{cauto:!1}}),cmin:i({},n.zmin,{editType:e||n.zmin.editType,impliedEdits:{cauto:!1}}),autocolorscale:i({},n.autocolorscale,{dflt:!1===r?r:n.autocolorscale.dflt}),reversescale:i({},n.reversescale,{})}}},{"../../lib/extend":713,"./attributes":604,"./scales.js":617}],607:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":617}],608:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,c,u){var f,h=u.prefix,d=u.cLetter,p=h.slice(0,h.length-1),m=h?i.nestedProperty(t,p).get()||{}:t,v=h?i.nestedProperty(e,p).get()||{}:e,g=m[d+"min"],y=m[d+"max"],b=m.colorscale;c(h+d+"auto",!(n(g)&&n(y)&&g=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],611:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){if(e||(e=i),!t)return e;function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return"string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e}},{"./default_scale":607,"./is_valid_scale_array":615,"./scales":617}],612:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;l4/3-s?o:s}},{}],619:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":724}],620:[function(t,e,r){"use strict";var n=t("mouse-event-offset"),i=t("has-hover"),a=t("has-passive-events"),o=t("../../plotly"),s=t("../../lib"),l=t("../../plots/cartesian/constants"),c=t("../../constants/interactions"),u=e.exports={};u.align=t("./align"),u.getCursor=t("./cursor");var f=t("./unhover");function h(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function d(t){return n(t.changedTouches?t.changedTouches[0]:t,document.body)}u.unhover=f.wrapped,u.unhoverRaw=f.raw,u.init=function(t){var e,r,n,f,p,m,v,g,y=t.gd,b=1,x=c.DBLCLICKDELAY,_=t.element;y._mouseDownTime||(y._mouseDownTime=0),_.style.pointerEvents="all",_.onmousedown=M,a?(_._ontouchstart&&_.removeEventListener("touchstart",_._ontouchstart),_._ontouchstart=M,_.addEventListener("touchstart",M,{passive:!1})):_.ontouchstart=M;var w=t.clampFn||function(t,e,r){return Math.abs(t)x&&(b=Math.max(b-1,1)),y._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(b,m),!g){var r;try{r=new MouseEvent("click",e)}catch(t){var n=d(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}v.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&o.plot(t)}(y),y._dragged=!1}else y._dragged=!1}},u.coverSlip=h},{"../../constants/interactions":701,"../../lib":724,"../../plotly":765,"../../plots/cartesian/constants":775,"./align":618,"./cursor":619,"./unhover":621,"has-hover":255,"has-passive-events":256,"mouse-event-offset":425}],621:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=t("../../lib/throttle"),a=t("../../lib/get_graph_div"),o=t("../fx/constants"),s=e.exports={};s.wrapped=function(t,e,r){(t=a(t))._fullLayout&&i.clear(t._fullLayout._uid+o.HOVERID),s.raw(t,e,r)},s.raw=function(t,e){var r=t._fullLayout,i=t._hoverdata;e||(e={}),e.target&&!1===n.triggerHandler(t,"plotly_beforehover",e)||(r._hoverlayer.selectAll("g").remove(),r._hoverlayer.selectAll("line").remove(),r._hoverlayer.selectAll("circle").remove(),t._hoverdata=void 0,e.target&&i&&t.emit("plotly_unhover",{event:e,points:i}))}},{"../../lib/events":712,"../../lib/get_graph_div":719,"../../lib/throttle":748,"../fx/constants":635}],622:[function(t,e,r){"use strict";r.dash={valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},{}],623:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("tinycolor2"),o=t("../../registry"),s=t("../color"),l=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),h=t("../../constants/alignment").LINE_SPACING,d=t("../../constants/interactions").DESELECTDIM,p=t("../../traces/scatter/subtypes"),m=t("../../traces/scatter/make_bubble_size_func"),v=e.exports={};v.font=function(t,e,r,n){c.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},v.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},v.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},v.setRect=function(t,e,r,n,i){t.call(v.setPosition,e,r).call(v.setSize,n,i)},v.translatePoint=function(t,e,r,n){var a=r.c2p(t.x),o=n.c2p(t.y);return!!(i(a)&&i(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",a).attr("y",o):e.attr("transform","translate("+a+","+o+")"),!0)},v.translatePoints=function(t,e,r){t.each(function(t){var i=n.select(this);v.translatePoint(t,i,e,r)})},v.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},v.hideOutsideRangePoints=function(t,e){if(e._hasClipOnAxisFalse){var r=e.xaxis,i=e.yaxis;t.each(function(e){var a=e[0].trace,o=a.xcalendar,s=a.ycalendar;t.selectAll(".point,.textpoint").each(function(t){v.hideOutsideRangePoint(t,n.select(this),r,i,o,s)})})}},v.crispRound=function(t,e,r){return e&&i(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},v.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,l=i||a.dash||"";s.stroke(e,n||a.color),v.dashLine(e,l,o)},v.lineGroupStyle=function(t,e,r,i){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=i||a.dash||"";n.select(this).call(s.stroke,r||a.color).call(v.dashLine,l,o)})},v.dashLine=function(t,e,r){r=+r||0,e=v.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},v.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},v.singleFillStyle=function(t){var e=(((n.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call(s.fill,e)},v.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=n.select(this);try{r.call(s.fill,e[0].trace.fillcolor)}catch(e){c.error(e,t),r.remove()}})};var g=t("./symbol_defs");v.symbolNames=[],v.symbolFuncs=[],v.symbolNeedLines={},v.symbolNoDot={},v.symbolNoFill={},v.symbolList=[],Object.keys(g).forEach(function(t){var e=g[t];v.symbolList=v.symbolList.concat([e.n,t,e.n+100,t+"-open"]),v.symbolNames[e.n]=t,v.symbolFuncs[e.n]=e.f,e.needLine&&(v.symbolNeedLines[e.n]=!0),e.noDot?v.symbolNoDot[e.n]=!0:v.symbolList=v.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(v.symbolNoFill[e.n]=!0)});var y=v.symbolNames.length,b="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function x(t,e){var r=t%100;return v.symbolFuncs[r](e)+(t>=200?b:"")}v.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=v.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=y||t>=400?0:Math.floor(Math.max(t,0))};var _={x1:1,x2:0,y1:0,y2:0},w={x1:0,x2:0,y1:1,y2:0};v.gradient=function(t,e,r,i,o,l){var u=e._fullLayout._defs.select(".gradients").selectAll("#"+r).data([i+o+l],c.identity);u.exit().remove(),u.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var t=n.select(this);"horizontal"===i?t.attr(_):"vertical"===i&&t.attr(w),t.attr("id",r);var e=a(o),c=a(l);t.append("stop").attr({offset:"0%","stop-color":s.tinyRGB(c),"stop-opacity":c.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":s.tinyRGB(e),"stop-opacity":e.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},v.initGradients=function(t){var e=t._fullLayout._defs.selectAll(".gradients").data([0]);e.enter().append("g").classed("gradients",!0),e.selectAll("linearGradient,radialGradient").remove()},v.singlePointStyle=function(t,e,r,n,i,a){var l=r.marker;!function(t,e,r,n,i,a,l,c){if(o.traceIs(r,"symbols")){var u=m(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:p.isBubble(r)?u(t.ms):(a.size||6)/2,t.mrc=e;var n=v.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,x(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var f,h,d,g=!1;if(t.so?(d=l.outlierwidth,h=l.outliercolor,f=a.outliercolor):(d=(t.mlw+1||l.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,h="mlc"in t?t.mlcc=i(t.mlc):Array.isArray(l.color)?s.defaultLine:l.color,Array.isArray(a.color)&&(f=s.defaultLine,g=!0),f="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(s.stroke,f).style({"stroke-width":(d||1)+"px",fill:"none"});else{e.style("stroke-width",d+"px");var y=a.gradient,b=t.mgt;if(b?g=!0:b=y&&y.type,b&&"none"!==b){var _=t.mgc;_?g=!0:_=y.color;var w="g"+c._fullLayout._uid+"-"+r.uid;g&&(w+="-"+t.i),e.call(v.gradient,c,w,b,f,_)}else e.call(s.fill,f);d&&e.call(s.stroke,h)}}(t,e,r,n,i,l,l.line,a)},v.pointStyle=function(t,e,r){if(t.size()){var i=e.marker,a=v.tryColorscale(i,""),o=v.tryColorscale(i,"line");t.each(function(t){v.singlePointStyle(t,n.select(this),e,a,o,r)})}},v.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=e.selected||{},i=e.unselected||{},a=e.marker||{},l=r.marker||{},c=i.marker||{},u=a.opacity,f=l.opacity,h=c.opacity,p=void 0!==f,m=void 0!==h;t.each(function(t){var e,r=n.select(this),i=t.mo,a=void 0!==i;(a||p||m)&&(t.selected?p&&(e=f):e=m?h:d*(a?i:u)),void 0!==e&&r.style("opacity",e)});var g=l.color,y=c.color;(g||y)&&t.each(function(t){var e,r=n.select(this);t.selected?g&&(e=g):y&&(e=y),e&&s.fill(r,e)});var b=l.size,_=c.size,w=void 0!==b,M=void 0!==_;o.traceIs(e,"symbols")&&(w||M)&&t.each(function(t){var e,r=n.select(this),i=t.mrc,o=t.mx||a.symbol||0;e=t.selected?w?b/2:i:M?_/2:i,r.attr("d",x(v.symbolNumber(o),e)),t.mrc2=e})}},v.tryColorscale=function(t,e){var r=e?c.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&Array.isArray(i)?l.makeColorScaleFunc(l.extractScale(n,r.cmin,r.cmax)):c.identity};var M={start:1,end:-1,middle:0,bottom:1,top:-1};function k(t,e,r,i){var a=n.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",s=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",l=i?i/.8+1:0,c=(u.lineCount(t)-1)*h+1,f=M[s]*l,d=.75*r+M[o]*l+(M[o]-1)*c*r/2;t.attr("text-anchor",s),a.attr("transform","translate("+f+","+d+")")}function A(t,e){var r=t.ts||e.textfont.size;return i(r)&&r>0?r:0}v.textPointStyle=function(t,e,r){t.each(function(t){var i=n.select(this),a=c.extractOption(t,e,"tx","text");if(a){var o=t.tp||e.textposition,s=A(t,e);i.call(v.font,t.tf||e.textfont.family,s,t.tc||e.textfont.color).text(a).call(u.convertToTspans,r).call(k,o,s,t.mrc)}else i.remove()})},v.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=e.selected||{},i=e.unselected||{};t.each(function(t){var a,o=n.select(this),l=t.tc||e.textfont.color,c=t.tp||e.textposition,u=A(t,e),f=(r.textfont||{}).color,h=(i.textfont||{}).color;t.selected?f&&(a=f):h?a=h:f||(a=s.addOpacity(l,d)),a&&s.fill(o,a),k(o,c,u,t.mrc2||t.mrc)})}};var T=.5;function E(t,e,r,i){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],c=Math.pow(a*a+o*o,T/2),u=Math.pow(s*s+l*l,T/2),f=(u*u*a-c*c*s)*i,h=(u*u*o-c*c*l)*i,d=3*u*(c+u),p=3*c*(c+u);return[[n.round(e[0]+(d&&f/d),2),n.round(e[1]+(d&&h/d),2)],[n.round(e[0]-(p&&f/p),2),n.round(e[1]-(p&&h/p),2)]]}v.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(v.savedBBoxes={},C=0),r&&(v.savedBBoxes[r]=g),C++,c.extendFlat({},g)},v.setClipUrl=function(t,e){if(e){var r="#"+e,i=n.select("base");i.size()&&i.attr("href")&&(r=window.location.href.split("#")[0]+r),t.attr("clip-path","url("+r+")")}else t.attr("clip-path",null)},v.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},v.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},v.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},v.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},v.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var z=/translate\([^)]*\)\s*$/;v.setTextPointsScale=function(t,e,r){t.each(function(){var t,i=n.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(z);t=1===e&&1===r?[]:["translate("+o+","+s+")","scale("+e+","+r+")","translate("+-o+","+-s+")"],l&&t.push(l),i.attr("transform",t.join(" "))}})}},{"../../constants/alignment":696,"../../constants/interactions":701,"../../constants/xmlns_namespaces":704,"../../lib":724,"../../lib/svg_text_utils":747,"../../registry":854,"../../traces/scatter/make_bubble_size_func":1065,"../../traces/scatter/subtypes":1070,"../color":598,"../colorscale":613,"./symbol_defs":624,d3:128,"fast-isnumeric":140,tinycolor2:526}],624:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+","+n.round(t/2,2)+"H"+e+"L0,-"+n.round(t,2)+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+",-"+n.round(t/2,2)+"H"+e+"L0,"+n.round(t,2)+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M"+n.round(t/2,2)+",-"+e+"V"+e+"L-"+n.round(t,2)+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+n.round(t/2,2)+",-"+e+"V"+e+"L"+n.round(t,2)+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(-.309*t,2);return"M"+e+","+a+"L"+r+","+n.round(.809*t,2)+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(-.309*e,2),c=n.round(.118*e,2),u=n.round(.809*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+c+"L"+o+","+u+"L0,"+n.round(.382*e,2)+"L-"+o+","+u+"L-"+a+","+c+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0,noFill:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0,noFill:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0,noFill:!0}}},{d3:128}],625:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}}},{}],626:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../registry"),a=t("../../plots/cartesian/axes"),o=t("./compute_error");function s(t,e,r,i){var s=e["error_"+i]||{},l=[];if(s.visible&&-1!==["linear","log"].indexOf(r.type)){for(var c=o(s),u=0;u0;t.each(function(t){var u,f=t[0].trace,h=f.error_x||{},d=f.error_y||{};f.ids&&(u=function(t){return t.id});var p=o.hasMarkers(f)&&f.marker.maxdisplayed>0;d.visible||h.visible||(t=[]);var m=n.select(this).selectAll("g.errorbar").data(t,u);if(m.exit().remove(),t.length){h.visible||m.selectAll("path.xerror").remove(),d.visible||m.selectAll("path.yerror").remove(),m.style("opacity",1);var v=m.enter().append("g").classed("errorbar",!0);c&&v.style("opacity",0).transition().duration(r.duration).style("opacity",1),a.setClipUrl(m,e.layerClipId),m.each(function(t){var e=n.select(this),a=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),i(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0)));void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),i(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0)));return n}(t,s,l);if(!p||t.vis){var o;if(d.visible&&i(a.x)&&i(a.yh)&&i(a.ys)){var u=d.width;o="M"+(a.x-u)+","+a.yh+"h"+2*u+"m-"+u+",0V"+a.ys,a.noYS||(o+="m-"+u+",0h"+2*u);var f=e.select("path.yerror");!f.size()?f=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0):c&&(f=f.transition().duration(r.duration).ease(r.easing)),f.attr("d",o)}if(h.visible&&i(a.y)&&i(a.xh)&&i(a.xs)){var m=(h.copy_ystyle?d:h).width;o="M"+a.xh+","+(a.y-m)+"v"+2*m+"m0,-"+m+"H"+a.xs,a.noXS||(o+="m0,-"+m+"v"+2*m);var v=e.select("path.xerror");!v.size()?v=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0):c&&(v=v.transition().duration(r.duration).ease(r.easing)),v.attr("d",o)}}})}})}},{"../../traces/scatter/subtypes":1070,"../drawing":623,d3:128,"fast-isnumeric":140}],631:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":598,d3:128}],632:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes");e.exports={hoverlabel:{bgcolor:{valType:"color",arrayOk:!0,editType:"none"},bordercolor:{valType:"color",arrayOk:!0,editType:"none"},font:n({arrayOk:!0,editType:"none"}),namelength:{valType:"integer",min:-1,arrayOk:!0,editType:"none"},editType:"calc"}}},{"../../plots/font_attributes":797}],633:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry");function a(t,e,r,i){i=i||n.identity,Array.isArray(t)&&(e[0][r]=i(t))}e.exports=function(t){var e=t.calcdata,r=t._fullLayout;function o(t){return function(e){return n.coerceHoverinfo({hoverinfo:e},{_module:t._module},r)}}for(var s=0;s=0&&r.index-1&&i.length>v&&(i=v>3?i.substr(0,v-3)+"...":i.substr(0,v))}void 0!==t.extraText&&(a+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(a+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(a+="y: "+t.yLabel+"
"),a+=(a?"z: ":"")+t.zLabel):P&&t[o+"Label"]===A?a=t[("x"===o?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(a=t.yLabel):a=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(a+=(a?"
":"")+t.text),""===a&&(""===i&&e.remove(),a=i);var b=e.select("text.nums").call(u.font,t.fontFamily||m,t.fontSize||y,t.fontColor||p).text(a).attr("data-notex",1).call(l.positionText,0,0).call(l.convertToTspans,r),x=e.select("text.name"),_=0;i&&i!==a?(x.call(u.font,t.fontFamily||m,t.fontSize||y,d).text(i).attr("data-notex",1).call(l.positionText,0,0).call(l.convertToTspans,r),_=x.node().getBoundingClientRect().width+2*M):(x.remove(),e.select("rect").remove()),e.select("path").style({fill:d,stroke:p});var k,T,E=b.node().getBoundingClientRect(),z=t.xa._offset+(t.x0+t.x1)/2,O=t.ya._offset+(t.y0+t.y1)/2,D=Math.abs(t.x1-t.x0),I=Math.abs(t.y1-t.y0),R=E.width+w+M+_;t.ty0=S-E.top,t.bx=E.width+2*M,t.by=E.height+2*M,t.anchor="start",t.txwidth=E.width,t.tx2width=_,t.offset=0,s?(t.pos=z,k=O+I/2+R<=C,T=O-I/2-R>=0,"top"!==t.idealAlign&&k||!T?k?(O+=I/2,t.anchor="start"):t.anchor="middle":(O-=I/2,t.anchor="end")):(t.pos=O,k=z+D/2+R<=L,T=z-D/2-R>=0,"left"!==t.idealAlign&&k||!T?k?(z+=D/2,t.anchor="start"):t.anchor="middle":(z-=D/2,t.anchor="end")),b.attr("text-anchor",t.anchor),_&&x.attr("text-anchor",t.anchor),e.attr("transform","translate("+z+","+O+")"+(s?"rotate("+g+")":""))}),D}function A(t,e){t.each(function(t){var r=n.select(this);if(t.del)r.remove();else{var i="end"===t.anchor?-1:1,a=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],s=o*(w+M),c=s+o*(t.txwidth+M),f=0,h=t.offset;"middle"===t.anchor&&(s-=t.tx2width/2,c-=t.tx2width/2),e&&(h*=-_,f=t.offset*x),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(i*w+f)+","+(w+h)+"v"+(t.by/2-w)+"h"+i*t.bx+"v-"+t.by+"H"+(i*w+f)+"V"+(h-w)+"Z"),a.call(l.positionText,s+f,h+t.ty0-t.by/2+M),t.tx2width&&(r.select("text.name").call(l.positionText,c+o*M+f,h+t.ty0-t.by/2+M),r.select("rect").call(u.setRect,c+(o-1)*t.tx2width/2+f,h-t.by/2-1,t.tx2width,t.by+2))}})}function T(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},s=Array.isArray(r)?function(t,e){return o.castOption(i,r,t)||o.extractOption({},n,"",e)}:function(t,e){return o.extractOption(a,n,t,e)};function l(e,r,n){var i=s(r,n);i&&(t[e]=i)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?(t.x0+t.x1)/2:(t.y0+t.y1)/2,t.x0=o.constrain(t.x0,0,t.xa._length),t.x1=o.constrain(t.x1,0,t.xa._length),t.y0=o.constrain(t.y0,0,t.ya._length),t.y1=o.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:d.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:d.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var c=d.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+c+" / -"+d.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+c,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=d.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+d.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var f=t.hoverinfo||t.trace.hoverinfo;return"all"!==f&&(-1===(f=Array.isArray(f)?f:f.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===f.indexOf("y")&&(t.yLabel=void 0),-1===f.indexOf("z")&&(t.zLabel=void 0),-1===f.indexOf("text")&&(t.text=void 0),-1===f.indexOf("name")&&(t.name=void 0)),t}function E(t,e){var r,n,i=e.container,o=e.fullLayout,s=e.event,l=!!t.hLinePoint,c=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),c||l){var h=f.combine(o.plot_bgcolor,o.paper_bgcolor);if(l){var d,p,m=t.hLinePoint;r=m&&m.xa,"cursor"===(n=m&&m.ya).spikesnap?(d=s.pointerX,p=s.pointerY):(d=r._offset+(m.x0+m.x1)/2,p=n._offset+(m.y0+m.y1)/2);var v,g,y=a.readability(m.color,h)<1.5?f.contrast(h):m.color,b=n.spikemode,x=n.spikethickness,_=n.spikecolor||y,w=n._boundingBox,M=(w.left+w.right)/2et.width||$<0||$>et.height)return h.unhoverRaw(t,e);e.pointerX=e.offsetX,e.pointerY=e.offsetY}if(D="xval"in e?m.flat(l,e.xval):m.p2c(_,Q),I="yval"in e?m.flat(l,e.yval):m.p2c(w,$),!i(D[0])||!i(I[0]))return o.warn("Fx.hover failed",e,t),h.unhoverRaw(t,e)}var rt=1/0;for(N=0;NY&&(Z.splice(0,Y),rt=Z[0].distance),u._has("cartesian")&&0!==X&&0===Z.length){G.distance=X,G.index=!1;var st=j._module.hoverPoints(G,q,H,"closest",u._hoverlayer);if(st){var lt,ct=st.filter(function(t){return t.xa.showspikes});if(ct.length){var ut=ct[0];i(ut.x0)&&i(ut.y0)&&(lt=pt(ut),(!K.vLinePoint||K.vLinePoint.distance>lt.distance)&&(K.vLinePoint=lt))}var ft=st.filter(function(t){return t.ya.showspikes});if(ft.length){var ht=ft[0];i(ht.x0)&&i(ht.y0)&&(lt=pt(ht),(!K.hLinePoint||K.hLinePoint.distance>lt.distance)&&(K.hLinePoint=lt))}}}}function dt(t,e){if(!t.length)return null;var r=t.map(function(t,e){var r=t.xa,n=t.ya,i=r.c2p(q),a=n.c2p(H),o=function(t){var e=t.kink,r=(t.x1+t.x0)/2-i,n=(t.y1+t.y0)/2-a;return Math.max(Math.sqrt(r*r+n*n)-e,1-3/e)}(t);return{distance:o,index:e}});return r=r.filter(function(t){return t.distance<=e}).sort(function(t,e){return t.distance-e.distance}),r.length?t[r[0].index]:null}function pt(t){return t?{xa:t.xa,ya:t.ya,x0:t.x0,x1:t.x1,y0:t.y0,y1:t.y1,distance:t.distance,curveNumber:t.trace.index,color:t.color,pointNumber:t.index}:null}var mt={fullLayout:u,container:u._hoverlayer,outerContainer:u._paperdiv,event:e},vt=t._spikepoints,gt={vLinePoint:K.vLinePoint,hLinePoint:K.hLinePoint};if(t._spikepoints=gt,u._has("cartesian")&&0!==X&&0!==Z.length){var yt=Z.filter(function(t){return t.ya.showspikes}),bt=dt(yt,X);K.hLinePoint=pt(bt);var xt=Z.filter(function(t){return t.xa.showspikes}),_t=dt(xt,X);K.vLinePoint=pt(_t)}if(0===Z.length){var wt=h.unhoverRaw(t,e);return!u._has("cartesian")||null===K.hLinePoint&&null===K.vLinePoint||S(vt)&&E(K,mt),wt}u._has("cartesian")&&S(vt)&&E(K,mt);Z.sort(function(t,e){return t.distance-e.distance});var Mt=t._hoverdata,kt=[];for(R=0;R1,Et=f.combine(u.plot_bgcolor||f.background,u.paper_bgcolor),St={hovermode:O,rotateLabels:Tt,bgColor:Et,container:u._hoverlayer,outerContainer:u._paperdiv,commonLabelOpts:u.hoverlabel,hoverdistance:u.hoverdistance},Lt=k(Z,St,t);if(function(t,e,r){var n,i,a,o,s,l,c,u=0,f=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?b:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function h(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var c=0;for(o=0;oe.pmax&&c++;for(o=t.length-1;o>=0&&!(c<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,c--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(c<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,c--)}}}for(;!n&&u<=t.length;){for(u++,n=!0,o=0;o.01&&m.pmin===v.pmin&&m.pmax===v.pmax){for(s=p.length-1;s>=0;s--)p[s].dp+=i;for(d.push.apply(d,p),f.splice(o+1,1),c=0,s=d.length-1;s>=0;s--)c+=d[s].dp;for(a=c/d.length,s=d.length-1;s>=0;s--)d[s].dp-=a;n=!1}else o++}f.forEach(h)}for(o=f.length-1;o>=0;o--){var g=f[o];for(s=g.length-1;s>=0;s--){var y=g[s],x=t[y.i];x.offset=y.dp,x.del=y.del}}}(Z,Tt?"xa":"ya",u),A(Lt,Tt),e.target&&e.target.tagName){var Ct=p.getComponentMethod("annotations","hasClickToShow")(t,kt);c(n.select(e.target),Ct?"pointer":"")}if(!e.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(t,0,Mt))return;Mt&&t.emit("plotly_unhover",{event:e,points:Mt});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:_,yaxes:w,xvals:D,yvals:I})}(t,e,r,a)})},r.loneHover=function(t,e){var r={color:t.color||f.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=n.select(e.container),a=e.outerContainer?n.select(e.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||f.background,container:i,outerContainer:a,hoverdistance:v.MAXDIST},s=k([r],o,e.gd);return A(s,o.rotateLabels),s.node()}},{"../../lib":724,"../../lib/events":712,"../../lib/override_cursor":735,"../../lib/svg_text_utils":747,"../../plots/cartesian/axes":770,"../../registry":854,"../color":598,"../dragelement":620,"../drawing":623,"./constants":635,"./helpers":637,d3:128,"fast-isnumeric":140,tinycolor2:526}],639:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,i){r("hoverlabel.bgcolor",(i=i||{}).bgcolor),r("hoverlabel.bordercolor",i.bordercolor),r("hoverlabel.namelength",i.namelength),n.coerceFont(r,"hoverlabel.font",i.font)}},{"../../lib":724}],640:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../dragelement"),o=t("./helpers"),s=t("./layout_attributes");e.exports={moduleType:"component",name:"fx",constants:t("./constants"),schema:{layout:s},attributes:t("./attributes"),layoutAttributes:s,supplyLayoutGlobalDefaults:t("./layout_global_defaults"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),getDistanceFunction:o.getDistanceFunction,getClosest:o.getClosest,inbox:o.inbox,quadrature:o.quadrature,appendArrayPointValue:o.appendArrayPointValue,castHoverOption:function(t,e,r){return i.castOption(t,e,"hoverlabel."+r)},castHoverinfo:function(t,e,r){return i.castOption(t,r,"hoverinfo",function(r){return i.coerceHoverinfo({hoverinfo:r},{_module:t._module},e)})},hover:t("./hover").hover,unhover:a.unhover,loneHover:t("./hover").loneHover,loneUnhover:function(t){var e=i.isD3Selection(t)?t:n.select(t);e.selectAll("g.hovertext").remove(),e.selectAll(".spikeline").remove()},click:t("./click")}},{"../../lib":724,"../dragelement":620,"./attributes":632,"./calc":633,"./click":634,"./constants":635,"./defaults":636,"./helpers":637,"./hover":638,"./layout_attributes":641,"./layout_defaults":642,"./layout_global_defaults":643,d3:128}],641:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../plots/font_attributes")({editType:"none"});i.family.dflt=n.HOVERFONT,i.size.dflt=n.HOVERFONTSIZE,e.exports={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:i,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}}},{"../../plots/font_attributes":797,"./constants":635}],642:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e,r){function a(r,a){return n.coerce(t,e,i,r,a)}var o;a("dragmode"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],650:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes");e.exports={bgcolor:{valType:"color",editType:"legend"},bordercolor:{valType:"color",dflt:i.defaultLine,editType:"legend"},borderwidth:{valType:"number",min:0,dflt:0,editType:"legend"},font:n({editType:"legend"}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v",editType:"legend"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"],editType:"legend"},tracegroupgap:{valType:"number",min:0,dflt:10,editType:"legend"},x:{valType:"number",min:-2,max:3,dflt:1.02,editType:"legend"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"legend"},y:{valType:"number",min:-2,max:3,dflt:1,editType:"legend"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"legend"},editType:"legend"}},{"../../plots/font_attributes":797,"../color/attributes":597}],651:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],652:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("./attributes"),o=t("../../plots/layout_attributes"),s=t("./helpers");e.exports=function(t,e,r){for(var l,c,u,f,h=t.legend||{},d={},p=0,m="normal",v=0;v1)){if(e.legend=d,y("bgcolor",e.paper_bgcolor),y("bordercolor"),y("borderwidth"),i.coerceFont(y,"font",e.font),y("orientation"),"h"===d.orientation){var b=t.xaxis;b&&b.rangeslider&&b.rangeslider.visible?(l=0,u="left",c=1.1,f="bottom"):(l=0,u="left",c=-.1,f="top")}y("traceorder",m),s.isGrouped(e.legend)&&y("tracegroupgap"),y("x",l),y("xanchor",u),y("y",c),y("yanchor",f),i.noneOrAll(h,d,["x","y"])}}},{"../../lib":724,"../../plots/layout_attributes":824,"../../registry":854,"./attributes":650,"./helpers":656}],653:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plotly"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../registry"),l=t("../dragelement"),c=t("../drawing"),u=t("../color"),f=t("../../lib/svg_text_utils"),h=t("./handle_click"),d=t("./constants"),p=t("../../constants/interactions"),m=t("../../constants/alignment"),v=m.LINE_SPACING,g=m.FROM_TL,y=m.FROM_BR,b=t("./get_legend_data"),x=t("./style"),_=t("./helpers"),w=t("./anchor_utils"),M=p.DBLCLICKDELAY;function k(t,e){var r=t.data()[0][0],n=e._fullLayout,o=r.trace,l=s.traceIs(o,"pie"),u=o.index,h=l?r.label:o.name,d=t.selectAll("text.legendtext").data([0]);function p(r){f.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*v;if(o){var l=c.bBox(o);n=l.height,i=l.width,c.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),h=f.lineCount(u),d=u.node();n=s*h,i=d?c.bBox(d).width:0;var p=s*(.3+(1-h)/2);f.positionText(u,40,p)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}d.enter().append("text").classed("legendtext",!0),d.attr("text-anchor","start").classed("user-select-none",!0).call(c.font,n.legend.font).text(h),e._context.edits.legendText&&!l?d.call(f.makeEditable,{gd:e}).call(p).on("edit",function(t){this.text(t).call(p);var n,o=t;this.text()||(t=" ");var l=r.trace._fullInput||{},c={};if(-1!==["ohlc","candlestick"].indexOf(l.type))c[(n=r.trace.transforms)[n.length-1].direction+".name"]=t;else if(s.hasTransform(l,"groupby")){var f=s.getTransformIndices(l,"groupby"),h=f[f.length-1],d=a.keyedContainer(l,"transforms["+h+"].styles","target","value.name");""===o?d.remove(r.trace._group):d.set(r.trace._group,t),c=d.constructUpdate()}else c.name=t;return i.restyle(e,c,u)}):d.call(p)}function A(t,e){var r,n=1,i=t.selectAll("rect").data([0]);i.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(u.fill,"rgba(0,0,0,0)"),i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeM&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){h(t,e,n)},M):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,h(t,e,n))}})}function T(t,e,r){var i=t._fullLayout,a=i.legend,o=a.borderwidth,s=_.isGrouped(a),l=0;if(a._width=0,a._height=0,_.isVertical(a))s&&e.each(function(t,e){c.setTranslate(this,0,e*a.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;c.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],f=e.data(),h=0,d=f.length;ho+w-M,r.each(function(t){var e=t[0],r=v?40+t[0].width:b;o+x+M+r>i.width-(i.margin.r+i.margin.l)&&(x=0,g+=y,a._height=a._height+y,y=0),c.setTranslate(this,o+x,5+o+e.height/2+g),a._width+=M+r,a._height=Math.max(a._height,e.height),x+=M+r,y=Math.max(e.height,y)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),r.each(function(e){var r=e[0];n.select(this).select(".legendtoggle").call(c.setRect,0,-r.height/2,(t._context.edits.legendText?0:a._width)+l,r.height)})}function E(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");var n="top";w.isBottomAnchor(e)?n="bottom":w.isMiddleAnchor(e)&&(n="middle"),o.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*g[r],r:e._width*y[r],b:e._height*y[n],t:e._height*g[n]})}e.exports=function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var f=e.legend,p=e.showlegend&&b(t.calcdata,f),m=e.hiddenlabels||[];if(!e.showlegend||!p.length)return e._infolayer.selectAll(".legend").remove(),e._topdefs.select("#"+r).remove(),void o.autoMargin(t,"legend");var v=e._infolayer.selectAll("g.legend").data([0]);v.enter().append("g").attr({class:"legend","pointer-events":"all"});var _=e._topdefs.selectAll("#"+r).data([0]);_.enter().append("clipPath").attr("id",r).append("rect");var S=v.selectAll("rect.bg").data([0]);S.enter().append("rect").attr({class:"bg","shape-rendering":"crispEdges"}),S.call(u.stroke,f.bordercolor),S.call(u.fill,f.bgcolor),S.style("stroke-width",f.borderwidth+"px");var L=v.selectAll("g.scrollbox").data([0]);L.enter().append("g").attr("class","scrollbox");var C=v.selectAll("rect.scrollbar").data([0]);C.enter().append("rect").attr({class:"scrollbar",rx:20,ry:2,width:0,height:0}).call(u.fill,"#808BA4");var P=L.selectAll("g.groups").data(p);P.enter().append("g").attr("class","groups"),P.exit().remove();var z=P.selectAll("g.traces").data(a.identity);z.enter().append("g").attr("class","traces"),z.exit().remove(),z.call(x,t).style("opacity",function(t){var e=t[0].trace;return s.traceIs(e,"pie")?-1!==m.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){n.select(this).call(k,t).call(A,t)});var O=0!==v.enter().size();O&&(T(t,P,z),E(t));var D=e.width,I=e.height;T(t,P,z),f._height>I?function(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");o.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*g[r],r:e._width*y[r],b:0,t:0})}(t):E(t);var R=e._size,N=R.l+R.w*f.x,F=R.t+R.h*(1-f.y);w.isRightAnchor(f)?N-=f._width:w.isCenterAnchor(f)&&(N-=f._width/2),w.isBottomAnchor(f)?F-=f._height:w.isMiddleAnchor(f)&&(F-=f._height/2);var j=f._width,B=R.w;j>B?(N=R.l,j=B):(N+j>D&&(N=D-j),N<0&&(N=0),j=Math.min(D-N,f._width));var U=f._height,V=R.h;U>V?(F=R.t,U=V):(F+U>I&&(F=I-U),F<0&&(F=0),U=Math.min(I-F,f._height)),c.setTranslate(v,N,F);var q,H,G,Y,W,X,Z=U-d.scrollBarHeight-2*d.scrollBarMargin,J=f._height-U;if(f._height<=U||t._context.staticPlot)S.attr({width:j-f.borderwidth,height:U-f.borderwidth,x:f.borderwidth/2,y:f.borderwidth/2}),c.setTranslate(L,0,0),_.select("rect").attr({width:j-2*f.borderwidth,height:U-2*f.borderwidth,x:f.borderwidth,y:f.borderwidth}),L.call(c.setClipUrl,r);else{q=d.scrollBarMargin,H=L.attr("data-scroll")||0,S.attr({width:j-2*f.borderwidth+d.scrollBarWidth+d.scrollBarMargin,height:U-f.borderwidth,x:f.borderwidth/2,y:f.borderwidth/2}),_.select("rect").attr({width:j-2*f.borderwidth+d.scrollBarWidth+d.scrollBarMargin,height:U-2*f.borderwidth,x:f.borderwidth,y:f.borderwidth-H}),L.call(c.setClipUrl,r),O&&Q(q,H),v.on("wheel",null),v.on("wheel",function(){H=a.constrain(L.attr("data-scroll")-n.event.deltaY/Z*J,-J,0),Q(q=d.scrollBarMargin-H/J*Z,H),0!==H&&H!==-J&&n.event.preventDefault()}),C.on(".drag",null),L.on(".drag",null);var K=n.behavior.drag().on("drag",function(){q=a.constrain(n.event.y-d.scrollBarHeight/2,d.scrollBarMargin,d.scrollBarMargin+Z),H=-(q-d.scrollBarMargin)/Z*J,Q(q,H)});C.call(K),L.call(K)}if(t._context.edits.legendPosition)v.classed("cursor-move",!0),l.init({element:v.node(),gd:t,prepFn:function(){var t=c.getTranslate(v);W=t.x,X=t.y},moveFn:function(t,e){var r=W+t,n=X+e;c.setTranslate(v,r,n),G=l.align(r,0,R.l,R.l+R.w,f.xanchor),Y=l.align(n,0,R.t+R.h,R.t,f.yanchor)},doneFn:function(){void 0!==G&&void 0!==Y&&i.relayout(t,{"legend.x":G,"legend.y":Y})},clickFn:function(r,n){var i=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===r?v._clickTimeout=setTimeout(function(){h(i,t,r)},M):2===r&&(v._clickTimeout&&clearTimeout(v._clickTimeout),h(i,t,r)))}})}function Q(t,e){L.attr("data-scroll",e).call(c.setTranslate,0,e),C.call(c.setRect,j,t,d.scrollBarWidth,d.scrollBarHeight),_.select("rect").attr({y:f.borderwidth-e})}}},{"../../constants/alignment":696,"../../constants/interactions":701,"../../lib":724,"../../lib/svg_text_utils":747,"../../plotly":765,"../../plots/plots":833,"../../registry":854,"../color":598,"../dragelement":620,"../drawing":623,"./anchor_utils":649,"./constants":651,"./get_legend_data":654,"./handle_click":655,"./helpers":656,"./style":658,d3:128}],654:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("./helpers");e.exports=function(t,e){var r,a,o={},s=[],l=!1,c={},u=0;function f(t,r){if(""!==t&&i.isGrouped(e))-1===s.indexOf(t)?(s.push(t),l=!0,o[t]=[[r]]):o[t].push([r]);else{var n="~~i"+u;s.push(n),o[n]=[[r]],u++}}for(r=0;rr[1])return r[1]}return i}function p(t){return t[0]}if(u||f||h){var m={},v={};u&&(m.mc=d("marker.color",p),m.mo=d("marker.opacity",a.mean,[.2,1]),m.ms=d("marker.size",a.mean,[2,16]),m.mlc=d("marker.line.color",p),m.mlw=d("marker.line.width",a.mean,[0,5]),v.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(v.line={width:d("line.width",p,[0,10])}),f&&(m.tx="Aa",m.tp=d("textposition",p),m.ts=10,m.tc=d("textfont.color",p),m.tf=d("textfont.family",p)),r=[a.minExtend(s,m)],i=a.minExtend(c,v)}var g=n.select(this).select("g.legendpoints"),y=g.selectAll("path.scatterpts").data(u?r:[]);y.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),y.exit().remove(),y.call(o.pointStyle,i,e),u&&(r[0].mrc=3);var b=g.selectAll("g.pointtext").data(f?r:[]);b.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),b.exit().remove(),b.selectAll("text").call(o.textPointStyle,i,e)})}},{"../../lib":724,"../../registry":854,"../../traces/pie/style_one":1034,"../../traces/scatter/subtypes":1070,"../color":598,"../drawing":623,d3:128}],659:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axis_ids"),o=t("../../lib"),s=t("../../snapshot/download"),l=t("../../../build/ploticon"),c=o._,u=e.exports={};function f(t,e){var r,i,o=e.currentTarget,s=o.getAttribute("data-attr"),l=o.getAttribute("data-val")||!0,c=t._fullLayout,u={},f=a.list(t,null,!0),h="on";if("zoom"===s){var d,p="in"===l?.5:2,m=(1+p)/2,v=(1-p)/2;for(i=0;i1?(_=["toggleHover"],w=["resetViews"]):f?(x=["zoomInGeo","zoomOutGeo"],_=["hoverClosestGeo"],w=["resetGeo"]):u?(_=["hoverClosest3d"],w=["resetCameraDefault3d","resetCameraLastSave3d"]):m?(_=["toggleHover"],w=["resetViewMapbox"]):_=d?["hoverClosestGl2d"]:h?["hoverClosestPie"]:["toggleHover"];c&&(_=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]);!c&&!d||g||(x=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==w[0]&&(w=["resetScale2d"]));u?M=["zoom3d","pan3d","orbitRotation","tableRotation"]:(c||d)&&!g||p?M=["zoom2d","pan2d"]:m||f?M=["pan2d"]:v&&(M=["zoom2d"]);(function(t){for(var e=!1,r=0;r0)){var d=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;ad&&(d=f)));return d>=h?[h,d]:void 0}}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var o=0;oU&&n>V&&!t.shiftKey?l.getCursor(i/r,1-a/n):"move";c(e,o),B=o.split("-")[0]}function Y(n,i){if("path"===r.type){var a=function(t){return F(R(t)+n)};D&&"date"===D.type&&(a=f.encodeDate(a));var l=function(t){return j(N(t)+i)};I&&"date"===I.type&&(l=f.encodeDate(l)),r.path=p(z,a,l),o[O]=r.path}else o[v]=r.x0=F(s+n),o[g]=r.y0=j(u+i),o[y]=r.x1=F(h+n),o[b]=r.y1=j(m+i);e.attr("d",d(t,r))}function W(n,i){if("path"===r.type){var a=function(t){return F(R(t)+n)};D&&"date"===D.type&&(a=f.encodeDate(a));var s=function(t){return j(N(t)+i)};I&&"date"===I.type&&(s=f.encodeDate(s)),r.path=p(z,a,s),o[O]=r.path}else{var l=~B.indexOf("n")?x+i:x,c=~B.indexOf("s")?_+i:_,u=~B.indexOf("w")?w+n:w,h=~B.indexOf("e")?M+n:M;c-l>V&&(o[k]=r[S]=j(l),o[A]=r[L]=j(c)),h-u>U&&(o[T]=r[C]=F(u),o[E]=r[P]=F(h))}e.attr("d",d(t,r))}l.init(q),e.node().onmousemove=G}(t,m,i,e)}}function d(t,e){var r,n,o,s,l=e.type,c=a.getFromId(t,e.xref),h=a.getFromId(t,e.yref),d=t._fullLayout._size;if(c?(r=f.shapePositionToRange(c),n=function(t){return c._offset+c.r2p(r(t,!0))}):n=function(t){return d.l+d.w*t},h?(o=f.shapePositionToRange(h),s=function(t){return h._offset+h.r2p(o(t,!0))}):s=function(t){return d.t+d.h*(1-t)},"path"===l)return c&&"date"===c.type&&(n=f.decodeDate(n)),h&&"date"===h.type&&(s=f.decodeDate(s)),function(t,e,r){return t.replace(u.segmentRE,function(t){var n=0,a=t.charAt(0),o=u.paramIsX[a],s=u.paramIsY[a],l=u.numParams[a],c=t.substr(1).replace(u.paramRE,function(t){return o[n]?t=e(t):s[n]&&(t=r(t)),++n>l&&(t="X"),t});return n>l&&(c=c.replace(/[\s,]*X.*/,""),i.log("Ignoring extra params in segment "+t)),a+c})}(e.path,n,s);var p=n(e.x0),m=n(e.x1),v=s(e.y0),g=s(e.y1);if("line"===l)return"M"+p+","+v+"L"+m+","+g;if("rect"===l)return"M"+p+","+v+"H"+m+"V"+g+"H"+p+"Z";var y=(p+m)/2,b=(v+g)/2,x=Math.abs(y-p),_=Math.abs(b-v),w="A"+x+","+_,M=y+x+","+b;return"M"+M+w+" 0 1,1 "+(y+","+(b-_))+w+" 0 0,1 "+M+"Z"}function p(t,e,r){return t.replace(u.segmentRE,function(t){var n=0,i=t.charAt(0),a=u.paramIsX[i],o=u.paramIsY[i],s=u.numParams[i];return i+t.substr(1).replace(u.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}e.exports={draw:function(t){var e=t._fullLayout;e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._shapeSubplotLayers.selectAll("path").remove();for(var r=0;r0)&&(i("active"),i("x"),i("y"),n.noneOrAll(t,e,["x","y"]),i("xanchor"),i("yanchor"),i("len"),i("lenmode"),i("pad.t"),i("pad.r"),i("pad.b"),i("pad.l"),n.coerceFont(i,"font",r.font),i("currentvalue.visible")&&(i("currentvalue.xanchor"),i("currentvalue.prefix"),i("currentvalue.suffix"),i("currentvalue.offset"),n.coerceFont(i,"currentvalue.font",e.font)),i("transition.duration"),i("transition.easing"),i("bgcolor"),i("activebgcolor"),i("bordercolor"),i("borderwidth"),i("ticklen"),i("tickwidth"),i("tickcolor"),i("minorticklen"))}e.exports=function(t,e){i(t,e,{name:o,handleItemDefaults:l})}},{"../../lib":724,"../../plots/array_container_defaults":767,"./attributes":684,"./constants":685}],687:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/plots"),a=t("../color"),o=t("../drawing"),s=t("../../lib/svg_text_utils"),l=t("../legend/anchor_utils"),c=t("./constants"),u=t("../../constants/alignment"),f=u.LINE_SPACING,h=u.FROM_TL,d=u.FROM_BR;function p(t){return t._index}function m(t,e){var r=o.tester.selectAll("g."+c.labelGroupClass).data(e.steps);r.enter().append("g").classed(c.labelGroupClass,!0);var a=0,u=0;r.each(function(t){var r=y(n.select(this),{step:t},e).node();if(r){var i=o.bBox(r);u=Math.max(u,i.height),a=Math.max(a,i.width)}}),r.remove();var f=e._dims={};f.inputAreaWidth=Math.max(c.railWidth,c.gripHeight);var p=t._fullLayout._size;f.lx=p.l+p.w*e.x,f.ly=p.t+p.h*(1-e.y),"fraction"===e.lenmode?f.outerLength=Math.round(p.w*e.len):f.outerLength=e.len,f.inputAreaStart=0,f.inputAreaLength=Math.round(f.outerLength-e.pad.l-e.pad.r);var m=(f.inputAreaLength-2*c.stepInset)/(e.steps.length-1),g=a+c.labelPadding;if(f.labelStride=Math.max(1,Math.ceil(g/m)),f.labelHeight=u,f.currentValueMaxWidth=0,f.currentValueHeight=0,f.currentValueTotalHeight=0,f.currentValueMaxLines=1,e.currentvalue.visible){var b=o.tester.append("g");r.each(function(t){var r=v(b,e,t.label),n=r.node()&&o.bBox(r.node())||{width:0,height:0},i=s.lineCount(r);f.currentValueMaxWidth=Math.max(f.currentValueMaxWidth,Math.ceil(n.width)),f.currentValueHeight=Math.max(f.currentValueHeight,Math.ceil(n.height)),f.currentValueMaxLines=Math.max(f.currentValueMaxLines,i)}),f.currentValueTotalHeight=f.currentValueHeight+e.currentvalue.offset,b.remove()}f.height=f.currentValueTotalHeight+c.tickOffset+e.ticklen+c.labelOffset+f.labelHeight+e.pad.t+e.pad.b;var x="left";l.isRightAnchor(e)&&(f.lx-=f.outerLength,x="right"),l.isCenterAnchor(e)&&(f.lx-=f.outerLength/2,x="center");var _="top";l.isBottomAnchor(e)&&(f.ly-=f.height,_="bottom"),l.isMiddleAnchor(e)&&(f.ly-=f.height/2,_="middle"),f.outerLength=Math.ceil(f.outerLength),f.height=Math.ceil(f.height),f.lx=Math.round(f.lx),f.ly=Math.round(f.ly),i.autoMargin(t,c.autoMarginIdRoot+e._index,{x:e.x,y:e.y,l:f.outerLength*h[x],r:f.outerLength*d[x],b:f.height*d[_],t:f.height*h[_]})}function v(t,e,r){if(e.currentvalue.visible){var n,i,a=t.selectAll("text").data([0]),l=e._dims;switch(e.currentvalue.xanchor){case"right":n=l.inputAreaLength-c.currentValueInset-l.currentValueMaxWidth,i="left";break;case"center":n=.5*l.inputAreaLength,i="middle";break;default:n=c.currentValueInset,i="left"}a.enter().append("text").classed(c.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1});var u=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)u+=r;else u+=e.steps[e.active].label;e.currentvalue.suffix&&(u+=e.currentvalue.suffix),a.call(o.font,e.currentvalue.font).text(u).call(s.convertToTspans,e._gd);var h=s.lineCount(a),d=(l.currentValueMaxLines+1-h)*e.currentvalue.font.size*f;return s.positionText(a,n,d),a}}function g(t,e,r){var n=t.selectAll("rect."+c.gripRectClass).data([0]);n.enter().append("rect").classed(c.gripRectClass,!0).call(w,e,t,r).style("pointer-events","all"),n.attr({width:c.gripWidth,height:c.gripHeight,rx:c.gripRadius,ry:c.gripRadius}).call(a.stroke,r.bordercolor).call(a.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function y(t,e,r){var n=t.selectAll("text").data([0]);return n.enter().append("text").classed(c.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(o.font,r.font).text(e.step.label).call(s.convertToTspans,r._gd),n}function b(t,e){var r=t.selectAll("g."+c.labelsClass).data([0]),i=e._dims;r.enter().append("g").classed(c.labelsClass,!0);var a=r.selectAll("g."+c.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(c.labelGroupClass,!0),a.exit().remove(),a.each(function(t){var r=n.select(this);r.call(y,t,e),o.setTranslate(r,A(e,t.fraction),c.tickOffset+e.ticklen+e.font.size*f+c.labelOffset+i.currentValueTotalHeight)})}function x(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&_(t,e,r,a,!0,i)}function _(t,e,r,n,a,o){var s=r.active;r._input.active=r.active=n;var l=r.steps[r.active];e.call(k,r,r.active/(r.steps.length-1),o),e.call(v,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:s}),l&&l.method&&a&&(e._nextMethod?(e._nextMethod.step=l,e._nextMethod.doCallback=a,e._nextMethod.doTransition=o):(e._nextMethod={step:l,doCallback:a,doTransition:o},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&i.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function w(t,e,r){var i=r.node(),o=n.select(e);function s(){return r.data()[0]}t.on("mousedown",function(){var t=s();e.emit("plotly_sliderstart",{slider:t});var l=r.select("."+c.gripRectClass);n.event.stopPropagation(),n.event.preventDefault(),l.call(a.fill,t.activebgcolor);var u=T(t,n.mouse(i)[0]);x(e,r,t,u,!0),t._dragging=!0,o.on("mousemove",function(){var t=s(),a=T(t,n.mouse(i)[0]);x(e,r,t,a,!1)}),o.on("mouseup",function(){var t=s();t._dragging=!1,l.call(a.fill,t.bgcolor),o.on("mouseup",null),o.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function M(t,e){var r=t.selectAll("rect."+c.tickRectClass).data(e.steps),i=e._dims;r.enter().append("rect").classed(c.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var s=r%i.labelStride==0,l=n.select(this);l.attr({height:s?e.ticklen:e.minorticklen}).call(a.fill,e.tickcolor),o.setTranslate(l,A(e,r/(e.steps.length-1))-.5*e.tickwidth,(s?c.tickOffset:c.minorTickOffset)+i.currentValueTotalHeight)})}function k(t,e,r,n){var i=t.select("rect."+c.gripRectClass),a=A(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*c.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function A(t,e){var r=t._dims;return r.inputAreaStart+c.stepInset+(r.inputAreaLength-2*c.stepInset)*Math.min(1,Math.max(0,e))}function T(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-c.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*c.stepInset-2*r.inputAreaStart)))}function E(t,e,r){var n=t.selectAll("rect."+c.railTouchRectClass).data([0]),i=r._dims;n.enter().append("rect").classed(c.railTouchRectClass,!0).call(w,e,t,r).style("pointer-events","all"),n.attr({width:i.inputAreaLength,height:Math.max(i.inputAreaWidth,c.tickOffset+r.ticklen+i.labelHeight)}).call(a.fill,r.bgcolor).attr("opacity",0),o.setTranslate(n,0,i.currentValueTotalHeight)}function S(t,e){var r=t.selectAll("rect."+c.railRectClass).data([0]),n=e._dims;r.enter().append("rect").classed(c.railRectClass,!0);var i=n.inputAreaLength-2*c.railInset;r.attr({width:i,height:c.railWidth,rx:c.railRadius,ry:c.railRadius,"shape-rendering":"crispEdges"}).call(a.stroke,e.bordercolor).call(a.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),o.setTranslate(r,c.railInset,.5*(n.inputAreaWidth-c.railWidth)+n.currentValueTotalHeight)}e.exports=function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[c.name],n=[],i=0;i0?[0]:[]);if(a.enter().append("g").classed(c.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0);e.call(v,r).call(S,r).call(b,r).call(M,r).call(E,t,r).call(g,t,r);var n=r._dims;o.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(k,r,r.active/(r.steps.length-1),!1),e.call(v,r)}(t,n.select(this),e)}})}}},{"../../constants/alignment":696,"../../lib/svg_text_utils":747,"../../plots/plots":833,"../color":598,"../drawing":623,"../legend/anchor_utils":649,"./constants":685,d3:128}],688:[function(t,e,r){"use strict";var n=t("./constants");e.exports={moduleType:"component",name:n.name,layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":684,"./constants":685,"./defaults":686,"./draw":687}],689:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../plotly"),o=t("../../plots/plots"),s=t("../../lib"),l=t("../drawing"),c=t("../color"),u=t("../../lib/svg_text_utils"),f=t("../../constants/interactions"),h=/ [XY][0-9]* /;(e.exports={}).draw=function(t,e,r){var d,p=r.propContainer,m=r.propName,v=r.placeholder,g=r.traceIndex,y=r.avoid||{},b=r.attributes,x=r.transform,_=r.containerGroup,w=t._fullLayout,M=p.titlefont||{},k=M.family,A=M.size,T=M.color,E=1,S=!1,L=(p.title||"").trim();"title"===m?d="titleText":-1!==m.indexOf("axis")?d="axisTitleText":m.indexOf(!0)&&(d="colorbarTitleText");var C=t._context.edits[d];""===L?E=0:L.replace(h," % ")===v.replace(h," % ")&&(E=.2,S=!0,C||(L=""));var P=L||C;_||(_=w._infolayer.selectAll(".g-"+e).data([0])).enter().append("g").classed("g-"+e,!0);var z=_.selectAll("text").data(P?[0]:[]);if(z.enter().append("text"),z.text(L).attr("class",e),z.exit().remove(),!P)return _;function O(t){s.syncOrAsync([D,I],t)}function D(e){var r;return x?(r="",x.rotate&&(r+="rotate("+[x.rotate,b.x,b.y]+")"),x.offset&&(r+="translate(0, "+x.offset+")")):r=null,e.attr("transform",r),e.style({"font-family":k,"font-size":n.round(A,2)+"px",fill:c.rgb(T),opacity:E*c.opacity(T),"font-weight":o.fontWeight}).attr(b).call(u.convertToTspans,t),o.previousPromises(t)}function I(t){var e=n.select(t.node().parentNode);if(y&&y.selection&&y.side&&L){e.attr("transform",null);var r=0,a={left:"right",right:"left",top:"bottom",bottom:"top"}[y.side],o=-1!==["left","top"].indexOf(y.side)?-1:1,c=i(y.pad)?y.pad:2,u=l.bBox(e.node()),f={left:0,top:0,right:w.width,bottom:w.height},h=y.maxShift||(f[y.side]-u[y.side])*("left"===y.side||"top"===y.side?-1:1);if(h<0)r=h;else{var d=y.offsetLeft||0,p=y.offsetTop||0;u.left-=d,u.right-=d,u.top-=p,u.bottom-=p,y.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[y.side]-u[a])+c))}),r=Math.min(h,r)}if(r>0||h<0){var m={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[y.side];e.attr("transform","translate("+m+")")}}}return z.call(O),C&&(L?z.on(".opacity",null):(E=0,S=!0,z.text(v).on("mouseover.opacity",function(){n.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),z.call(u.makeEditable,{gd:t}).on("edit",function(e){void 0!==g?a.restyle(t,m,e,g):a.relayout(t,m,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(O)}).on("input",function(t){this.text(t||" ").call(u.positionText,b.x,b.y)})),z.classed("js-placeholder",S),_}},{"../../constants/interactions":701,"../../lib":724,"../../lib/svg_text_utils":747,"../../plotly":765,"../../plots/plots":833,"../color":598,"../drawing":623,d3:128,"fast-isnumeric":140}],690:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll,s=t("../../plots/pad_attributes");e.exports=o({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:a({},s,{}),font:n({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root")},{"../../lib/extend":713,"../../plot_api/edit_types":754,"../../plots/font_attributes":797,"../../plots/pad_attributes":832,"../color/attributes":597}],691:[function(t,e,r){"use strict";e.exports={name:"updatemenus",containerClassName:"updatemenu-container",headerGroupClassName:"updatemenu-header-group",headerClassName:"updatemenu-header",headerArrowClassName:"updatemenu-header-arrow",dropdownButtonGroupClassName:"updatemenu-dropdown-button-group",dropdownButtonClassName:"updatemenu-dropdown-button",buttonClassName:"updatemenu-button",itemRectClassName:"updatemenu-item-rect",itemTextClassName:"updatemenu-item-text",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}}},{}],692:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/array_container_defaults"),a=t("./attributes"),o=t("./constants").name,s=a.buttons;function l(t,e,r){function i(r,i){return n.coerce(t,e,a,r,i)}i("visible",function(t,e){var r,i,a=t.buttons||[],o=e.buttons=[];function l(t,e){return n.coerce(r,i,s,t,e)}for(var c=0;c0)&&(i("active"),i("direction"),i("type"),i("showactive"),i("x"),i("y"),n.noneOrAll(t,e,["x","y"]),i("xanchor"),i("yanchor"),i("pad.t"),i("pad.r"),i("pad.b"),i("pad.l"),n.coerceFont(i,"font",r.font),i("bgcolor",r.paper_bgcolor),i("bordercolor"),i("borderwidth"))}e.exports=function(t,e){i(t,e,{name:o,handleItemDefaults:l})}},{"../../lib":724,"../../plots/array_container_defaults":767,"./attributes":690,"./constants":691}],693:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/plots"),a=t("../color"),o=t("../drawing"),s=t("../../lib/svg_text_utils"),l=t("../legend/anchor_utils"),c=t("../../constants/alignment").LINE_SPACING,u=t("./constants"),f=t("./scrollbox");function h(t){return t._index}function d(t,e){return+t.attr(u.menuIndexAttrName)===e._index}function p(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?v(t,n,null,null,e):"dropdown"===e.type&&(i.attr(u.menuIndexAttrName,"-1"),m(t,n,i,a,e),s||v(t,n,i,a,e))}function m(t,e,r,n,i){var a=e.selectAll("g."+u.headerClassName).data([0]),s=i._dims;a.enter().append("g").classed(u.headerClassName,!0).style("pointer-events","all");var l=i.active,c=i.buttons[l]||u.blankHeaderOpts,f={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},h={width:s.headerWidth,height:s.headerHeight};a.call(g,i,c,t).call(k,i,f,h);var p=e.selectAll("text."+u.headerArrowClassName).data([0]);p.enter().append("text").classed(u.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(o.font,i.font).text(u.arrowSymbol[i.direction]),p.attr({x:s.headerWidth-u.arrowOffsetX+i.pad.l,y:s.headerHeight/2+u.textOffsetY+i.pad.t}),a.on("click",function(){r.call(A),r.attr(u.menuIndexAttrName,d(r,i)?-1:String(i._index)),v(t,e,r,n,i)}),a.on("mouseover",function(){a.call(_)}),a.on("mouseout",function(){a.call(w,i)}),o.setTranslate(e,s.lx,s.ly)}function v(t,e,r,a,o){r||(r=e).attr("pointer-events","all");var s=function(t){return-1==+t.attr(u.menuIndexAttrName)}(r)&&"buttons"!==o.type?[]:o.buttons,l="dropdown"===o.type?u.dropdownButtonClassName:u.buttonClassName,c=r.selectAll("g."+l).data(s),f=c.enter().append("g").classed(l,!0),h=c.exit();"dropdown"===o.type?(f.attr("opacity","0").transition().attr("opacity","1"),h.transition().attr("opacity","0").remove()):h.remove();var d=0,m=0,v=o._dims,y=-1!==["up","down"].indexOf(o.direction);"dropdown"===o.type&&(y?m=v.headerHeight+u.gapButtonHeader:d=v.headerWidth+u.gapButtonHeader),"dropdown"===o.type&&"up"===o.direction&&(m=-u.gapButtonHeader+u.gapButton-v.openHeight),"dropdown"===o.type&&"left"===o.direction&&(d=-u.gapButtonHeader+u.gapButton-v.openWidth);var b={x:v.lx+d+o.pad.l,y:v.ly+m+o.pad.t,yPad:u.gapButton,xPad:u.gapButton,index:0},M={l:b.x+o.borderwidth,t:b.y+o.borderwidth};c.each(function(s,l){var u=n.select(this);u.call(g,o,s,t).call(k,o,b),u.on("click",function(){n.event.defaultPrevented||(p(t,o,0,e,r,a,l),s.execute&&i.executeAPICommand(t,s.method,s.args),t.emit("plotly_buttonclicked",{menu:o,button:s,active:o.active}))}),u.on("mouseover",function(){u.call(_)}),u.on("mouseout",function(){u.call(w,o),c.call(x,o)})}),c.call(x,o),y?(M.w=Math.max(v.openWidth,v.headerWidth),M.h=b.y-M.t):(M.w=b.x-M.l,M.h=Math.max(v.openHeight,v.headerHeight)),M.direction=o.direction,a&&(c.size()?function(t,e,r,n,i,a){var o,s,l,c=i.direction,f="up"===c||"down"===c,h=i._dims,d=i.active;if(f)for(s=0,l=0;l0?[0]:[]);if(a.enter().append("g").classed(u.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nw,A=s.barLength+2*s.barPad,T=s.barWidth+2*s.barPad,E=p,S=v+g;S+T>c&&(S=c-T);var L=this.container.selectAll("rect.scrollbar-horizontal").data(k?[0]:[]);L.exit().on(".drag",null).remove(),L.enter().append("rect").classed("scrollbar-horizontal",!0).call(i.fill,s.barColor),k?(this.hbar=L.attr({rx:s.barRadius,ry:s.barRadius,x:E,y:S,width:A,height:T}),this._hbarXMin=E+A/2,this._hbarTranslateMax=w-A):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var C=g>M,P=s.barWidth+2*s.barPad,z=s.barLength+2*s.barPad,O=p+m,D=v;O+P>l&&(O=l-P);var I=this.container.selectAll("rect.scrollbar-vertical").data(C?[0]:[]);I.exit().on(".drag",null).remove(),I.enter().append("rect").classed("scrollbar-vertical",!0).call(i.fill,s.barColor),C?(this.vbar=I.attr({rx:s.barRadius,ry:s.barRadius,x:O,y:D,width:P,height:z}),this._vbarYMin=D+z/2,this._vbarTranslateMax=M-z):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var R=this.id,N=u-.5,F=C?f+P+.5:f+.5,j=h-.5,B=k?d+T+.5:d+.5,U=o._topdefs.selectAll("#"+R).data(k||C?[0]:[]);if(U.exit().remove(),U.enter().append("clipPath").attr("id",R).append("rect"),k||C?(this._clipRect=U.select("rect").attr({x:Math.floor(N),y:Math.floor(j),width:Math.ceil(F)-Math.floor(N),height:Math.ceil(B)-Math.floor(j)}),this.container.call(a.setClipUrl,R),this.bg.attr({x:p,y:v,width:m,height:g})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(a.setClipUrl,null),delete this._clipRect),k||C){var V=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(V);var q=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault(),n.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));k&&this.hbar.on(".drag",null).call(q),C&&this.vbar.on(".drag",null).call(q)}this.setTranslate(e,r)},s.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(a.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},s.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=n.event.dx),this.vbar&&(e-=n.event.dy),this.setTranslate(t,e)},s.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=n.event.deltaY),this.vbar&&(e+=n.event.deltaY),this.setTranslate(t,e)},s.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,i=r+this._hbarTranslateMax;t=(o.constrain(n.event.x,r,i)-r)/(i-r)*(this.position.w-this._box.w)}if(this.vbar){var a=e+this._vbarYMin,s=a+this._vbarTranslateMax;e=(o.constrain(n.event.y,a,s)-a)/(s-a)*(this.position.h-this._box.h)}this.setTranslate(t,e)},s.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=o.constrain(t||0,0,r),e=o.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(a.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(a.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var s=e/n;this.vbar.call(a.setTranslate,t,e+s*this._vbarTranslateMax)}}},{"../../lib":724,"../color":598,"../drawing":623,d3:128}],696:[function(t,e,r){"use strict";e.exports={FROM_BL:{left:0,center:.5,right:1,bottom:0,middle:.5,top:1},FROM_TL:{left:0,center:.5,right:1,bottom:1,middle:.5,top:0},FROM_BR:{left:1,center:.5,right:0,bottom:0,middle:.5,top:1},LINE_SPACING:1.3,MID_SHIFT:.35,OPPOSITE_SIDE:{left:"right",right:"left",top:"bottom",bottom:"top"}}},{}],697:[function(t,e,r){"use strict";e.exports={COMPARISON_OPS:["=","!=","<",">=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}}},{}],698:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],699:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],700:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],701:[function(t,e,r){"use strict";e.exports={SHOW_PLACEHOLDER:100,HIDE_PLACEHOLDER:1e3,DBLCLICKDELAY:300,DESELECTDIM:.2}},{}],702:[function(t,e,r){"use strict";e.exports={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"}},{}],703:[function(t,e,r){"use strict";e.exports={entityToUnicode:{mu:"\u03bc","#956":"\u03bc",amp:"&","#28":"&",lt:"<","#60":"<",gt:">","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}}},{}],704:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],705:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.34.0",t("es6-promise").polyfill(),t("../build/plotcss"),t("./fonts/mathjax_config"),r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.update=n.update,r.react=n.react,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=t("./plot_api/register"),r.toImage=t("./plot_api/to_image"),r.downloadImage=t("./snapshot/download"),r.validate=t("./plot_api/validate"),r.addFrames=n.addFrames,r.deleteFrames=n.deleteFrames,r.animate=n.animate,r.register(t("./traces/scatter")),r.register([t("./components/fx"),t("./components/legend"),t("./components/annotations"),t("./components/annotations3d"),t("./components/shapes"),t("./components/images"),t("./components/updatemenus"),t("./components/sliders"),t("./components/rangeslider"),t("./components/rangeselector")]),r.register([t("./locale-en"),t("./locale-en-us")]),r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=t("./components/fx"),r.Snapshot=t("./snapshot"),r.PlotSchema=t("./plot_api/plot_schema"),r.Queue=t("./lib/queue"),r.d3=t("d3")},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":589,"./components/annotations3d":594,"./components/fx":640,"./components/images":648,"./components/legend":657,"./components/rangeselector":669,"./components/rangeslider":675,"./components/shapes":682,"./components/sliders":688,"./components/updatemenus":694,"./fonts/mathjax_config":706,"./lib/queue":738,"./locale-en":752,"./locale-en-us":751,"./plot_api/plot_schema":759,"./plot_api/register":760,"./plot_api/set_plot_config":761,"./plot_api/to_image":763,"./plot_api/validate":764,"./plotly":765,"./snapshot":859,"./snapshot/download":856,"./traces/scatter":1060,d3:128,"es6-promise":137}],706:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],707:[function(t,e,r){"use strict";var n=Math.PI;r.deg2rad=function(t){return t/180*n},r.rad2deg=function(t){return t/n*180},r.wrap360=function(t){var e=t%360;return e<0?e+360:e},r.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t}},{}],708:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../constants/numerical").BADNUM,a=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;e.exports=function(t){return"string"==typeof t&&(t=t.replace(a,"")),n(t)?Number(t):i}},{"../constants/numerical":702,"fast-isnumeric":140}],709:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("../plots/attributes"),o=t("../components/colorscale/get_scale"),s=(Object.keys(t("../components/colorscale/scales")),t("./nested_property")),l=t("./regex").counter,c=t("../constants/interactions").DESELECTDIM,u=t("./angles").wrap180;r.valObjectMeta={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)},validateFunction:function(t,e){e.coerceNumber&&(t=+t);for(var r=e.values,n=0;ni.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return i(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?e.set(u(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r){"string"==typeof t&&l(r).test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!l(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=n&&t<=i?t:u;if("string"!=typeof t&&"number"!=typeof t)return u;t=String(t);var a=_(e),o=t.charAt(0);!a||"G"!==o&&"g"!==o||(t=t.substr(1),e="");var s=a&&"chinese"===e.substr(0,7),l=t.match(s?b:y);if(!l)return u;var c=l[1],g=l[3]||"1",w=Number(l[5]||1),M=Number(l[7]||0),k=Number(l[9]||0),A=Number(l[11]||0);if(a){if(2===c.length)return u;var T;c=Number(c);try{var E=v.getComponentMethod("calendars","getCal")(e);if(s){var S="i"===g.charAt(g.length-1);g=parseInt(g,10),T=E.newDate(c,E.toMonthIndex(c,g,S),w)}else T=E.newDate(c,Number(g),w)}catch(t){return u}return T?(T.toJD()-m)*f+M*h+k*d+A*p:u}c=2===c.length?(Number(c)+2e3-x)%100+x:Number(c),g-=1;var L=new Date(Date.UTC(2e3,g,w,M,k));return L.setUTCFullYear(c),L.getUTCMonth()!==g?u:L.getUTCDate()!==w?u:L.getTime()+A*p},n=r.MIN_MS=r.dateTime2ms("-9999"),i=r.MAX_MS=r.dateTime2ms("9999-12-31 23:59:59.9999"),r.isDateTime=function(t,e){return r.dateTime2ms(t,e)!==u};var M=90*f,k=3*h,A=5*d;function T(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+w(e,2)+":"+w(r,2),(n||i)&&(t+=":"+w(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+w(i,a)}return t}r.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=n&&t<=i))return u;e||(e=0);var a,o,s,c,y,b,x=Math.floor(10*l(t+.05,1)),w=Math.round(t-x/10);if(_(r)){var E=Math.floor(w/f)+m,S=Math.floor(l(t,f));try{a=v.getComponentMethod("calendars","getCal")(r).fromJD(E).formatDate("yyyy-mm-dd")}catch(t){a=g("G%Y-%m-%d")(new Date(w))}if("-"===a.charAt(0))for(;a.length<11;)a="-0"+a.substr(1);else for(;a.length<10;)a="0"+a;o=e=n+f&&t<=i-f))return u;var e=Math.floor(10*l(t+.05,1)),r=new Date(Math.round(t-e/10));return T(a.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},r.cleanDate=function(t,e,n){if(r.isJSDate(t)||"number"==typeof t){if(_(n))return s.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=r.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!r.isDateTime(t,n))return s.error("unrecognized date",t),e;return t};var E=/%\d?f/g;function S(t,e,r,n){t=t.replace(E,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(_(n))try{t=v.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var L=[59,59.9,59.99,59.999,59.9999];r.formatDate=function(t,e,r,n,i,a){if(i=_(i)&&i,!e)if("y"===r)e=a.year;else if("m"===r)e=a.month;else{if("d"!==r)return function(t,e){var r=l(t+.05,f),n=w(Math.floor(r/h),2)+":"+w(l(Math.floor(r/d),60),2);if("M"!==e){o(e)||(e=0);var i=(100+Math.min(l(t/p,60),L[e])).toFixed(e).substr(1);e>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+i}return n}(t,r)+"\n"+S(a.dayMonthYear,t,n,i);e=a.dayMonth+"\n"+a.year}return S(e,t,n,i)};var C=3*f;r.incrementMonth=function(t,e,r){r=_(r)&&r;var n=l(t,f);if(t=Math.round(t-n),r)try{var i=Math.round(t/f)+m,a=v.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-m)*f+n}catch(e){s.error("invalid ms "+t+" in calendar "+r)}var c=new Date(t+C);return c.setUTCMonth(c.getUTCMonth()+e)+n-C},r.findExactDates=function(t,e){for(var r,n,i=0,a=0,s=0,l=0,c=_(e)&&v.getComponentMethod("calendars","getCal")(e),u=0;u0&&(r.push(i),i=[])}return i.length>0&&r.push(i),r},r.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},r.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r1||m<0||m>1?null:{x:t+l*m,y:e+f*m}}function l(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}r.segmentsIntersect=s,r.segmentDistance=function(t,e,r,n,i,a,o,c){if(s(t,e,r,n,i,a,o,c))return 0;var u=r-t,f=n-e,h=o-i,d=c-a,p=u*u+f*f,m=h*h+d*d,v=Math.min(l(u,f,p,i-t,a-e),l(u,f,p,o-t,c-e),l(h,d,m,t-i,e-a),l(h,d,m,r-i,n-a));return Math.sqrt(v)},r.getTextLocation=function(t,e,r,s){if(t===i&&s===a||(n={},i=t,a=s),n[r])return n[r];var l=t.getPointAtLength(o(r-s/2,e)),c=t.getPointAtLength(o(r+s/2,e)),u=Math.atan((c.y-l.y)/(c.x-l.x)),f=t.getPointAtLength(o(r,e)),h={x:(4*f.x+l.x+c.x)/6,y:(4*f.y+l.y+c.y)/6,theta:u};return n[r]=h,h},r.clearLocationCache=function(){i=null},r.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,c=0,u=t.getTotalLength(),f=u;function h(e){var r=t.getPointAtLength(e);0===e?n=r:e===u&&(i=r);var c=r.xo?r.x-o:0,f=r.yl?r.y-l:0;return Math.sqrt(c*c+f*f)}for(var d=h(c);d;){if((c+=d+r)>f)return;d=h(c)}for(d=h(f);d;){if(c>(f-=d+r))return;d=h(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},r.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,c=n.iterationLimit||30,u=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,f=0,h=0,d=s;f0?d=i:h=i,f++}return a}},{"./mod":731}],719:[function(t,e,r){"use strict";e.exports=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}},{}],720:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("color-normalize"),a=t("../components/colorscale"),o=t("../components/color/attributes").defaultLine,s=i(o),l=1;function c(t,e){var r=t;return r[3]*=e,r}function u(t){if(n(t))return s;var e=i(t);return e.length?e:s}function f(t){return n(t)?t:l}e.exports=function(t,e,r){var n,o,h,d,p,m=t.color,v=Array.isArray(m),g=Array.isArray(e),y=[];if(n=void 0!==t.colorscale?a.makeColorScaleFunc(a.extractScale(t.colorscale,t.cmin,t.cmax)):u,o=v?function(t,e){return void 0===t[e]?s:i(n(t[e]))}:u,h=g?function(t,e){return void 0===t[e]?l:f(t[e])}:f,v||g)for(var b=0;b=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))}},{"../constants/string_mappings":703,"superscript-text":519}],723:[function(t,e,r){"use strict";e.exports=function(t){return t}},{}],724:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../constants/numerical"),o=a.FP_SAFE,s=a.BADNUM,l=e.exports={};l.nestedProperty=t("./nested_property"),l.keyedContainer=t("./keyed_container"),l.relativeAttr=t("./relative_attr"),l.isPlainObject=t("./is_plain_object"),l.isArray=t("./is_array"),l.mod=t("./mod"),l.toLogRange=t("./to_log_range"),l.relinkPrivateKeys=t("./relink_private"),l.ensureArray=t("./ensure_array");var c=t("./coerce");l.valObjectMeta=c.valObjectMeta,l.coerce=c.coerce,l.coerce2=c.coerce2,l.coerceFont=c.coerceFont,l.coerceHoverinfo=c.coerceHoverinfo,l.coerceSelectionMarkerOpacity=c.coerceSelectionMarkerOpacity,l.validate=c.validate;var u=t("./dates");l.dateTime2ms=u.dateTime2ms,l.isDateTime=u.isDateTime,l.ms2DateTime=u.ms2DateTime,l.ms2DateTimeLocal=u.ms2DateTimeLocal,l.cleanDate=u.cleanDate,l.isJSDate=u.isJSDate,l.formatDate=u.formatDate,l.incrementMonth=u.incrementMonth,l.dateTick0=u.dateTick0,l.dfltRange=u.dfltRange,l.findExactDates=u.findExactDates,l.MIN_MS=u.MIN_MS,l.MAX_MS=u.MAX_MS;var f=t("./search");l.findBin=f.findBin,l.sorterAsc=f.sorterAsc,l.sorterDes=f.sorterDes,l.distinctVals=f.distinctVals,l.roundUp=f.roundUp;var h=t("./stats");l.aggNums=h.aggNums,l.len=h.len,l.mean=h.mean,l.variance=h.variance,l.stdev=h.stdev,l.interp=h.interp;var d=t("./matrix");l.init2dArray=d.init2dArray,l.transposeRagged=d.transposeRagged,l.dot=d.dot,l.translationMatrix=d.translationMatrix,l.rotationMatrix=d.rotationMatrix,l.rotationXYMatrix=d.rotationXYMatrix,l.apply2DTransform=d.apply2DTransform,l.apply2DTransform2=d.apply2DTransform2;var p=t("./angles");l.deg2rad=p.deg2rad,l.rad2deg=p.rad2deg,l.wrap360=p.wrap360,l.wrap180=p.wrap180;var m=t("./geometry2d");l.segmentsIntersect=m.segmentsIntersect,l.segmentDistance=m.segmentDistance,l.getTextLocation=m.getTextLocation,l.clearLocationCache=m.clearLocationCache,l.getVisibleSegment=m.getVisibleSegment,l.findPointOnPath=m.findPointOnPath;var v=t("./extend");l.extendFlat=v.extendFlat,l.extendDeep=v.extendDeep,l.extendDeepAll=v.extendDeepAll,l.extendDeepNoArrays=v.extendDeepNoArrays;var g=t("./loggers");l.log=g.log,l.warn=g.warn,l.error=g.error;var y=t("./regex");l.counterRegex=y.counter;var b=t("./throttle");l.throttle=b.throttle,l.throttleDone=b.done,l.clearThrottle=b.clear,l.getGraphDiv=t("./get_graph_div"),l._=t("./localize"),l.notifier=t("./notifier"),l.filterUnique=t("./filter_unique"),l.filterVisible=t("./filter_visible"),l.pushUnique=t("./push_unique"),l.cleanNumber=t("./clean_number"),l.ensureNumber=function(t){return i(t)?(t=Number(t))<-o||t>o?s:i(t)?Number(t):s:s},l.noop=t("./noop"),l.identity=t("./identity"),l.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},l.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},l.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||c!==1/0&&c>=Math.pow(2,r)?t(e,r,n):s},l.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},l.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,c=new Array(l),u=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*c[n];u[r]=a}return u},l.syncOrAsync=function(t,e,r){var n;function i(){return l.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,l.promiseError);return r&&r(e)},l.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},l.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&a%1==0){var p=n?n[d]:d,m=r?r[p]:p;f(m)&&(t[m].selected=1)}}},l.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=l.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},l.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var w=/%{([^\s%{}]*)}/g,M=/^\w*$/;l.templateString=function(t,e){var r={};return t.replace(w,function(t,n){return M.test(n)?e[n]||"":(r[n]=r[n]||l.nestedProperty(e,n).get,r[n]()||"")})};l.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,c=s>=48&&s<=57;if(l&&(n=10*n+o-48),c&&(i=10*i+s-48),!l||!c){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n}},{"../constants/numerical":702,"./angles":707,"./clean_number":708,"./coerce":709,"./dates":710,"./ensure_array":711,"./extend":713,"./filter_unique":714,"./filter_visible":715,"./geometry2d":718,"./get_graph_div":719,"./identity":723,"./is_array":725,"./is_plain_object":726,"./keyed_container":727,"./localize":728,"./loggers":729,"./matrix":730,"./mod":731,"./nested_property":732,"./noop":733,"./notifier":734,"./push_unique":737,"./regex":739,"./relative_attr":740,"./relink_private":741,"./search":742,"./stats":745,"./throttle":748,"./to_log_range":749,d3:128,"fast-isnumeric":140}],725:[function(t,e,r){"use strict";var n="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer:{isView:function(){return!1}};e.exports=function(t){return Array.isArray(t)||n.isView(t)}},{}],726:[function(t,e,r){"use strict";e.exports=function(t){return window&&window.process&&window.process.versions?"[object Object]"===Object.prototype.toString.call(t):"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],727:[function(t,e,r){"use strict";var n=t("./nested_property"),i=/^\w*$/;e.exports=function(t,e,r,a){var o,s;r=r||"name",a=a||"value";var l={};s=e&&e.length?n(t,e).get():t,e=e||"",s=s||[];var c={};for(o=0;o2)return l[e]=2|l[e],f.set(t,null);if(u){for(o=e;o1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],a=t[e][1],s=!1,i(n))for(r=n.length-1;r>=0;r--)c(n[r],f(a,r))?s?n[r]=void 0:n.pop():s=!0;else if("object"==typeof n&&null!==n)for(o=Object.keys(n),s=!1,r=o.length-1;r>=0;r--)c(n[o[r]],f(a,o[r]))?delete n[o[r]]:s=!0;if(s)return}}(u)):s[e[o]]=n}}function f(t,e){var r=e;return n(e)?r="["+e+"]":t&&(r="."+e),t+r}function h(t,e,r,n){var a,o=i(r),s=!0,l=r,f=n.replace("-1",0),h=!o&&c(r,f),p=e[0];for(a=0;a/g),o=0;oo||a===i||al||e&&c(t))}:function(t,e){var a=t[0],c=t[1];if(a===i||ao||c===i||cl)return!1;var u,f,h,d,p,m=r.length,v=r[0][0],g=r[0][1],y=0;for(u=1;uMath.max(f,v)||c>Math.max(h,g)))if(cu||Math.abs(n(o,h))>i)return!0;return!1};a.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var s=r.length,l=n;r.splice(i+1);for(var c=l+1;c1&&a(t.pop());return{addPt:a,raw:t,filtered:r}}},{"../constants/numerical":702,"./matrix":730}],737:[function(t,e,r){"use strict";e.exports=function(t,e){if(e instanceof RegExp){var r,n=e.toString();for(r=0;ri.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;re}function l(t,e){return t>=e}r.findBin=function(t,e,r){if(n(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var c,u,f=0,h=e.length,d=0,p=h>1?(e[h-1]-e[0])/(h-1):1;for(u=p>=0?r?a:o:r?l:s,t+=1e-9*p*(r?-1:1)*(p>=0?1:-1);f90&&i.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;se[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,c=r?Math.ceil:Math.floor;it.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":140}],746:[function(t,e,r){"use strict";var n=t("color-normalize");e.exports=function(t){return t?n(t):[0,0,0,1]}},{"color-normalize":99}],747:[function(t,e,r){"use strict";var n=t("d3"),i=t("../lib"),a=t("../constants/xmlns_namespaces"),o=t("../constants/string_mappings"),s=t("../constants/alignment").LINE_SPACING;function l(t,e){return t.node().getBoundingClientRect()[e]}var c=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;r.convertToTspans=function(t,e,o){var g=t.text(),L=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&g.match(c),C=n.select(t.node().parentNode);if(!C.empty()){var P=t.attr("class")?t.attr("class").split(" ")[0]:"text";return P+="-math",C.selectAll("svg."+P).remove(),C.selectAll("g."+P+"-group").remove(),t.style("display",null).attr({"data-unformatted":g,"data-math":"N"}),L?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var r=parseInt(t.node().style.fontSize,10),a={fontSize:r};!function(t,e,r){var a="math-output-"+i.randstr([],64),o=n.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text((s=t,s.replace(u,"\\lt ").replace(f,"\\gt ")));var s;MathJax.Hub.Queue(["Typeset",MathJax.Hub,o.node()],function(){var e=n.select("body").select("#MathJax_SVG_glyphs");if(o.select(".MathJax_SVG").empty()||!o.select("svg").node())i.log("There was an error in the tex syntax.",t),r();else{var a=o.select("svg").node().getBoundingClientRect();r(o.select(".MathJax_SVG"),e,a)}o.remove()})}(L[2],a,function(n,i,a){C.selectAll("svg."+P).remove(),C.selectAll("g."+P+"-group").remove();var s=n&&n.select("svg");if(!s||!s.node())return z(),void e();var c=C.append("g").classed(P+"-group",!0).attr({"pointer-events":"none","data-unformatted":g,"data-math":"Y"});c.node().appendChild(s.node()),i&&i.node()&&s.node().insertBefore(i.node().cloneNode(!0),s.node().firstChild),s.attr({class:P,height:a.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=t.node().style.fill||"black";s.select("g").attr({fill:u,stroke:u});var f=l(s,"width"),h=l(s,"height"),d=+t.attr("x")-f*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],p=-(r||l(t,"height"))/4;"y"===P[0]?(c.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-f/2,p-h/2]+")"}),s.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===P[0]?s.attr({x:t.attr("x"),y:p-h/2}):"a"===P[0]?s.attr({x:0,y:p}):s.attr({x:d,y:+t.attr("y")+p-h/2}),o&&o.call(t,c),e(c)})})):z(),t}function z(){C.empty()||(P=t.attr("class")+"-math",C.select("svg."+P).remove()),t.text("").style("white-space","pre"),function(t,e){e=(r=e,function(t,e){if(!t)return"";for(var r=0;r1)for(var i=1;i doesnt match end tag <"+t+">. Pretending it did match.",e),o=c[c.length-1].node}else i.log("Ignoring unexpected end tag .",e)}w.test(e)?f():(o=t,c=[{node:t}]);for(var P=e.split(x),z=0;z|>|>)/g;var h={sup:"font-size:70%",sub:"font-size:70%",b:"font-weight:bold",i:"font-style:italic",a:"cursor:pointer",span:"",em:"font-style:italic;font-weight:bold"},d={sub:"0.3em",sup:"-0.6em"},p={sub:"-0.21em",sup:"0.42em"},m="\u200b",v=["http:","https:","mailto:","",void 0,":"],g=new RegExp("]*)?/?>","g"),y=Object.keys(o.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:o.entityToUnicode[t]}}),b=/(\r\n?|\n)/g,x=/(<[^<>]*>)/,_=/<(\/?)([^ >]*)(\s+(.*))?>/i,w=//i,M=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,k=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,A=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,T=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function E(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var S=/(^|;)\s*color:/;function L(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-c.top+"px",left:a()-c.left+"px","z-index":1e3}),this}}r.plainText=function(t){return(t||"").replace(g," ")},r.lineCount=function(t){return t.selectAll("tspan.line").size()||1},r.positionText=function(t,e,r){return t.each(function(){var t=n.select(this);function i(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var a=i("x",e),o=i("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:a,y:o})})},r.makeEditable=function(t,e){var r=e.gd,i=e.delegate,a=n.dispatch("edit","input","cancel"),o=i||t;if(t.style({"pointer-events":i?"none":"all"}),1!==t.size())throw new Error("boo");function s(){var i,s,c,u;i=n.select(r).select(".svg-container"),s=i.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:e.fill||c.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(e.text||t.attr("data-unformatted")).call(L(t,i,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,i=n.select(this).attr("class");(e=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;n.select(this).transition().duration(0).remove(),n.select(document).on("mouseup",null),a.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,n.select(document).on("mouseup",function(){if(n.event.target===t)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===n.event.which?(r._editing=!1,t.style({opacity:1}),n.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(t,this.textContent)):(a.input.call(t,this.textContent),n.select(this).call(L(t,i,e)))}).on("keydown",function(){13===n.event.which&&this.blur()}).call(l),t.style({opacity:0});var f,h=o.attr("class");(f=h?"."+h.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(f).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?s():o.on("click",s),n.rebind(t,a,"on")}},{"../constants/alignment":696,"../constants/string_mappings":703,"../constants/xmlns_namespaces":704,"../lib":724,d3:128}],748:[function(t,e,r){"use strict";var n={};function i(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}r.throttle=function(t,e,r){var a=n[t],o=Date.now();if(!a){for(var s in n)n[s].tsa.ts+e?l():a.timer=setTimeout(function(){l(),a.timer=null},e)},r.done=function(t){var e=n[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},r.clear=function(t){if(t)i(n[t]),delete n[t];else for(var e in n)r.clear(e)}},{}],749:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r}},{"fast-isnumeric":140}],750:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson-client").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":799,"topojson-client":529}],751:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en-US",dictionary:{"Click to enter Colorscale title":"Click to enter Colorscale title"},format:{date:"%m/%d/%Y"}}},{}],752:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en",dictionary:{"Click to enter Colorscale title":"Click to enter Colourscale title"},format:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"],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"],periods:["AM","PM"],dateTime:"%a %b %e %X %Y",date:"%d/%m/%Y",time:"%H:%M:%S",decimal:".",thousands:",",grouping:[3],currency:["$",""],year:"%Y",month:"%b %Y",dayMonth:"%b %-d",dayMonthYear:"%b %-d, %Y"}}},{}],753:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t){for(var e,r,i=n.layoutArrayContainers,a=n.layoutArrayRegexes,o=t.split("[")[0],s=0;s0&&o.log("Clearing previous rejected promises from queue."),t._promises=[]},r.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(s.subplotsRegistry.cartesian||{}).attrRegex,a=(s.subplotsRegistry.gl3d||{}).attrRegex,l=Object.keys(t);for(e=0;e3?(T.x=1.02,T.xanchor="left"):T.x<-2&&(T.x=-.02,T.xanchor="right"),T.y>3?(T.y=1.02,T.yanchor="bottom"):T.y<-2&&(T.y=-.02,T.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),f.clean(t),t},r.cleanData=function(t,e){for(var n=[],i=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),l=0;l0)return t.substr(0,e)}r.hasParent=function(t,e){for(var r=v(e);r;){if(r in t)return!0;r=v(r)}return!1};var g=["x","y","z"];r.clearAxisTypes=function(t,e,r){for(var n=0;n1&&o.warn("Full array edits are incompatible with other edits",f);var y=r[""][""];if(u(y))e.set(null);else{if(!Array.isArray(y))return o.warn("Unrecognized full array edit value",f,y),!0;e.set(y)}return!m&&(h(v,g),d(t),!0)}var b,x,_,w,M,k,A,T=Object.keys(r).map(Number).sort(s),E=e.get(),S=E||[],L=n(g,f).get(),C=[],P=-1,z=S.length;for(b=0;bS.length-(A?0:1))o.warn("index out of range",f,_);else if(void 0!==k)M.length>1&&o.warn("Insertion & removal are incompatible with edits to the same index.",f,_),u(k)?C.push(_):A?("add"===k&&(k={}),S.splice(_,0,k),L&&L.splice(_,0,{})):o.warn("Unrecognized full object edit value",f,_,k),-1===P&&(P=_);else for(x=0;x=0;b--)S.splice(C[b],1),L&&L.splice(C[b],1);if(S.length?E||e.set(S):e.set(null),m)return!1;if(h(v,g),p!==a){var O;if(-1===P)O=T;else{for(z=Math.max(S.length,z),O=[],b=0;b=P);b++)O.push(_);for(b=P;b=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function I(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),D(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&D(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function R(t,e,r,n,a,o){!function(t,e,r,n){var i=s.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!s.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in D(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var l,c,u,f=function(t,e,r,n){var a,o,l,c,u,f=s.isPlainObject(n),h=[];for(var d in Array.isArray(r)||(r=[r]),r=O(r,t.data.length-1),e)for(var p=0;p=0&&uY.range[0]?[1,2]:[2,1]);else{var Z=Y.range[0],J=Y.range[1];W?(Z<=0&&J<=0&&A(F+".autorange",!0),Z<=0?Z=J/1e6:J<=0&&(J=Z/1e6),A(F+".range[0]",Math.log(Z)/Math.LN10),A(F+".range[1]",Math.log(J)/Math.LN10)):(A(F+".range[0]",Math.pow(10,Z)),A(F+".range[1]",Math.pow(10,J)))}else A(F+".autorange",!0);Array.isArray(l._subplots.polar)&&l._subplots.polar.length&&l[P.parts[0]]&&"radialaxis"===P.parts[1]&&delete l[P.parts[0]]._subplot.viewInitial["radialaxis.range"],u.getComponentMethod("annotations","convertCoords")(t,U,z,A),u.getComponentMethod("images","convertCoords")(t,U,z,A)}else A(F+".autorange",!0),A(F+".range",null);s.nestedProperty(l,F+"._inputRange").set(null)}else if(I.match(k.AX_NAME_PATTERN)){var K=s.nestedProperty(l,C).get(),Q=(z||{}).type;Q&&"-"!==Q||(Q="linear"),u.getComponentMethod("annotations","convertCoords")(t,K,Q,A),u.getComponentMethod("images","convertCoords")(t,K,Q,A)}var $=x.containerArrayMatch(C);if($){r=$.array,n=$.index;var tt=$.property,et=(s.nestedProperty(a,r)||[])[n]||{},rt=et,nt=q||{editType:"calc"},it=-1!==nt.editType.indexOf("calcIfAutorange");""===n?(it?y.calc=!0:M.update(y,nt),it=!1):""===tt&&(rt=z,x.isAddVal(z)?w[C]=null:x.isRemoveVal(z)?(w[C]=et,rt=et):s.warn("unrecognized full object value",e)),it&&(B(t,rt,"x")||B(t,rt,"y"))?y.calc=!0:M.update(y,nt),p[r]||(p[r]={});var at=p[r][n];at||(at=p[r][n]={}),at[tt]=z,delete e[C]}else"reverse"===I?(j.range?j.range.reverse():(A(F+".autorange",!0),j.range=[1,0]),U.autorange?y.calc=!0:y.plot=!0):((!l._has("gl2d")&&!l._has("regl")||"dragmode"!==C||"lasso"!==z&&"select"!==z||"lasso"===V||"select"===V)&&q?M.update(y,q):y.calc=!0,P.set(z))}}for(r in p){x.applyContainerArrayChanges(t,s.nestedProperty(a,r),p[r],y)||(y.plot=!0)}var ot=l._axisConstraintGroups||[];for(T in E)for(n=0;n=i.length?i[0]:i[t]:i}function l(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function c(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function f(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,h.transition(t,e.frame.data,e.frame.layout,_.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function d(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&f()};e()}var p,m,v=0;function g(t){return Array.isArray(i)?v>=i.length?t.transitionOpts=i[v]:t.transitionOpts=i[0]:t.transitionOpts=i,v++,t}var y=[],b=void 0===e||null===e,x=Array.isArray(e);if(!b&&!x&&s.isPlainObject(e))y.push({type:"object",data:g(s.extendFlat({},e))});else if(b||-1!==["string","number"].indexOf(typeof e))for(p=0;p0&&kk)&&A.push(m);y=A}}y.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(s.isPlainObject(e[n])){var m=e[n].name,v=(u[m]||p[m]||{}).name,g=e[n].name,y=u[v]||p[v];v&&g&&"number"==typeof g&&y&&L<5&&(L++,s.warn('addFrames: overwriting frame "'+(u[v]||p[v]).name+'" with a frame whose name of type "number" also equates to "'+v+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===L&&s.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),p[m]={name:m},d.push({frame:h.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:f+n})}d.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=d[n].frame).name&&s.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;u[i.name="frame "+t._transitionData._counter++];);if(u[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var l=h.modifyFrames,u=h.modifyFrames,f=[t,o],d=[t,a];return c&&c.add(t,l,f,u,d),h.modifyFrames(t,a)},o.purge=function(t){var e=(t=s.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return h.cleanPlot([],{},r,e),h.purge(t),l.purge(t),e._container&&e._container.remove(),delete t._context,t}},{"../components/color":598,"../components/drawing":623,"../components/errorbars":629,"../constants/xmlns_namespaces":704,"../lib":724,"../lib/events":712,"../lib/queue":738,"../lib/svg_text_utils":747,"../plotly":765,"../plots/cartesian/axis_ids":773,"../plots/cartesian/constants":775,"../plots/cartesian/constraints":777,"../plots/cartesian/graph_interact":779,"../plots/plots":833,"../plots/polar/legacy":841,"../registry":854,"./edit_types":754,"./helpers":755,"./manage_arrays":756,"./plot_schema":759,"./subroutines":762,d3:128,"fast-isnumeric":140,"has-hover":255}],758:[function(t,e,r){"use strict";e.exports={staticPlot:!1,editable:!1,edits:{annotationPosition:!1,annotationTail:!1,annotationText:!1,axisTitleText:!1,colorbarPosition:!1,colorbarTitleText:!1,legendPosition:!1,legendText:!1,shapePosition:!1,titleText:!1},autosizable:!1,queueLength:0,fillFrame:!1,frameMargins:0,scrollZoom:!1,doubleClick:"reset+autosize",showTips:!0,showAxisDragHandles:!0,showAxisRangeEntryBoxes:!0,showLink:!1,sendData:!0,linkText:"Edit chart",showSources:!1,displayModeBar:"hover",modeBarButtonsToRemove:[],modeBarButtonsToAdd:[],modeBarButtons:!1,displaylogo:!0,plotGlPixelRatio:2,setBackground:"transparent",topojsonURL:"https://cdn.plot.ly/",mapboxAccessToken:null,logging:1,globalTransforms:[],locale:"en-US",locales:{}}},{}],759:[function(t,e,r){"use strict";var n=t("../registry"),i=t("../lib"),a=t("../plots/attributes"),o=t("../plots/layout_attributes"),s=t("../plots/frame_attributes"),l=t("../plots/animation_attributes"),c=t("../plots/polar/legacy/area_attributes"),u=t("../plots/polar/legacy/axis_attributes"),f=t("./edit_types"),h=i.extendFlat,d=i.extendDeepAll,p="_isSubplotObj",m="_isLinkedToArray",v=[p,m,"_arrayAttrRegexps","_deprecated"];function g(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(y(e[r]))r++;else if(r=t.items.length)return!1;t=t.items[a]}}return t}function y(t){return t===Math.round(t)&&t>=0}function b(t){return function(t){r.crawl(t,function(t,e,n){r.isValObject(t)?"data_array"===t.valType?(t.role="data",n[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(n[e+"src"]={valType:"string",editType:"none"}):i.isPlainObject(t)&&(t.role="object")})}(t),function(t){r.crawl(t,function(t,e,r){if(!t)return;var n=t[m];if(!n)return;delete t[m],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),t}function x(t,e,r){var n=i.nestedProperty(t,r),a=d({},e.layoutAttributes);a[p]=!0,n.set(a)}function _(t,e,r){var n=i.nestedProperty(t,r);n.set(d(n.get()||{},e))}r.IS_SUBPLOT_OBJ=p,r.IS_LINKED_TO_ARRAY=m,r.DEPRECATED="_deprecated",r.UNDERSCORE_ATTRS=v,r.get=function(){var t={};n.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:c},r={}):(e=n.modules[t]._module,r=e.basePlotModule);var i={type:null};d(i,a),d(i,e.attributes),r.attributes&&d(i,r.attributes);i.type=t;var o={meta:e.meta||{},attributes:b(i)};if(e.layoutAttributes){var s={};d(s,e.layoutAttributes),o.layoutAttributes=b(s)}return o}(e)});var e,r={};return Object.keys(n.transformsRegistry).forEach(function(t){r[t]=function(t){var e=n.transformsRegistry[t],r=d({},e.attributes);return Object.keys(n.componentsRegistry).forEach(function(e){var i=n.componentsRegistry[e];i.schema&&i.schema.transforms&&i.schema.transforms[t]&&Object.keys(i.schema.transforms[t]).forEach(function(e){_(r,i.schema.transforms[t][e],e)})}),{attributes:b(r)}}(t)}),{defs:{valObjects:i.valObjectMeta,metaKeys:v.concat(["description","role","editType","impliedEdits"]),editType:{traces:f.traces,layout:f.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in d(r,o),n.subplotsRegistry)if((e=n.subplotsRegistry[t]).layoutAttributes)if("cartesian"===e.name)x(r,e,"xaxis"),x(r,e,"yaxis");else{var i="subplot"===e.attr?e.name:e.attr;x(r,e,i)}for(t in r=function(t){return h(t,{radialaxis:u.radialaxis,angularaxis:u.angularaxis}),h(t,u.layout),t}(r),n.componentsRegistry){var a=(e=n.componentsRegistry[t]).schema;if(a&&(a.subplots||a.layout)){var s=a.subplots;if(s&&s.xaxis&&!s.yaxis)for(var l in s.xaxis)delete r.yaxis[l]}else e.layoutAttributes&&_(r,e.layoutAttributes,e.name)}return{layoutAttributes:b(r)}}(),transforms:r,frames:(e={frames:i.extendDeepAll({},s)},b(e),e.frames),animation:b(l)}},r.crawl=function(t,e,n,a){var o=n||0;a=a||"",Object.keys(t).forEach(function(n){var s=t[n];if(-1===v.indexOf(n)){var l=(a?a+".":"")+n;e(s,n,t,o,l),r.isValObject(s)||i.isPlainObject(s)&&"impliedEdits"!==n&&r.crawl(s,e,o+1,l)}})},r.isValObject=function(t){return t&&void 0!==t.valType},r.findArrayAttributes=function(t){var e=[],n=[];function o(r,a,o,s){if(n=n.slice(0,s).concat([a]),r&&("data_array"===r.valType||!0===r.arrayOk)&&!("colorbar"===n[s-1]&&("ticktext"===a||"tickvals"===a))){var l=function(t){return t.join(".")}(n),c=i.nestedProperty(t,l).get();Array.isArray(c)&&e.push(l)}}if(r.crawl(a,o),t._module&&t._module.attributes&&r.crawl(t._module.attributes,o),t.transforms)for(var s=t.transforms,l=0;l=t.transforms.length)return!1;i=(r=(n.transformsRegistry[t.transforms[l].type]||{}).attributes)&&r[e[2]],s=3}else if("area"===t.type)i=c[o];else{var u=t._module;if(u||(u=(n.modules[t.type||a.type.dflt]||{})._module),!u)return!1;if(!(i=(r=u.attributes)&&r[o])){var f=u.basePlotModule;f&&f.attributes&&(i=f.attributes[o])}i||(i=a[o])}return g(i,e,s)},r.getLayoutValObject=function(t,e){return g(function(t,e){var r,i,a,s,l=t._basePlotModules;if(l){var c;for(r=0;r=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(r,n,w)?(_.push(t),w.push([r,n])):i=[0];var o=e.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){e.bg=o;var t=e.plotgroup.node();t.insertBefore(this,t.childNodes[0])})});var M=a._bgLayer.selectAll(".bg").data(_);return M.enter().append("rect").classed("bg",!0),M.exit().remove(),M.each(function(t){a._plots[t].bg=n.select(this)}),x.each(function(t){var r=a._plots[t],n=r.xaxis,i=r.yaxis;r.bg&&h&&r.bg.call(c.setRect,n._offset-s,i._offset-s,n._length+2*s,i._length+2*s).call(l.fill,a.plot_bgcolor).style("stroke-width",0),r.clipId="clip"+a._uid+t+"plot";var o,f,p=a._clips.selectAll("#"+r.clipId).data([0]);for(p.enter().append("clipPath").attr({class:"plotclip",id:r.clipId}).append("rect"),p.selectAll("rect").attr({width:n._length,height:i._length}),c.setTranslate(r.plot,n._offset,i._offset),r._hasClipOnAxisFalse?(o=null,f=r.clipId):(o=r.clipId,f=null),c.setClipUrl(r.plot,o),e=0;e1&&d.push(h("object","layout"))),i.supplyDefaults(p);for(var m=p._fullData,v=r.length,g=0;g2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},w.getAutoRange=function(t){var e,r=[],n=t._min[0].val,i=t._max[0].val;for(e=1;e0&&f>0&&h/f>d&&(c=s,u=l,d=h/f);if(n===i){var v=n-1,g=n+1;r="tozero"===t.rangemode?n<0?[v,0]:[0,g]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,g)]:[v,g]}else d&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(c.val>=0&&(c={val:0,pad:0}),u.val<=0&&(u={val:0,pad:0})):"nonnegative"===t.rangemode&&(c.val-d*c.pad<0&&(c={val:0,pad:0}),u.val<0&&(u={val:1,pad:0})),d=(u.val-c.val)/(t._length-c.pad-u.pad)),r=[c.val-d*c.pad,u.val+d*u.pad]);return r[0]===r[1]&&("tozero"===t.rangemode?r=r[0]<0?[r[0],0]:r[0]>0?[0,r[0]]:[0,1]:(r=[r[0]-1,r[0]+1],"nonnegative"===t.rangemode&&(r[0]=Math.max(0,r[0])))),p&&r.reverse(),o.simpleMap(r,t.l2r||Number)},w.doAutoRange=function(t){t._length||t.setScale();var e=t._min&&t._max&&t._min.length&&t._max.length;if(t.autorange&&e){t.range=w.getAutoRange(t),t._r=t.range.slice(),t._rl=o.simpleMap(t._r,t.r2l);var r=t._input;r.range=t.range.slice(),r.autorange=t.autorange}},w.saveRangeInitial=function(t,e){for(var r=w.list(t,"",!0),n=!1,i=0;i0?r.ppadplus:r.ppadminus)||r.ppad||0),_=k((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=k(r.vpadplus||r.vpad),M=k(r.vpadminus||r.vpad);for(n=0;n<6;n++)A(n);for(n=g-1;n>5;n--)A(n)}function k(t){if(Array.isArray(t))return function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}function A(r){if(l=e[r],i(l)){if(f=x(r)+y,d=_(r)+y,m=l-M(r),v=l+w(r),"log"===t.type&&m=d?p=!1:s.val>=c&&s.pad<=d&&(t._min.splice(a,1),a--);p&&t._min.push({val:c,pad:b&&0===c?0:d})}if(n(u)){for(p=!0,a=0;a=u&&s.pad>=f?p=!1:s.val<=u&&s.pad<=f&&(t._max.splice(a,1),a--);p&&t._max.push({val:u,pad:b&&0===u?0:f})}}function n(t){return i(t)&&Math.abs(t).3*h||u(n)||u(a))){var d=r.dtick/2;t+=t+d.8){var s=Number(r.substr(1));a.exactYears>.8&&s%12==0?t=w.tickIncrement(t,"M6","reverse")+1.5*m:a.exactMonths>.8?t=w.tickIncrement(t,"M1","reverse")+15.5*m:t-=m/2;var l=w.tickIncrement(t,r);if(l<=n)return l}return t}(g,t,l.dtick,c,a)),p=g,v=0;p<=u;)p=w.tickIncrement(p,l.dtick,!1,a),v++;return{start:e.c2r(g,0,a),end:e.c2r(p,0,a),size:l.dtick,_count:v}},w.calcTicks=function(t){var e=o.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=o.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),w.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}if(t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),R(t),"array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),s=o.simpleMap(t.range,t.r2l),l=1.0001*s[0]-1e-4*s[1],c=1.0001*s[1]-1e-4*s[0],u=Math.min(l,c),f=Math.max(l,c),h=0;Array.isArray(i)||(i=[]);var d="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=s:u<=s)&&!(a.length>c||u===l);u=w.tickIncrement(u,t.dtick,i,t.calendar))l=u,a.push(u);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var f=new Array(a.length),h=0;h10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=m&&a<=10||e>=15*m)t._tickround="d";else if(e>=g&&a<=16||e>=v)t._tickround="M";else if(e>=y&&a<=19||e>=g)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20}}else if(i(e)||"L"===e.charAt(0)){var s=t.range.map(t.r2d||Number);i(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),c=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(c)>3&&(j(t.exponentformat)&&!B(c)?t._tickexponent=3*Math.round((c-1)/3):t._tickexponent=c)}else t._tickround=null}function N(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}w.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=o.dateTick0(t.calendar);var a=2*e;a>d?(e/=d,r=n(10),t.dtick="M"+12*I(e,r,S)):a>p?(e/=p,t.dtick="M"+I(e,1,L)):a>m?(t.dtick=I(e,m,P),t.tick0=o.dateTick0(t.calendar,!0)):a>v?t.dtick=I(e,v,L):a>g?t.dtick=I(e,g,C):a>y?t.dtick=I(e,y,C):(r=n(10),t.dtick=I(e,r,S))}else if("log"===t.type){t.tick0=0;var s=o.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(s[1]-s[0])<1){var l=1.5*Math.abs((s[1]-s[0])/e);e=Math.abs(Math.pow(10,s[1])-Math.pow(10,s[0]))/l,r=n(10),t.dtick="L"+I(e,r,S)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,r=1,t.dtick=I(e,r,D)):(t.tick0=0,r=n(10),t.dtick=I(e,r,S));if(0===t.dtick&&(t.dtick=1),!i(t.dtick)&&"string"!=typeof t.dtick){var c=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(c)}},w.tickIncrement=function(t,e,r,a){var s=r?-1:1;if(i(e))return t+s*e;var l=e.charAt(0),c=s*Number(e.substr(1));if("M"===l)return o.incrementMonth(t,c,a);if("L"===l)return Math.log(Math.pow(10,t)+c)/Math.LN10;if("D"===l){var u="D2"===e?O:z,f=t+.01*s,h=o.roundUp(o.mod(f,1),u,r);return Math.floor(f)+Math.log(n.round(Math.pow(10,h),1))/Math.LN10}throw"unrecognized dtick "+String(e)},w.tickFirst=function(t){var e=t.r2l||Number,r=o.simpleMap(t.range,e),a=r[1]"+l,t._prevDateHead=l));e.text=c}(t,s,r,c):"log"===t.type?function(t,e,r,n,a){var s=t.dtick,l=e.x,c=t.tickformat;"never"===a&&(a="");!n||"string"==typeof s&&"L"===s.charAt(0)||(s="L3");if(c||"string"==typeof s&&"L"===s.charAt(0))e.text=U(Math.pow(10,l),t,a,n);else if(i(s)||"D"===s.charAt(0)&&o.mod(l+.01,1)<.1){var u=Math.round(l);-1!==["e","E","power"].indexOf(t.exponentformat)||j(t.exponentformat)&&B(u)?(e.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+b+-u+"",e.fontSize*=1.25):(e.text=U(Math.pow(10,l),t,"","fakehover"),"D1"===s&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==s.charAt(0))throw"unrecognized dtick "+String(s);e.text=String(Math.round(Math.pow(10,o.mod(l,1)))),e.fontSize*=.75}if("D1"===t.dtick){var f=String(e.text).charAt(0);"0"!==f&&"1"!==f||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(l<0?.5:.25)))}}(t,s,0,c,n):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,s):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=U(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var s=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(s[1]>=100)e.text=U(o.deg2rad(e.x),t,i,n);else{var l=e.x<0;1===s[1]?1===s[0]?e.text="\u03c0":e.text=s[0]+"\u03c0":e.text=["",s[0],"","\u2044","",s[1],"","\u03c0"].join(""),l&&(e.text=b+e.text)}}}}(t,s,r,c,n):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=U(e.x,t,i,n)}(t,s,0,c,n),t.tickprefix&&!d(t.showtickprefix)&&(s.text=t.tickprefix+s.text),t.ticksuffix&&!d(t.showticksuffix)&&(s.text+=t.ticksuffix),s},w.hoverLabelText=function(t,e,r){if(r!==x&&r!==e)return w.hoverLabelText(t,e)+" - "+w.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=w.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":b+i:i};var F=["f","p","n","\u03bc","m","","k","M","G","T"];function j(t){return"SI"===t||"B"===t}function B(t){return t>14||t<-15}function U(t,e,r,n){var a=t<0,s=e._tickround,l=r||e.exponentformat||"B",c=e._tickexponent,u=w.getTickFormat(e),f=e.separatethousands;if(n){var h={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:i(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};R(h),s=(Number(h._tickround)||0)+4,c=h._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,b);var d,p=Math.pow(10,-s)/2;if("none"===l&&(c=0),(t=Math.abs(t))"+d+"":"B"===l&&9===c?t+="B":j(l)&&(t+=F[c/3+5]));return a?b+t:t}function V(t,e){for(var r=0;r=0,a=c(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n2*o}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,o=0,s=0;s2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;en?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},{"../../registry":854,"./constants":775}],774:[function(t,e,r){"use strict";e.exports=function(t,e,r){if("category"===e.type){var n,i=t.categoryarray,a=Array.isArray(i)&&i.length>0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}},{}],775:[function(t,e,r){"use strict";var n=t("../../lib").counterRegex;e.exports={idRegex:{x:n("x"),y:n("y")},attrRegex:n("[xy]axis"),xAxisMatch:n("xaxis"),yAxisMatch:n("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}}},{"../../lib":724}],776:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./axis_ids").id2name;e.exports=function(t,e,r,a,o){var s=o._axisConstraintGroups,l=e._id,c=l.charAt(0);if(!e.fixedrange&&(r("constrain"),n.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===c?["left","center","right"]:["bottom","middle","top"],dflt:"x"===c?"center":"middle"}},"constraintoward"),t.scaleanchor)){var u=function(t,e,r,n){var a,o,s,l,c=n[i(e)].type,u=[];for(o=0;oa*g)||_)for(r=0;rP&&OL&&(L=O);f/=(L-S)/(2*C),S=l.l2r(S),L=l.l2r(L),l.range=l._input.range=A=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function P(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function z(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:u.background,stroke:u.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function O(t){t.selectAll(".select-outline").remove()}function D(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),I(t,e,i,a)}function I(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function R(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function N(t){k&&t.data&&t._context.showTips&&(l.notifier(l._(t,"Double-click to zoom back out"),"long"),k=!1)}function F(t){return"lasso"===t||"select"===t}function j(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,M)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function B(t,e){if(a){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}e.exports={makeDragBox:function(t,e,r,a,u,d,k,A){var I,U,V,q,H,G,Y,W,X,Z,J,K,Q,$=t._fullLayout,tt=t._fullLayout._zoomlayer,et=k+A==="nsew",rt=1===(k+A).length;function nt(){U=[e.xaxis],V=[e.yaxis];var r=U[0],n=V[0];G=r._length,Y=n._length;var i,a,o=$._axisConstraintGroups,s=[r._id],c=[n._id];I=[e].concat(k&&A?e.overlays:[]);for(var u=1;uM||o>M?(ht="xy",a/G>o/Y?(o=a*Y/G,st>i?lt.t=st-o:lt.b=st+o):(a=o*G/Y,ot>n?lt.l=ot-a:lt.r=ot+a),pt.attr("d",j(lt))):s():!X||o rect").call(f.setTranslate,i,a).call(f.setScale,r,n);var C=y.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");y.plot.call(f.setTranslate,S,L).call(f.setScale,1/r,1/n),C.selectAll(".point").call(f.setPointGroupScale,r,n),C.selectAll(".textpoint").call(f.setTextPointsScale,r,n),C.call(f.hideOutsideRangePoints,y)}}}return k.length*A.length!=1&&B(it,function(e){if(t._context.scrollZoom||$._enablescrollzoom){if(t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(nt(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(xt);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=wt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(A||J){for(A||(s=.5),i=0;iu[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return r("layer"),e}},{"../../lib":724,"fast-isnumeric":140}],787:[function(t,e,r){"use strict";var n=t("../../constants/alignment").FROM_BL;e.exports=function(t,e,r){void 0===r&&(r=n[t.constraintoward||"center"]);var i=[t.r2l(t.range[0]),t.r2l(t.range[1])],a=i[0]+(i[1]-i[0])*r;t.range=t._input.range=[t.l2r(a+(i[0]-a)*e),t.l2r(a+(i[1]-a)*e)]}},{"../../constants/alignment":696}],788:[function(t,e,r){"use strict";var n=t("polybooljs"),i=t("../../lib/polygon"),a=t("../../lib/throttle"),o=t("../../components/color"),s=t("../../components/fx/helpers").makeEventData,l=t("../../components/fx"),c=t("./axes"),u=t("./constants"),f=i.filter,h=i.tester,d=i.multitester,p=u.MINSELECT;function m(t){return t._id}function v(t,e,r){var n,i,a;if(r){var o=r.points||[];for(n=0;n0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*u*Math.abs(n-i))}return h}function g(e,r,n){var a=l(e,n||t.calendar);if(a===h){if(!i(e))return h;a=l(new Date(+e))}return a}function y(e,r,n){return s(e,r,n||t.calendar)}function b(e){return t._categories[Math.round(e)]}function x(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(i(e))return+e}function _(e){return i(e)?n.round(t._b+t._m*e,2):h}function w(e){return(e-t._b)/t._m}t.c2l="log"===t.type?v:c,t.l2c="log"===t.type?m:c,t.l2p=_,t.p2l=w,t.c2p="log"===t.type?function(t,e){return _(v(t,e))}:_,t.p2c="log"===t.type?function(t){return m(w(t))}:w,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=o,t.c2d=t.c2r=t.l2d=t.l2r=c,t.d2p=t.r2p=function(e){return t.l2p(o(e))},t.p2d=t.p2r=w,t.cleanPos=c):"log"===t.type?(t.d2r=t.d2l=function(t,e){return v(o(t),e)},t.r2d=t.r2c=function(t){return m(o(t))},t.d2c=t.r2l=o,t.c2d=t.l2r=c,t.c2r=v,t.l2d=m,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return m(w(t))},t.r2p=function(e){return t.l2p(o(e))},t.p2r=w,t.cleanPos=c):"date"===t.type?(t.d2r=t.r2d=a.identity,t.d2c=t.r2c=t.d2l=t.r2l=g,t.c2d=t.c2r=t.l2d=t.l2r=y,t.d2p=t.r2p=function(e,r,n){return t.l2p(g(e,0,n))},t.p2d=t.p2r=function(t,e,r){return y(w(t),e,r)},t.cleanPos=function(e){return a.cleanDate(e,h,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return h},t.r2d=t.c2d=t.l2d=b,t.d2r=t.d2l_noadd=x,t.r2c=function(e){var r=x(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=c,t.r2l=x,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return b(w(t))},t.r2p=t.d2p,t.p2r=w,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:c(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var o,s,l=a.nestedProperty(t,e).get();if(s=(s="date"===t.type?a.dfltRange(t.calendar):"y"===r?d.DFLTRANGEY:n.dfltRange||d.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=a.cleanDate(l[0],h,t.calendar),l[1]=a.cleanDate(l[1],h,t.calendar)),o=0;o<2;o++)if("date"===t.type){if(!a.isDateTime(l[o],t.calendar)){t[e]=s;break}if(t.r2l(l[0])===t.r2l(l[1])){var c=a.constrain(t.r2l(l[0]),a.MIN_MS+1e3,a.MAX_MS-1e3);l[0]=t.l2r(c-1e3),l[1]=t.l2r(c+1e3);break}}else{if(!i(l[o])){if(!i(l[1-o])){t[e]=s;break}l[o]=l[1-o]*(o?10:.1)}if(l[o]<-f?l[o]=-f:l[o]>f&&(l[o]=f),l[0]===l[1]){var u=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=u,l[1]+=u}}else a.nestedProperty(t,e).set(s)},t.setScale=function(n){var i=e._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var a=p.getFromId({_fullLayout:e},t.overlaying);t.domain=a.domain}var o=n&&t._r?"_r":"range",s=t.calendar;t.cleanRange(o);var l=t.r2l(t[o][0],s),c=t.r2l(t[o][1],s);if("y"===r?(t._offset=i.t+(1-t.domain[1])*i.h,t._length=i.h*(t.domain[1]-t.domain[0]),t._m=t._length/(l-c),t._b=-t._m*c):(t._offset=i.l+t.domain[0]*i.w,t._length=i.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-l),t._b=-t._m*l),!isFinite(t._m)||!isFinite(t._b))throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,i,a,o,s="date"===t.type&&e[r+"calendar"];if(r in e)for(n=e[r],o=e._length||n.length,i=new Array(o),a=0;a=t.r2l(t.range[0])&&i<=t.r2l(t.range[1])},t._min=[],t._max=[];var M=e._d3locale;"date"===t.type&&(t._dateFormat=M?M.timeFormat.utc:n.time.format.utc,t._extraFormat=e._extraFormat),t._separators=e.separators,t._numFormat=M?M.numberFormat:n.format,delete t._minDtick,delete t._forceTick0}},{"../../constants/numerical":702,"../../lib":724,"./axis_ids":773,"./constants":775,d3:128,"fast-isnumeric":140}],790:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e,r,a,o){var s=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",s),r("ticksuffix",o.tickSuffixDflt)&&r("showticksuffix",s),r("showticklabels")){var l=o.font||{},c=e.color===t.color?e.color:l.color;if(n.coerceFont(r,"tickfont",{family:l.family,size:l.size,color:c}),r("tickangle"),"category"!==a){var u=r("tickformat");!function(t,e){var r,a,o=t.tickformatstops,s=e.tickformatstops=[];if(!Array.isArray(o))return;function l(t,e){return n.coerce(r,a,i.tickformatstops,t,e)}for(var c=0;c0?Number(u):c;else if("string"!=typeof u)e.dtick=c;else{var f=u.charAt(0),h=u.substr(1);((h=n(h)?Number(h):0)<=0||!("date"===o&&"M"===f&&h===Math.round(h)||"log"===o&&"L"===f||"log"===o&&"D"===f&&(1===h||2===h)))&&(e.dtick=c)}var d="date"===o?i.dateTick0(e.calendar):0,p=r("tick0",d);"date"===o?e.tick0=i.cleanDate(p,d):n(p)&&"D1"!==u&&"D2"!==u?e.tick0=Number(p):e.tick0=d}else{void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}}},{"../../constants/numerical":702,"../../lib":724,"fast-isnumeric":140}],793:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plotly"),a=t("../../registry"),o=t("../../components/drawing"),s=t("./axes"),l=t("./constants").attrRegex;e.exports=function(t,e,r,c){var u=t._fullLayout,f=[];var h,d,p,m,v=function(t){var e,r,n,i,a={};for(e in t)if((r=e.split("."))[0].match(l)){var o=e.charAt(0),s=r[0];if(n=u[s],i={},Array.isArray(t[e])?i.to=t[e].slice(0):Array.isArray(t[e].range)&&(i.to=t[e].range.slice(0)),!i.to)continue;i.axisName=s,i.length=n._length,f.push(o),a[o]=i}return a}(e),g=Object.keys(v),y=function(t,e,r){var n,i,a,o=t._plots,s=[];for(n in o){var l=o[n];if(-1===s.indexOf(l)){var c=l.xaxis._id,u=l.yaxis._id,f=l.xaxis.range,h=l.yaxis.range;l.xaxis._r=l.xaxis.range.slice(),l.yaxis._r=l.yaxis.range.slice(),i=r[c]?r[c].to:f,a=r[u]?r[u].to:h,f[0]===i[0]&&f[1]===i[1]&&h[0]===a[0]&&h[1]===a[1]||-1===e.indexOf(c)&&-1===e.indexOf(u)||s.push(l)}}return s}(u,g,v);if(!y.length)return function(){function e(e,r,n){for(var i=0;i rect").call(o.setTranslate,0,0).call(o.setScale,1,1),t.plot.call(o.setTranslate,e._offset,r._offset).call(o.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(o.setPointGroupScale,1,1),n.selectAll(".textpoint").call(o.setTextPointsScale,1,1),n.call(o.hideOutsideRangePoints,t)}function x(e,r){var n,i,l,c=v[e.xaxis._id],f=v[e.yaxis._id],h=[];if(c){i=(n=t._fullLayout[c.axisName])._r,l=c.to,h[0]=(i[0]*(1-r)+r*l[0]-i[0])/(i[1]-i[0])*e.xaxis._length;var d=i[1]-i[0],p=l[1]-l[0];n.range[0]=i[0]*(1-r)+r*l[0],n.range[1]=i[1]*(1-r)+r*l[1],h[2]=e.xaxis._length*(1-r+r*p/d)}else h[0]=0,h[2]=e.xaxis._length;if(f){i=(n=t._fullLayout[f.axisName])._r,l=f.to,h[1]=(i[1]*(1-r)+r*l[1]-i[1])/(i[0]-i[1])*e.yaxis._length;var m=i[1]-i[0],g=l[1]-l[0];n.range[0]=i[0]*(1-r)+r*l[0],n.range[1]=i[1]*(1-r)+r*l[1],h[3]=e.yaxis._length*(1-r+r*g/m)}else h[1]=0,h[3]=e.yaxis._length;!function(e,r){var n,i=[];for(i=[e._id,r._id],n=0;n rect").call(o.setTranslate,k,A).call(o.setScale,1/w,1/M),e.plot.call(o.setTranslate,S,L).call(o.setScale,w,M).selectAll(".points").selectAll(".point").call(o.setPointGroupScale,1/w,1/M),e.plot.selectAll(".points").selectAll(".textpoint").call(o.setTextPointsScale,1/w,1/M)}c&&(h=c());var _=n.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(m),m=null,function(){for(var e={},r=0;rr.duration?(function(){for(var e={},r=0;r0?".":"")+a;i.isPlainObject(o)?l(o,e,s,n+1):e(s,a,o)}})}r.manageCommandObserver=function(t,e,n,o){var s={},l=!0;e&&e._commandObserver&&(s=e._commandObserver),s.cache||(s.cache={}),s.lookupTable={};var c=r.hasSimpleAPICommandBindings(t,n,s.lookupTable);if(e&&e._commandObserver){if(c)return s;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,s}if(c){a(t,c,s.cache),s.check=function(){if(l){var e=a(t,c,s.cache);return e.changed&&o&&void 0!==s.lookupTable[e.value]&&(s.disable(),Promise.resolve(o({value:e.value,type:c.type,prop:c.prop,traces:c.traces,index:s.lookupTable[e.value]})).then(s.enable,s.enable)),e.changed}};for(var u=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],f=0;fi*Math.PI/180}return!1},r.getPath=function(){return n.geo.path().projection(r)},r.getBounds=function(t){return r.getPath().bounds(t)},r.fitExtent=function(t,e){var n=t[1][0]-t[0][0],i=t[1][1]-t[0][1],a=r.clipExtent&&r.clipExtent();r.scale(150).translate([0,0]),a&&r.clipExtent(null);var o=r.getBounds(e),s=Math.min(n/(o[1][0]-o[0][0]),i/(o[1][1]-o[0][1])),l=+t[0][0]+(n-s*(o[1][0]+o[0][0]))/2,c=+t[0][1]+(i-s*(o[1][1]+o[0][1]))/2;return a&&r.clipExtent(a),r.scale(150*s).translate([l,c])},r.precision(p.precision),i&&r.clipAngle(i-p.clipPad);return r}(e);u.center([c.lon-l.lon,c.lat-l.lat]).rotate([-l.lon,-l.lat,l.roll]).parallels(s.parallels);var f=[[r.l+r.w*o.x[0],r.t+r.h*(1-o.y[1])],[r.l+r.w*o.x[1],r.t+r.h*(1-o.y[0])]],h=e.lonaxis,d=e.lataxis,m=function(t,e){var r=p.clipPad,n=t[0]+r,i=t[1]-r,a=e[0]+r,o=e[1]-r;n>0&&i<0&&(i+=360);var s=(i-n)/4;return{type:"Polygon",coordinates:[[[n,a],[n,o],[n+s,o],[n+2*s,o],[n+3*s,o],[i,o],[i,a],[i-s,a],[i-2*s,a],[i-3*s,a],[n,a]]]}}(h.range,d.range);u.fitExtent(f,m);var v=this.bounds=u.getBounds(m),g=this.fitScale=u.scale(),y=u.translate();if(!isFinite(v[0][0])||!isFinite(v[0][1])||!isFinite(v[1][0])||!isFinite(v[1][1])||isNaN(y[0])||isNaN(y[0])){for(var b=this.graphDiv,x=["projection.rotation","center","lonaxis.range","lataxis.range"],_="Invalid geo settings, relayout'ing to default view.",w={},M=0;M0&&w<0&&(w+=360);var M,k,A,T=(_+w)/2;if(!c){var E=u?s.projRotate:[T,0,0];M=r("projection.rotation.lon",E[0]),r("projection.rotation.lat",E[1]),r("projection.rotation.roll",E[2]),r("showcoastlines",!u)&&(r("coastlinecolor"),r("coastlinewidth")),r("showocean")&&r("oceancolor")}(c?(k=-96.6,A=38.7):(k=u?T:M,A=(x[0]+x[1])/2),r("center.lon",k),r("center.lat",A),f)&&r("projection.parallels",s.projParallels||[0,60]);r("projection.scale"),r("showland")&&r("landcolor"),r("showlakes")&&r("lakecolor"),r("showrivers")&&(r("rivercolor"),r("riverwidth")),r("showcountries",u&&"usa"!==a)&&(r("countrycolor"),r("countrywidth")),("usa"===a||"north america"===a&&50===n)&&(r("showsubunits",!0),r("subunitcolor"),r("subunitwidth")),u||r("showframe",!0)&&(r("framecolor"),r("framewidth")),r("bgcolor")}e.exports=function(t,e,r){n(t,e,r,{type:"geo",attributes:a,handleDefaults:s,partition:"y"})}},{"../../subplot_defaults":846,"../constants":799,"./layout_attributes":804}],804:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("../../domain_attributes"),a=t("../constants"),o=t("../../../plot_api/edit_types").overrideAll,s={range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},showgrid:{valType:"boolean",dflt:!1},tick0:{valType:"number"},dtick:{valType:"number"},gridcolor:{valType:"color",dflt:n.lightLine},gridwidth:{valType:"number",min:0,dflt:1}};e.exports=o({domain:i({name:"geo"},{}),resolution:{valType:"enumerated",values:[110,50],dflt:110,coerceNumber:!0},scope:{valType:"enumerated",values:Object.keys(a.scopeDefaults),dflt:"world"},projection:{type:{valType:"enumerated",values:Object.keys(a.projNames)},rotation:{lon:{valType:"number"},lat:{valType:"number"},roll:{valType:"number"}},parallels:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},scale:{valType:"number",min:0,dflt:1}},center:{lon:{valType:"number"},lat:{valType:"number"}},showcoastlines:{valType:"boolean"},coastlinecolor:{valType:"color",dflt:n.defaultLine},coastlinewidth:{valType:"number",min:0,dflt:1},showland:{valType:"boolean",dflt:!1},landcolor:{valType:"color",dflt:a.landColor},showocean:{valType:"boolean",dflt:!1},oceancolor:{valType:"color",dflt:a.waterColor},showlakes:{valType:"boolean",dflt:!1},lakecolor:{valType:"color",dflt:a.waterColor},showrivers:{valType:"boolean",dflt:!1},rivercolor:{valType:"color",dflt:a.waterColor},riverwidth:{valType:"number",min:0,dflt:1},showcountries:{valType:"boolean"},countrycolor:{valType:"color",dflt:n.defaultLine},countrywidth:{valType:"number",min:0,dflt:1},showsubunits:{valType:"boolean"},subunitcolor:{valType:"color",dflt:n.defaultLine},subunitwidth:{valType:"number",min:0,dflt:1},showframe:{valType:"boolean"},framecolor:{valType:"color",dflt:n.defaultLine},framewidth:{valType:"number",min:0,dflt:1},bgcolor:{valType:"color",dflt:n.background},lonaxis:s,lataxis:s},"plot","from-root")},{"../../../components/color/attributes":597,"../../../plot_api/edit_types":754,"../../domain_attributes":796,"../constants":799}],805:[function(t,e,r){"use strict";e.exports=function(t){function e(t,e){return{type:"Feature",id:t.id,properties:t.properties,geometry:r(t.geometry,e)}}function r(e,n){if(!e)return null;if("GeometryCollection"===e.type)return{type:"GeometryCollection",geometries:object.geometries.map(function(t){return r(t,n)})};if(!c.hasOwnProperty(e.type))return null;var i=c[e.type];return t.geo.stream(e,n(i)),i.result()}t.geo.project=function(t,e){var i=e.stream;if(!i)throw new Error("not yet supported");return(t&&n.hasOwnProperty(t.type)?n[t.type]:r)(t,i)};var n={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},i=[],a=[],o={point:function(t,e){i.push([t,e])},result:function(){var t=i.length?i.length<2?{type:"Point",coordinates:i[0]}:{type:"MultiPoint",coordinates:i}:null;return i=[],t}},s={lineStart:u,point:function(t,e){i.push([t,e])},lineEnd:function(){i.length&&(a.push(i),i=[])},result:function(){var t=a.length?a.length<2?{type:"LineString",coordinates:a[0]}:{type:"MultiLineString",coordinates:a}:null;return a=[],t}},l={polygonStart:u,lineStart:u,point:function(t,e){i.push([t,e])},lineEnd:function(){var t=i.length;if(t){do{i.push(i[0].slice())}while(++t<4);a.push(i),i=[]}},polygonEnd:u,result:function(){if(!a.length)return null;var t=[],e=[];return a.forEach(function(r){!function(t){if((e=t.length)<4)return!1;for(var e,r=0,n=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++rn^d>n&&r<(h-c)*(n-u)/(d-u)+c&&(i=!i)}return i}(t[0],r))return t.push(e),!0})||t.push([e])}),a=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},c={Point:o,MultiPoint:o,LineString:s,MultiLineString:s,Polygon:l,MultiPolygon:l,Sphere:l};function u(){}var f=1e-6,h=f*f,d=Math.PI,p=d/2,m=(Math.sqrt(d),d/180),v=180/d;function g(t){return t>1?p:t<-1?-p:Math.asin(t)}function y(t){return t>1?0:t<-1?d:Math.acos(t)}var b=t.geo.projection,x=t.geo.projectionMutator;function _(t,e){var r=(2+p)*Math.sin(e);e/=2;for(var n=0,i=1/0;n<10&&Math.abs(i)>f;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(d*(4+d))*t*(1+Math.cos(e)),2*Math.sqrt(d/(4+d))*Math.sin(e)]}t.geo.interrupt=function(e){var r,n=[[[[-d,0],[0,p],[d,0]]],[[[-d,0],[0,-p],[d,0]]]];function i(t,r){for(var i=r<0?-1:1,a=n[+(r<0)],o=0,s=a.length-1;oa[o][2][0];++o);var l=e(t-a[o][1][0],r);return l[0]+=e(a[o][1][0],i*r>i*a[o][0][1]?a[o][0][1]:r)[0],l}e.invert&&(i.invert=function(t,a){for(var o=r[+(a<0)],s=n[+(a<0)],c=0,u=o.length;c=0;--i){var o=n[1][i],l=180*o[0][0]/d,c=180*o[0][1]/d,u=180*o[1][1]/d,f=180*o[2][0]/d,h=180*o[2][1]/d;r.push(s([[f-e,h-e],[f-e,u+e],[l+e,u+e],[l+e,c-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}(),l)},i},a.lobes=function(t){return arguments.length?(n=t.map(function(t){return t.map(function(t){return[[t[0][0]*d/180,t[0][1]*d/180],[t[1][0]*d/180,t[1][1]*d/180],[t[2][0]*d/180,t[2][1]*d/180]]})}),r=n.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})}),a):n.map(function(t){return t.map(function(t){return[[180*t[0][0]/d,180*t[0][1]/d],[180*t[1][0]/d,180*t[1][1]/d],[180*t[2][0]/d,180*t[2][1]/d]]})})},a},_.invert=function(t,e){var r=.5*e*Math.sqrt((4+d)/d),n=g(r),i=Math.cos(n);return[t/(2/Math.sqrt(d*(4+d))*(1+i)),g((n+r*(i+2))/(2+p))]},(t.geo.eckert4=function(){return b(_)}).raw=_;var w=t.geo.azimuthalEqualArea.raw;function M(t,e){if(arguments.length<2&&(e=t),1===e)return w;if(e===1/0)return k;function r(r,n){var i=w(r/e,n);return i[0]*=t,i}return r.invert=function(r,n){var i=w.invert(r/t,n);return i[0]*=e,i},r}function k(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function A(t,e){return[3*t/(2*d)*Math.sqrt(d*d/3-e*e),e]}function T(t,e){return[t,1.25*Math.log(Math.tan(d/4+.4*e))]}function E(t){return function(e){var r,n=t*Math.sin(e),i=30;do{e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e))}while(Math.abs(r)>f&&--i>0);return e/2}}k.invert=function(t,e){var r=2*g(e/2);return[t*Math.cos(r/2)/Math.cos(r),r]},(t.geo.hammer=function(){var t=2,e=x(M),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}).raw=M,A.invert=function(t,e){return[2/3*d*t/Math.sqrt(d*d/3-e*e),e]},(t.geo.kavrayskiy7=function(){return b(A)}).raw=A,T.invert=function(t,e){return[t,2.5*Math.atan(Math.exp(.8*e))-.625*d]},(t.geo.miller=function(){return b(T)}).raw=T,E(d);var S=function(t,e,r){var n=E(r);function i(r,i){return[t*r*Math.cos(i=n(i)),e*Math.sin(i)]}return i.invert=function(n,i){var a=g(i/e);return[n/(t*Math.cos(a)),g((2*a+Math.sin(2*a))/r)]},i}(Math.SQRT2/p,Math.SQRT2,d);function L(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(n*(.003971*r-.001529*n)-.013791)),e*(1.007226+r*(.015085+n*(.028874*r-.044475-.005916*n)))]}(t.geo.mollweide=function(){return b(S)}).raw=S,L.invert=function(t,e){var r,n=e,i=25;do{var a=n*n,o=a*a;n-=r=(n*(1.007226+a*(.015085+o*(.028874*a-.044475-.005916*o)))-e)/(1.007226+a*(.045255+o*(.259866*a-.311325-.005916*11*o)))}while(Math.abs(r)>f&&--i>0);return[t/(.8707+(a=n*n)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),n]},(t.geo.naturalEarth=function(){return b(L)}).raw=L;var C=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];function P(t,e){var r,n=Math.min(18,36*Math.abs(e)/d),i=Math.floor(n),a=n-i,o=(r=C[i])[0],s=r[1],l=(r=C[++i])[0],c=r[1],u=(r=C[Math.min(19,++i)])[0],f=r[1];return[t*(l+a*(u-o)/2+a*a*(u-2*l+o)/2),(e>0?p:-p)*(c+a*(f-s)/2+a*a*(f-2*c+s)/2)]}function z(t,e){return[t*Math.cos(e),e]}function O(t,e){var r,n=Math.cos(e),i=(r=y(n*Math.cos(t/=2)))?r/Math.sin(r):1;return[2*n*Math.sin(t)*i,Math.sin(e)*i]}function D(t,e){var r=O(t,e);return[(r[0]+t/p)/2,(r[1]+e)/2]}C.forEach(function(t){t[1]*=1.0144}),P.invert=function(t,e){var r=e/p,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=C[a][1],s=C[a+1][1],l=C[Math.min(19,a+2)][1],c=l-o,u=l-2*s+o,f=2*(Math.abs(r)-s)/c,d=u/c,g=f*(1-d*f*(1-2*d*f));if(g>=0||1===a){n=(e>=0?5:-5)*(g+i);var y,b=50;do{g=(i=Math.min(18,Math.abs(n)/5))-(a=Math.floor(i)),o=C[a][1],s=C[a+1][1],l=C[Math.min(19,a+2)][1],n-=(y=(e>=0?p:-p)*(s+g*(l-o)/2+g*g*(l-2*s+o)/2)-e)*v}while(Math.abs(y)>h&&--b>0);break}}while(--a>=0);var x=C[a][0],_=C[a+1][0],w=C[Math.min(19,a+2)][0];return[t/(_+g*(w-x)/2+g*g*(w-2*_+x)/2),n*m]},(t.geo.robinson=function(){return b(P)}).raw=P,z.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return b(z)}).raw=z,O.invert=function(t,e){if(!(t*t+4*e*e>d*d+f)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),l=Math.cos(r/2),c=Math.sin(n),u=Math.cos(n),h=Math.sin(2*n),p=c*c,m=u*u,v=s*s,g=1-m*l*l,b=g?y(u*l)*Math.sqrt(a=1/g):a=0,x=2*b*u*s-t,_=b*c-e,w=a*(m*v+b*u*l*p),M=a*(.5*o*h-2*b*c*s),k=.25*a*(h*s-b*c*m*o),A=a*(p*l+b*v*u),T=M*k-A*w;if(!T)break;var E=(_*M-x*A)/T,S=(x*k-_*w)/T;r-=E,n-=S}while((Math.abs(E)>f||Math.abs(S)>f)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return b(O)}).raw=O,D.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),l=Math.sin(2*n),c=s*s,u=o*o,h=Math.sin(r),d=Math.cos(r/2),m=Math.sin(r/2),v=m*m,g=1-u*d*d,b=g?y(o*d)*Math.sqrt(a=1/g):a=0,x=.5*(2*b*o*m+r/p)-t,_=.5*(b*s+n)-e,w=.5*a*(u*v+b*o*d*c)+.5/p,M=a*(h*l/4-b*s*m),k=.125*a*(l*m-b*s*u*h),A=.5*a*(c*d+b*v*o)+.5,T=M*k-A*w,E=(_*M-x*A)/T,S=(x*k-_*w)/T;r-=E,n-=S}while((Math.abs(E)>f||Math.abs(S)>f)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return b(D)}).raw=D}},{}],806:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=Math.PI/180,o=180/Math.PI,s={cursor:"pointer"},l={cursor:"auto"};function c(t,e){return n.behavior.zoom().translate(e.translate()).scale(e.scale())}function u(t,e,r){var n=t.id,a=t.graphDiv,o=a.layout[n],s=a._fullLayout[n],l={};function c(t,e){var r=i.nestedProperty(s,t);r.get()!==e&&(r.set(e),i.nestedProperty(o,t).set(e),l[n+"."+t]=e)}r(c),c("projection.scale",e.scale()/t.fitScale),a.emit("plotly_relayout",l)}function f(t,e){var r=c(0,e);function i(r){var n=e.invert(t.midPt);r("center.lon",n[0]),r("center.lat",n[1])}return r.on("zoomstart",function(){n.select(this).style(s)}).on("zoom",function(){e.scale(n.event.scale).translate(n.event.translate),t.render()}).on("zoomend",function(){n.select(this).style(l),u(t,e,i)}),r}function h(t,e){var r,i,a,o,f,h,d,p,m=c(0,e),v=2;function g(t){return e.invert(t)}function y(r){var n=e.rotate(),i=e.invert(t.midPt);r("projection.rotation.lon",-n[0]),r("center.lon",i[0]),r("center.lat",i[1])}return m.on("zoomstart",function(){n.select(this).style(s),r=n.mouse(this),i=e.rotate(),a=e.translate(),o=i,f=g(r)}).on("zoom",function(){if(h=n.mouse(this),l=e(g(s=r)),Math.abs(l[0]-s[0])>v||Math.abs(l[1]-s[1])>v)return m.scale(e.scale()),void m.translate(e.translate());var s,l;e.scale(n.event.scale),e.translate([a[0],n.event.translate[1]]),f?g(h)&&(p=g(h),d=[o[0]+(p[0]-f[0]),i[1],i[2]],e.rotate(d),o=d):f=g(r=h),t.render()}).on("zoomend",function(){n.select(this).style(l),u(t,e,y)}),m}function d(t,e){var r,i={r:e.rotate(),k:e.scale()},f=c(0,e),h=function(t){var e=0,r=arguments.length,i=[];for(;++ep?(a=(f>0?90:-90)-d,i=0):(a=Math.asin(f/p)*o-d,i=Math.sqrt(p*p-f*f));var v=180-a-2*d,y=(Math.atan2(h,u)-Math.atan2(c,i))*o,b=(Math.atan2(h,u)-Math.atan2(c,-i))*o,x=m(r[0],r[1],a,y),_=m(r[0],r[1],v,b);return x<=_?[a,y,r[2]]:[v,b,r[2]]}(M,r,S);isFinite(k[0])&&isFinite(k[1])&&isFinite(k[2])||(k=S),e.rotate(k),S=k}}else r=p(e,T=x);h.of(this,arguments)({type:"zoom"})}),A=h.of(this,arguments),d++||A({type:"zoomstart"})}).on("zoomend",function(){var r;n.select(this).style(l),v.call(f,"zoom",null),r=h.of(this,arguments),--d||r({type:"zoomend"}),u(t,e,b)}).on("zoom.redraw",function(){t.render()}),n.rebind(f,h,"on")}function p(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&function(t){var e=t[0]*a,r=t[1]*a,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}(r)}function m(t,e,r,n){var i=v(r-t),a=v(n-e);return Math.sqrt(i*i+a*a)}function v(t){return(t%360+540)%360-180}function g(t,e,r){var n=r*a,i=t.slice(),o=0===e?1:0,s=2===e?1:2,l=Math.cos(n),c=Math.sin(n);return i[o]=t[o]*l-t[s]*c,i[s]=t[s]*l+t[o]*c,i}function y(t,e){for(var r=0,n=0,i=t.length;nMath.abs(s)?(l.boxEnd[1]=l.boxStart[1]+Math.abs(a)*_*(s>=0?1:-1),l.boxEnd[1]u[3]&&(l.boxEnd[1]=u[3],l.boxEnd[0]=l.boxStart[0]+(u[3]-l.boxStart[1])/Math.abs(_))):(l.boxEnd[0]=l.boxStart[0]+Math.abs(s)/_*(a>=0?1:-1),l.boxEnd[0]u[2]&&(l.boxEnd[0]=u[2],l.boxEnd[1]=l.boxStart[1]+(u[2]-l.boxStart[0])*Math.abs(_)))}}else l.boxEnabled?(a=l.boxStart[0]!==l.boxEnd[0],s=l.boxStart[1]!==l.boxEnd[1],a||s?(a&&(v(0,l.boxStart[0],l.boxEnd[0]),t.xaxis.autorange=!1),s&&(v(1,l.boxStart[1],l.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),l.boxEnabled=!1,l.boxInited=!1):l.boxInited&&(l.boxInited=!1);break;case"pan":l.boxEnabled=!1,l.boxInited=!1,e?(l.panning||(l.dragStart[0]=n,l.dragStart[1]=i),Math.abs(l.dragStart[0]-n)h[p+2]&&(h[p]=-1,h[p+2]=1),(d=this[b[p]])._length=s.viewBox[p+2]-s.viewBox[p],o.doAutoRange(d),d.setScale();g(l),s.ticks=this.computeTickMarks(),s.dataBox=this.calcDataBox(),s.merge(r),n.update(s),this.glplot.draw()},w.calcDataBox=function(){var t=this.xaxis,e=this.yaxis,r=t.range,n=e.range,i=t.r2l,a=e.r2l;return[i(r[0]),a(n[0]),i(r[1]),a(n[1])]},w.setRanges=function(t){var e=this.xaxis,r=this.yaxis,n=e.l2r,i=r.l2r;e.range=[n(t[0]),n(t[2])],r.range=[i(t[1]),i(t[3])]},w.updateTraces=function(t,e){var r,n,i,a=Object.keys(this.traces);this.fullData=t;t:for(r=0;rMath.abs(e))c.rotate(a,0,0,-t*r*Math.PI*p.rotateSpeed/window.innerWidth);else{var o=-p.zoomSpeed*i*e/window.innerHeight*(a-c.lastT())/20;c.pan(a,0,0,f*(Math.exp(o)-1))}}},!0),p};var n=t("right-now"),i=t("3d-view"),a=t("mouse-change"),o=t("mouse-wheel"),s=t("mouse-event-offset"),l=t("has-passive-events")},{"3d-view":40,"has-passive-events":256,"mouse-change":424,"mouse-event-offset":425,"mouse-wheel":427,"right-now":489}],813:[function(t,e,r){"use strict";var n=t("../../plot_api/edit_types").overrideAll,i=t("../../components/fx/layout_attributes"),a=t("./scene"),o=t("../get_data").getSubplotData,s=t("../../lib"),l=t("../../constants/xmlns_namespaces");r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=r.attrRegex=s.counterRegex("scene"),r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.baseLayoutAttrOverrides=n({hoverlabel:i.hoverlabel},"plot","nested"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=e._subplots.gl3d,i=0;i1;o(t,e,r,{type:"gl3d",attributes:l,handleDefaults:c,fullLayout:e,font:e.font,fullData:r,getDfltFromLayout:function(e){if(!i)return n.validate(t[e],l[e])?t[e]:void 0},paper_bgcolor:e.paper_bgcolor,calendar:e.calendar})}},{"../../../components/color":598,"../../../lib":724,"../../../registry":854,"../../subplot_defaults":846,"./axis_defaults":816,"./layout_attributes":819}],819:[function(t,e,r){"use strict";var n=t("./axis_attributes"),i=t("../../domain_attributes"),a=t("../../../lib/extend").extendFlat,o=t("../../../lib").counterRegex;function s(t,e,r){return{x:{valType:"number",dflt:t,editType:"camera"},y:{valType:"number",dflt:e,editType:"camera"},z:{valType:"number",dflt:r,editType:"camera"},editType:"camera"}}e.exports={_arrayAttrRegexps:[o("scene",".annotations",!0)],bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"plot"},camera:{up:a(s(0,0,1),{}),center:a(s(0,0,0),{}),eye:a(s(1.25,1.25,1.25),{}),editType:"camera"},domain:i({name:"scene",editType:"plot"}),aspectmode:{valType:"enumerated",values:["auto","cube","data","manual"],dflt:"auto",editType:"plot",impliedEdits:{"aspectratio.x":void 0,"aspectratio.y":void 0,"aspectratio.z":void 0}},aspectratio:{x:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},y:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},z:{valType:"number",min:0,editType:"plot",impliedEdits:{"^aspectmode":"manual"}},editType:"plot",impliedEdits:{aspectmode:"manual"}},xaxis:n,yaxis:n,zaxis:n,dragmode:{valType:"enumerated",values:["orbit","turntable","zoom","pan",!1],dflt:"turntable",editType:"plot"},hovermode:{valType:"enumerated",values:["closest",!1],dflt:"closest",editType:"modebar"},editType:"plot",_deprecated:{cameraposition:{valType:"info_array",editType:"camera"}}}},{"../../../lib":724,"../../../lib/extend":713,"../../domain_attributes":796,"./axis_attributes":815}],820:[function(t,e,r){"use strict";var n=t("../../../lib/str2rgbarray"),i=["xaxis","yaxis","zaxis"];function a(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}a.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[i[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=n(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}},e.exports=function(t){var e=new a;return e.merge(t),e}},{"../../../lib/str2rgbarray":746}],821:[function(t,e,r){"use strict";e.exports=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,l=t.fullSceneLayout,c=[[],[],[]],u=0;u<3;++u){var f=l[o[u]];if(f._length=(r[u].hi-r[u].lo)*r[u].pixelsPerDataUnit/t.dataScale[u],Math.abs(f._length)===1/0)c[u]=[];else{f._input_range=f.range.slice(),f.range[0]=r[u].lo/t.dataScale[u],f.range[1]=r[u].hi/t.dataScale[u],f._m=1/(t.dataScale[u]*r[u].pixelsPerDataUnit),f.range[0]===f.range[1]&&(f.range[0]-=1,f.range[1]+=1);var h=f.tickmode;if("auto"===f.tickmode){f.tickmode="linear";var d=f.nticks||i.constrain(f._length/40,4,9);n.autoTicks(f,Math.abs(f.range[1]-f.range[0])/d)}for(var p=n.calcTicks(f),m=0;mf[1][o]?d[o]=1:f[1][o]===f[0][o]?d[o]=1:d[o]=1/(f[1][o]-f[0][o]);for(this.dataScale=d,this.convertAnnotations(this),a=0;am[1][a])m[0][a]=-1,m[1][a]=1;else{var T=m[1][a]-m[0][a];m[0][a]-=T/32,m[1][a]+=T/32}}else{var E=s.range;m[0][a]=s.r2l(E[0]),m[1][a]=s.r2l(E[1])}m[0][a]===m[1][a]&&(m[0][a]-=1,m[1][a]+=1),v[a]=m[1][a]-m[0][a],this.glplot.bounds[0][a]=m[0][a]*d[a],this.glplot.bounds[1][a]=m[1][a]*d[a]}var S=[1,1,1];for(a=0;a<3;++a){var L=g[l=(s=c[w[a]]).type];S[a]=Math.pow(L.acc,1/L.count)/d[a]}var C;if("auto"===c.aspectmode)C=Math.max.apply(null,S)/Math.min.apply(null,S)<=4?S:[1,1,1];else if("cube"===c.aspectmode)C=[1,1,1];else if("data"===c.aspectmode)C=S;else{if("manual"!==c.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var P=c.aspectratio;C=[P.x,P.y,P.z]}c.aspectratio.x=u.aspectratio.x=C[0],c.aspectratio.y=u.aspectratio.y=C[1],c.aspectratio.z=u.aspectratio.z=C[2],this.glplot.aspect=C;var z=c.domain||null,O=e._size||null;if(z&&O){var D=this.container.style;D.position="absolute",D.left=O.l+z.x[0]*O.w+"px",D.top=O.t+(1-z.y[1])*O.h+"px",D.width=O.w*(z.x[1]-z.x[0])+"px",D.height=O.h*(z.y[1]-z.y[0])+"px"}this.glplot.redraw()}},_.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},_.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),A(this.glplot.camera)},_.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]])},_.saveCamera=function(t){var e=this.getCamera(),r=c.nestedProperty(t,this.id+".camera"),n=r.get(),i=!1;function a(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===n)i=!0;else for(var o=0;o<3;o++)for(var s=0;s<3;s++)if(!a(e,n,o,s)){i=!0;break}return i&&r.set(e),i},_.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},_.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(n),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,i=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var a=new Uint8Array(r*i*4);e.readPixels(0,0,r,i,e.RGBA,e.UNSIGNED_BYTE,a);for(var o=0,s=i-1;o0}o.update=function(t){this.visible?this.needsNewSource(t)?(this.updateLayer(t),this.updateSource(t)):this.needsNewLayer(t)&&this.updateLayer(t):(this.updateSource(t),this.updateLayer(t)),this.updateStyle(t),this.visible=s(t)},o.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},o.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},o.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,s(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},o.updateLayer=function(t){var e=this.map;if(e.getLayer(this.idLayer)&&e.removeLayer(this.idLayer),this.layerType=t.type,s(t)){e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type},t.below);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",{visibility:"visible"})}},o.updateStyle=function(t){var e=function(t){var e={},r={};switch(t.type){case"circle":n.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":n.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity});break;case"fill":n.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var a=t.symbol,o=i(a.textposition,a.iconsize);n.extendFlat(e,{"icon-image":a.icon+"-15","icon-size":a.iconsize/10,"text-field":a.text,"text-size":a.textfont.size,"text-anchor":o.anchor,"text-offset":o.offset}),n.extendFlat(r,{"icon-color":t.color,"text-color":a.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}(t);s(t)&&(this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint))},o.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)},e.exports=function(t,e,r){var n=new a(t,e);return n.update(r),n}},{"../../lib":724,"./convert_text_opts":826}],829:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color").defaultLine,a=t("../domain_attributes"),o=t("../font_attributes"),s=t("../../traces/scatter/attributes").textposition,l=t("../../plot_api/edit_types").overrideAll,c=o({});c.family.dflt="Open Sans Regular, Arial Unicode MS Regular",e.exports=l({_arrayAttrRegexps:[n.counterRegex("mapbox",".layers",!0)],domain:a({name:"mapbox"}),accesstoken:{valType:"string",noBlank:!0,strict:!0},style:{valType:"any",values:["basic","streets","outdoors","light","dark","satellite","satellite-streets"],dflt:"basic"},center:{lon:{valType:"number",dflt:0},lat:{valType:"number",dflt:0}},zoom:{valType:"number",dflt:1},bearing:{valType:"number",dflt:0},pitch:{valType:"number",dflt:0},layers:{_isLinkedToArray:"layer",sourcetype:{valType:"enumerated",values:["geojson","vector"],dflt:"geojson"},source:{valType:"any"},sourcelayer:{valType:"string",dflt:""},type:{valType:"enumerated",values:["circle","line","fill","symbol"],dflt:"circle"},below:{valType:"string",dflt:""},color:{valType:"color",dflt:i},opacity:{valType:"number",min:0,max:1,dflt:1},circle:{radius:{valType:"number",dflt:15}},line:{width:{valType:"number",dflt:2}},fill:{outlinecolor:{valType:"color",dflt:i}},symbol:{icon:{valType:"string",dflt:"marker"},iconsize:{valType:"number",dflt:10},text:{valType:"string",dflt:""},textfont:c,textposition:n.extendFlat({},s,{arrayOk:!1})}}},"plot","from-root")},{"../../components/color":598,"../../lib":724,"../../plot_api/edit_types":754,"../../traces/scatter/attributes":1048,"../domain_attributes":796,"../font_attributes":797}],830:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../subplot_defaults"),a=t("./layout_attributes");function o(t,e,r,i){r("accesstoken",i.accessToken),r("style"),r("center.lon"),r("center.lat"),r("zoom"),r("bearing"),r("pitch"),function(t,e){var r,i,o=t.layers||[],s=e.layers=[];function l(t,e){return n.coerce(r,i,a.layers,t,e)}for(var c=0;c=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var o=r.select(".js-link-to-tool"),s=r.select(".js-link-spacer"),l=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){d.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(t,o),s.text(o.text()&&l.text()?" - ":"")}},d.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=n.select(t).append("div").attr("id","hiddenform").style("display","none"),i=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=d.graphJson(t,!1,"keepdata"),i.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var x,_=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],w=["year","month","dayMonth","dayMonthYear"];function M(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},d.cleanPlot=function(t,e,r,n){var i,a,o=n._basePlotModules||[];for(i=0;i0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),f=u.left+u.right,h=u.bottom+u.top,p=1-2*s,m=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};n=Math.round(p*(m.width-f)),a=Math.round(p*(m.height-h))}else{var v=l?window.getComputedStyle(t):{};n=parseFloat(v.width)||r.width,a=parseFloat(v.height)||r.height}var g=d.layoutAttributes.width.min,y=d.layoutAttributes.height.min;n1,x=!e.height&&Math.abs(r.height-a)>1;(x||b)&&(b&&(r.width=n),x&&(r.height=a)),t._initialAutoSize||(t._initialAutoSize={width:n,height:a}),d.sanitizeMargins(r)},d.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,l=s.componentsRegistry,c=e._basePlotModules,u=s.subplotsRegistry.cartesian;for(i in l)(o=l[i]).includeBasePlot&&o.includeBasePlot(t,e);for(c.length||c.push(u),e._has("cartesian")&&u.finalizeSubplots(t,e),a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||d.doAutoMargin(t)}},d.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),o=Math.max(e.margin.l||0,0),s=Math.max(e.margin.r||0,0),l=Math.max(e.margin.t||0,0),c=Math.max(e.margin.b||0,0),u=e._pushmargin;if(!1!==e.margin.autoexpand)for(var f in u.base={l:{val:0,size:o},r:{val:1,size:s},t:{val:1,size:l},b:{val:0,size:c}},u){var h=u[f].l||{},d=u[f].b||{},p=h.val,m=h.size,v=d.val,g=d.size;for(var y in u){if(i(m)&&u[y].r){var b=u[y].r.val,x=u[y].r.size;if(b>p){var _=(m*b+(x-e.width)*p)/(b-p),w=(x*(1-p)+(m-e.width)*(1-b))/(b-p);_>=0&&w>=0&&_+w>o+s&&(o=_,s=w)}}if(i(g)&&u[y].t){var M=u[y].t.val,k=u[y].t.size;if(M>v){var A=(g*M+(k-e.height)*v)/(M-v),T=(k*(1-v)+(g-e.height)*(1-M))/(M-v);A>=0&&T>=0&&A+T>c+l&&(c=A,l=T)}}}}if(r.l=Math.round(o),r.r=Math.round(s),r.t=Math.round(l),r.b=Math.round(c),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return a.plot(t)},d.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&d.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(c.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!c.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):c.isJSDate(t)?c.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},d.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){p=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return a.redraw(t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,s,l=0,u=0;function f(){return l++,function(){var r;p||++u!==l||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return a.redraw(t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var d=t._fullLayout._basePlotModules,m=!1;if(r)for(s=0;s=0;a--)if(x[a].enabled){r._indexToPoints=x[a]._indexToPoints;break}n&&n.calc&&(b=n.calc(t,r))}Array.isArray(b)&&b[0]||(b=[{x:h,y:h}]),b[0].t||(b[0].t={}),b[0].trace=r,d[i]=b}s.getComponentMethod("fx","calc")(t)},d.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},d.generalUpdatePerTraceModule=function(t,e,r,n){var i,a=e.traceHash,o={};for(i=0;i=0?h.angularAxis.domain:n.extent(w),E=Math.abs(w[1]-w[0]);k&&!M&&(E=0);var S=T.slice();A&&M&&(S[1]+=E);var L=h.angularAxis.ticksCount||4;L>8&&(L=L/(L/8)+L%8),h.angularAxis.ticksStep&&(L=(S[1]-S[0])/L);var C=h.angularAxis.ticksStep||(S[1]-S[0])/(L*(h.minorTicks+1));_&&(C=Math.max(Math.round(C),1)),S[2]||(S[2]=C);var P=n.range.apply(this,S);if(P=P.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=n.scale.linear().domain(S.slice(0,2)).range("clockwise"===h.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=s.domain(),u.layout.angularAxis.endPadding=A?E:0,void 0===(t=n.select(this).select("svg.chart-root"))||t.empty()){var z=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));t=n.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var D,I=t.select(".chart-group"),R={fill:"none",stroke:h.tickColor},N={"font-size":h.font.size,"font-family":h.font.family,fill:h.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+h.font.outlineColor}).join(",")};if(h.showLegend){D=t.select(".legend-group").attr({transform:"translate("+[y,h.margin.top]+")"}).style({display:"block"});var F=d.map(function(t,e){var r=o.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});o.Legend().config({data:d.map(function(t,e){return t.name||"Element"+e}),legendConfig:i({},o.Legend.defaultConfig().legendConfig,{container:D,elements:F,reverseOrder:h.legend.reverseOrder})})();var j=D.node().getBBox();y=Math.min(h.width-j.width-h.margin.left-h.margin.right,h.height-h.margin.top-h.margin.bottom)/2,y=Math.max(10,y),x=[h.margin.left+y,h.margin.top+y],r.range([0,y]),u.layout.radialAxis.domain=r.domain(),D.attr("transform","translate("+[x[0]+y,x[1]-y]+")")}else D=t.select(".legend-group").style({display:"none"});t.attr({width:h.width,height:h.height}).style({opacity:h.opacity}),I.attr("transform","translate("+x+")").style({cursor:"crosshair"});var B=[(h.width-(h.margin.left+h.margin.right+2*y+(j?j.width:0)))/2,(h.height-(h.margin.top+h.margin.bottom+2*y))/2];if(B[0]=Math.max(0,B[0]),B[1]=Math.max(0,B[1]),t.select(".outer-group").attr("transform","translate("+B+")"),h.title){var U=t.select("g.title-group text").style(N).text(h.title),V=U.node().getBBox();U.attr({x:x[0]-V.width/2,y:x[1]-y-20})}var q=t.select(".radial.axis-group");if(h.radialAxis.gridLinesVisible){var H=q.selectAll("circle.grid-circle").data(r.ticks(5));H.enter().append("circle").attr({class:"grid-circle"}).style(R),H.attr("r",r),H.exit().remove()}q.select("circle.outside-circle").attr({r:y}).style(R);var G=t.select("circle.background-circle").attr({r:y}).style({fill:h.backgroundColor,stroke:h.stroke});function Y(t,e){return s(t)%360+h.orientation}if(h.radialAxis.visible){var W=n.svg.axis().scale(r).ticks(5).tickSize(5);q.call(W).attr({transform:"rotate("+h.radialAxis.orientation+")"}),q.selectAll(".domain").style(R),q.selectAll("g>text").text(function(t,e){return this.textContent+h.radialAxis.ticksSuffix}).style(N).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===h.radialAxis.tickOrientation?"rotate("+-h.radialAxis.orientation+") translate("+[0,N["font-size"]]+")":"translate("+[0,N["font-size"]]+")"}}),q.selectAll("g>line").style({stroke:"black"})}var X=t.select(".angular.axis-group").selectAll("g.angular-tick").data(P),Z=X.enter().append("g").classed("angular-tick",!0);X.attr({transform:function(t,e){return"rotate("+Y(t)+")"}}).style({display:h.angularAxis.visible?"block":"none"}),X.exit().remove(),Z.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(h.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(h.minorTicks+1)==0)}).style(R),Z.selectAll(".minor").style({stroke:h.minorTickColor}),X.select("line.grid-line").attr({x1:h.tickLength?y-h.tickLength:0,x2:y}).style({display:h.angularAxis.gridLinesVisible?"block":"none"}),Z.append("text").classed("axis-text",!0).style(N);var J=X.select("text.axis-text").attr({x:y+h.labelOffset,dy:a+"em",transform:function(t,e){var r=Y(t),n=y+h.labelOffset,i=h.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:h.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(h.minorTicks+1)!=0?"":_?_[t]+h.angularAxis.ticksSuffix:t+h.angularAxis.ticksSuffix}).style(N);h.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(h.minorTicks+1)!=0?"":h.angularAxis.rewriteTicks(this.textContent,e)});var K=n.max(I.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));D.attr({transform:"translate("+[y+K,h.margin.top]+")"});var Q=t.select("g.geometry-group").selectAll("g").size()>0,$=t.select("g.geometry-group").selectAll("g.geometry").data(d);if($.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),$.exit().remove(),d[0]||Q){var tt=[];d.forEach(function(t,e){var n={};n.radialScale=r,n.angularScale=s,n.container=$.filter(function(t,r){return r==e}),n.geometry=t.geometry,n.orientation=h.orientation,n.direction=h.direction,n.index=e,tt.push({data:t,geometryConfig:n})});var et=[];n.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(tt).forEach(function(t,e){"unstacked"===t.key?et=et.concat(t.values.map(function(t,e){return[t]})):et.push(t.values)}),et.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return i(o[r].defaultConfig(),t)});o[r]().config(n)()})}var rt,nt,it=t.select(".guides-group"),at=t.select(".tooltips-group"),ot=o.tooltipPanel().config({container:at,fontSize:8})(),st=o.tooltipPanel().config({container:at,fontSize:8})(),lt=o.tooltipPanel().config({container:at,hasTick:!0})();if(!M){var ct=it.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});I.on("mousemove.angular-guide",function(t,e){var r=o.util.getMousePos(G).angle;ct.attr({x2:-y,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-h.orientation)%360;rt=s.invert(n);var i=o.util.convertToCartesian(y+12,r+180);ot.text(o.util.round(rt)).move([i[0]+x[0],i[1]+x[1]])}).on("mouseout.angular-guide",function(t,e){it.select("line").style({opacity:0})})}var ut=it.select("circle").style({stroke:"grey",fill:"none"});I.on("mousemove.radial-guide",function(t,e){var n=o.util.getMousePos(G).radius;ut.attr({r:n}).style({opacity:.5}),nt=r.invert(o.util.getMousePos(G).radius);var i=o.util.convertToCartesian(n,h.radialAxis.orientation);st.text(o.util.round(nt)).move([i[0]+x[0],i[1]+x[1]])}).on("mouseout.radial-guide",function(t,e){ut.style({opacity:0}),lt.hide(),ot.hide(),st.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var i=n.select(this),a=this.style.fill,s="black",l=this.style.opacity||1;if(i.attr({"data-opacity":l}),a&&"none"!==a){i.attr({"data-fill":a}),s=n.hsl(a).darker().toString(),i.style({fill:s,opacity:1});var c={t:o.util.round(e[0]),r:o.util.round(e[1])};M&&(c.t=_[e[0]]);var u="t: "+c.t+", r: "+c.r,f=this.getBoundingClientRect(),h=t.node().getBoundingClientRect(),d=[f.left+f.width/2-B[0]-h.left,f.top+f.height/2-B[1]-h.top];lt.config({color:s}).text(u),lt.move(d)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),s=n.hsl(a).darker().toString(),i.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=n.event.which)return!1;n.select(this).attr("data-fill")&<.show()}).on("mouseout.tooltip",function(t,e){lt.hide();var r=n.select(this),i=r.attr("data-fill");i?r.style({fill:i,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(c),this},h.config=function(t){if(!arguments.length)return l;var e=o.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),i(l.data[e],o.Axis.defaultConfig().data[0]),i(l.data[e],t)}),i(l.layout,o.Axis.defaultConfig().layout),i(l.layout,e.layout),this},h.getLiveConfig=function(){return u},h.getinputConfig=function(){return c},h.radialScale=function(t){return r},h.angularScale=function(t){return s},h.svg=function(){return t},n.rebind(h,f,"on"),h},o.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:n.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},o.util={},o.DATAEXTENT="dataExtent",o.AREA="AreaChart",o.LINE="LinePlot",o.DOT="DotPlot",o.BAR="BarChart",o.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},o.util._extend=function(t,e){for(var r in t)e[r]=t[r]},o.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},o.util.dataFromEquation2=function(t,e){var r=e||6;return n.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},o.util.dataFromEquation=function(t,e,r){var i=e||6,a=[],o=[];n.range(0,360+i,i).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},o.util.ensureArray=function(t,e){if(void 0===t)return null;var r=[].concat(t);return n.range(e).map(function(t,e){return r[e]||r[0]})},o.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=o.util.ensureArray(t[e],r)}),t},o.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},o.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},o.util.sumArrays=function(t,e){return n.zip(t,e).map(function(t,e){return n.sum(t)})},o.util.arrayLast=function(t){return t[t.length-1]},o.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},o.util.flattenArray=function(t){for(var e=[];!o.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},o.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},o.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},o.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},o.util.getMousePos=function(t){var e=n.mouse(t.node()),r=e[0],i=e[1],a={};return a.x=r,a.y=i,a.pos=e,a.angle=180*(Math.atan2(i,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+i*i),a},o.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=n.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:u(s),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return p.fill(r,i,a)},"fill-opacity":0,stroke:function(t,e){return p.stroke(r,i,a)},"stroke-width":function(t,e){return p["stroke-width"](r,i,a)},"stroke-dasharray":function(t,e){return p["stroke-dasharray"](r,i,a)},opacity:function(t,e){return p.opacity(r,i,a)},display:function(t,e){return p.display(r,i,a)}})}};var f=e.angularScale.range(),h=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,d=n.svg.arc().startAngle(function(t){return-h/2}).endAngle(function(t){return h/2}).innerRadius(function(t){return e.radialScale(l+(t[2]||0))}).outerRadius(function(t){return e.radialScale(l+(t[2]||0))+e.radialScale(t[1])});c.arc=function(t,r,i){n.select(this).attr({class:"mark arc",d:d,transform:function(t,r){return"rotate("+(e.orientation+s(t[0])+90)+")"}})};var p={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,i){return r[t[i].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},m=n.select(this).selectAll("g.layer").data(o);m.enter().append("g").attr({class:"layer"});var v=m.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[e.geometryType]),v.exit().remove(),m.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),i(t[r],o.PolyChart.defaultConfig()),i(t[r],e)}),this):t},a.getColorScale=function(){},n.rebind(a,e,"on"),a},o.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:n.scale.category20()}}},o.BarChart=function(){return o.PolyChart()},o.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},o.AreaChart=function(){return o.PolyChart()},o.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},o.DotPlot=function(){return o.PolyChart()},o.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},o.LinePlot=function(){return o.PolyChart()},o.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},o.Legend=function(){var t=o.Legend.defaultConfig(),e=n.dispatch("hover");function r(){var e=t.legendConfig,a=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var a=i({},e.elements[r]);return a.name=t,a.color=[].concat(e.elements[r].color)[n],a})}),o=n.merge(a);o=o.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||void 0===e.elements[r].visibleInLegend)}),e.reverseOrder&&(o=o.reverse());var s=e.container;("string"==typeof s||s.nodeName)&&(s=n.select(s));var l=o.map(function(t,e){return t.color}),c=e.fontSize,u=null==e.isContinuous?"number"==typeof o[0]:e.isContinuous,f=u?e.height:c*o.length,h=s.classed("legend-group",!0).selectAll("svg").data([0]),d=h.enter().append("svg").attr({width:300,height:f+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var p=n.range(o.length),m=n.scale[u?"linear":"ordinal"]().domain(p).range(l),v=n.scale[u?"linear":"ordinal"]().domain(p)[u?"range":"rangePoints"]([0,f]);if(u){var g=h.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);g.enter().append("stop"),g.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),h.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var y=h.select(".legend-marks").selectAll("path.legend-mark").data(o);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(t,e){return"translate("+[c/2,v(e)+c/2]+")"},d:function(t,e){var r,i,a,o=t.symbol;return a=3*(i=c),"line"===(r=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=n.svg.symbolTypes.indexOf(r)?n.svg.symbol().type(r).size(a)():n.svg.symbol().type("square").size(a)()},fill:function(t,e){return m(e)}}),y.exit().remove()}var b=n.svg.axis().scale(v).orient("right"),x=h.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:c,c/2]+")"}).call(b);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),x.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return o[e].name}),r}return r.config=function(e){return arguments.length?(i(t,e),this):t},n.rebind(r,e,"on"),r},o.Legend.defaultConfig=function(t,e){return{data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}}},o.tooltipPanel=function(){var t,e,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+o.tooltipPanel.uid++,l=10,c=function(){var n=(t=a.container.selectAll("g."+s).data([0])).enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=n.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=n.append("text").attr({dx:a.padding+l,dy:.3*+a.fontSize}),c};return c.text=function(i){var o=n.hsl(a.color).l,s=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",f=i||"";e.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var h=a.padding,d=e.node().getBBox(),p={fill:a.color,stroke:s,"stroke-width":"2px"},m=d.width+2*h+l,v=d.height+2*h;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[a.hasTick?0:l,0],[l,v/4],[l,v/2],[m,v/2],[m,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[l,-v/2+2*h]+")"}),t.style({display:"block"}),c},c.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c},c.hide=function(){if(t)return t.style({display:"none"}),c},c.show=function(){if(t)return t.style({display:"block"}),c},c.config=function(t){return i(a,t),c},c},o.tooltipPanel.uid=1,o.adapter={},o.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=i({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var a=o.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var n=a.indexOf(t.geometry);-1!=n&&(r.data[e].groupId=n)})}if(t.layout){var s=i({},t.layout);if([[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e?(void 0!==s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&void 0!==s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&void 0!==s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&void 0!==s.margin.t){var l=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],u={};n.entries(s.margin).forEach(function(t,e){u[c[l.indexOf(t.key)]]=t.value}),s.margin=u}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r}};return t}},{"../../../constants/alignment":696,"../../../lib":724,d3:128}],843:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../../lib"),a=t("../../../components/color"),o=t("./micropolar"),s=t("./undo_manager"),l=i.extendDeepAll,c=e.exports={};c.framework=function(t){var e,r,i,a,u,f=new s;function h(r,s){return s&&(u=s),n.select(n.select(u).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),e=e?l(e,r):r,i||(i=o.Axis()),a=o.adapter.plotly().convert(e),i.config(a).render(u),t.data=e.data,t.layout=e.layout,c.fillLayout(t),e}return h.isPolar=!0,h.svg=function(){return i.svg()},h.getConfig=function(){return e},h.getLiveConfig=function(){return o.adapter.plotly().convert(i.getLiveConfig(),!0)},h.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},h.setUndoPoint=function(){var t,n,i=this,a=o.util.cloneJson(e);t=a,n=r,f.add({undo:function(){n&&i(n)},redo:function(){i(t)}}),r=o.util.cloneJson(a)},h.undo=function(){f.undo()},h.redo=function(){f.redo()},h},c.fillLayout=function(t){var e=n.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),i=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:a.background,_container:e,_paperdiv:r,_paper:i};t._fullLayout=l(o,t.layout)}},{"../../../components/color":598,"../../../lib":724,"./micropolar":842,"./undo_manager":844,d3:128}],844:[function(t,e,r){"use strict";e.exports=function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r0?1:-1}function N(t){return R(Math.cos(t))}function F(t){return R(Math.sin(t))}e.exports=function(t,e){return new T(t,e)},E.plot=function(t,e){var r=e[this.id];this._hasClipOnAxisFalse=!1;for(var n=0;n=90||s>90&&l>=450?1:u<=0&&h<=0?0:Math.max(u,h);e=s<=180&&l>=180||s>180&&l>=540?-1:c>=0&&f>=0?0:Math.min(c,f);r=s<=270&&l>=270||s>270&&l>=630?-1:u>=0&&h>=0?0:Math.min(u,h);n=l>=360?1:c<=0&&f<=0?0:Math.max(c,f);return[e,r,n,i]}(g),b=y[2]-y[0],_=y[3]-y[1],M=v/m,k=Math.abs(_/b);M>k?(s=m,p=(v-(u=m*k))/i.h/2,h=[a[0],a[1]],d=[o[0]+p,o[1]-p]):(u=v,p=(m-(s=v/k))/i.w/2,h=[a[0]+p,a[1]-p],d=[o[0],o[1]]),r.xLength2=s,r.yLength2=u,r.xDomain2=h,r.yDomain2=d;var A=r.xOffset2=i.l+i.w*h[0],T=r.yOffset2=i.t+i.h*(1-d[1]),E=r.radius=s/b,S=r.cx=A-E*y[0],L=r.cy=T+E*y[3],C=r.cxx=S-A,z=r.cyy=L-T;r.updateRadialAxis(t,e),r.updateRadialAxisTitle(t,e),r.updateAngularAxis(t,e);var O=r.radialAxis.range,I=O[1]-O[0],R=r.xaxis={type:"linear",_id:"x",range:[y[0]*I,y[2]*I],domain:h};f.setConvert(R,t),R.setScale();var N=r.yaxis={type:"linear",_id:"y",range:[y[1]*I,y[3]*I],domain:d};f.setConvert(N,t),N.setScale(),R.isPtWithinRange=function(t){return r.isPtWithinSector(t)},N.isPtWithinRange=function(){return!0},n.frontplot.attr("transform",D(A,T)).call(c.setClipUrl,r._hasClipOnAxisFalse?null:r.clipIds.circle),n.bgcircle.attr({d:P(E,g),transform:D(S,L)}).call(l.fill,e.bgcolor),r.clipPaths.circle.select("path").attr("d",P(E,g)).attr("transform",D(C,z)),r.framework.selectAll(".crisp").classed("crisp",0)},E.updateRadialAxis=function(t,e){var r=this.gd,n=this.layers,i=this.radius,a=this.cx,o=this.cy,c=t._size,u=e.radialaxis,h=e.sector,d=w(h[0]);this.fillViewInitialKey("radialaxis.angle",u.angle);var p=this.radialAxis=s.extendFlat({},u,{_axislayer:n["radial-axis"],_gridlayer:n["radial-grid"],_id:"x",_pos:0,side:{counterclockwise:"top",clockwise:"bottom"}[u.side],domain:[0,i/c.w],anchor:"free",position:0,_counteraxis:!0});S(p,u,t),f.doAutoRange(p),u.range=p.range.slice(),u._input.range=p.range.slice(),this.fillViewInitialKey("radialaxis.range",p.range.slice()),"auto"===p.tickangle&&d>90&&d<=270&&(p.tickangle=180),p._transfn=function(t){return"translate("+p.l2p(t.x)+",0)"},p._gridpath=function(t){return C(p.r2p(t.x),h)};var m=L(u);this.radialTickLayout!==m&&(n["radial-axis"].selectAll(".xtick").remove(),this.radialTickLayout=m),f.doTicks(r,p,!0),O(n["radial-axis"],u.showticklabels||u.ticks,{transform:D(a,o)+I(-u.angle)}),O(n["radial-grid"],u.showgrid,{transform:D(a,o)}).selectAll("path").attr("transform",null),O(n["radial-line"].select("line"),u.showline,{x1:0,y1:0,x2:i,y2:0,transform:D(a,o)+I(-u.angle)}).attr("stroke-width",u.linewidth).call(l.stroke,u.linecolor)},E.updateRadialAxisTitle=function(t,e,r){var n=this.gd,i=this.radius,a=this.cx,o=this.cy,s=e.radialaxis,l=this.id+"title",u=void 0!==r?r:s.angle,f=x(u),h=Math.cos(f),d=Math.sin(f),p=0;if(s.title){var v=c.bBox(this.layers["radial-axis"].node()).height,g=s.titlefont.size;p="counterclockwise"===s.side?-v-.4*g:v+.8*g}this.layers["radial-axis-title"]=m.draw(n,l,{propContainer:s,propName:this.id+".radialaxis.title",placeholder:b(n,"Click to enter radial axis title"),attributes:{x:a+i/2*h+p*d,y:o-i/2*d+p*h,"text-anchor":"middle"},transform:{rotate:-u}})},E.updateAngularAxis=function(t,e){var r=this,i=r.gd,a=r.layers,o=r.radius,c=r.cx,u=r.cy,h=e.angularaxis,d=e.sector,p=d.map(x);r.fillViewInitialKey("angularaxis.rotation",h.rotation);var m=r.angularAxis=s.extendFlat({},h,{_axislayer:a["angular-axis"],_gridlayer:a["angular-grid"],_id:"angular",_pos:0,side:"right",domain:[0,Math.PI],anchor:"free",position:0,_counteraxis:!0});function v(t){return m.c2rad(t.x,"degrees")}function g(t){return[o*Math.cos(t),o*Math.sin(t)]}"linear"===m.type?(m.autorange=!1,z(d)?m.range=d.slice():m.range=p.map(m.unTransformRad).map(_),"radians"===m.thetaunit&&(m.tick0=_(m.tick0),m.dtick=_(m.dtick))):"category"===m.type&&(m._tickFilter=function(t){return r.isPtWithinSector({r:r.radialAxis.range[1],rad:m.c2rad(t.x)})}),S(m,h,t),f.doAutoRange(m),m._transfn=function(t){var e=v(t),r=g(e),i=D(c+r[0],u-r[1]),a=n.select(this);return a&&a.node()&&a.classed("ticks")&&(i+=I(-_(e))),i},m._gridpath=function(t){var e=g(v(t));return"M0,0L"+-e[0]+","+e[1]};var b="outside"!==h.ticks?.7:.5;m._labelx=function(t){var e=v(t),r=m._labelStandoff,n=m._pad;return(0===F(e)?0:Math.cos(e)*(r+n+b*t.fontSize))+N(e)*(t.dx+r+n)},m._labely=function(t){var e=v(t),r=m._labelStandoff,n=m._labelShift,i=m._pad;return t.dy+t.fontSize*y-n+-Math.sin(e)*(r+i+b*t.fontSize)},m._labelanchor=function(t,e){var r=v(e);return 0===F(r)?N(r)>0?"start":"end":"middle"};var w=L(h);r.angularTickLayout!==w&&(a["angular-axis"].selectAll(".angulartick").remove(),r.angularTickLayout=w),f.doTicks(i,m,!0),O(a["angular-line"].select("path"),h.showline,{d:P(o,d),transform:D(c,u)}).attr("stroke-width",h.linewidth).call(l.stroke,h.linecolor)},E.updateFx=function(t,e){this.gd._context.staticPlot||(this.updateAngularDrag(t,e),this.updateRadialDrag(t,e),this.updateMainDrag(t,e))},E.updateMainDrag=function(t,e){var r=this,o=r.gd,s=r.layers,l=t._zoomlayer,c=A.MINZOOM,u=A.OFFEDGE,f=r.radius,m=r.cx,g=r.cy,y=r.cxx,b=r.cyy,x=e.sector,_=d.makeDragger(s,"path","maindrag","crosshair");n.select(_).attr("d",P(f,x)).attr("transform",D(m,g));var w,M,k,T,E,S,L,C,z,O={element:_,gd:o,subplot:r.id,plotinfo:{xaxis:r.xaxis,yaxis:r.yaxis},xaxes:[r.xaxis],yaxes:[r.yaxis]};function I(t,e){var r=t-y,n=e-b;return Math.sqrt(r*r+n*n)}function R(t,e){return Math.atan2(b-e,t-y)}function N(t,e){return[t*Math.cos(e),t*Math.sin(-e)]}function F(t,e){var r=A.cornerLen,n=A.cornerHalfWidth;if(0===t)return P(2*n,x);var i=r/t/2,a=e-i,o=e+i,s=Math.max(0,Math.min(t,f)),l=s-n,c=s+n;return"M"+N(l,a)+"A"+[l,l]+" 0,0,0 "+N(l,o)+"L"+N(c,o)+"A"+[c,c]+" 0,0,1 "+N(c,a)+"Z"}function j(t,e){var r,n,i=w+t,a=M+e,o=I(w,M),s=Math.min(I(i,a),f),l=R(w,M),h=R(i,a);oc?(o0==a>y[0]){E=m.range[1]=a,f.doTicks(i,r.radialAxis,!0),l["radial-grid"].attr("transform",D(u,p)).selectAll("path").attr("transform",null);var h=E-y[0],d=r.sectorBBox;for(var v in r.xaxis.range=[d[0]*h,d[2]*h],r.yaxis.range=[d[1]*h,d[3]*h],r.xaxis.setScale(),r.yaxis.setScale(),r.traceHash){var x=r.traceHash[v],_=s.filterVisible(x),w=x[0][0].trace._module,M=i._fullLayout[r.id];if(w.plot(i,r,_,M),!o.traceIs(v,"gl"))for(var k=0;k<_.length;k++)w.style(i,_[k])}}}},E.updateAngularDrag=function(t,e){var r=this,i=r.gd,l=r.layers,u=r.radius,p=r.cx,m=r.cy,v=r.cxx,y=r.cyy,b=e.sector,w=A.angularDragBoxSize,T=d.makeDragger(l,"path","angulardrag","move"),E={element:T,gd:i};function S(t,e){return Math.atan2(y+w-e,t-v-w)}n.select(T).attr("d",function(t,e,r){var n,i,a,o=Math.abs(r[1]-r[0])<=180?0:1;function s(t,e){return[t*Math.cos(e),-t*Math.sin(e)]}function l(t,e,r){return"A"+[t,t]+" "+[0,o,r]+" "+s(t,e)}return z(r)?(n=0,a=2*Math.PI,i=Math.PI,"M"+s(t,n)+l(t,i,0)+l(t,a,0)+"ZM"+s(e,n)+l(e,i,1)+l(e,a,1)+"Z"):(n=x(r[0]),a=x(r[1]),"M"+s(t,n)+"L"+s(e,n)+l(e,a,0)+"L"+s(t,a)+l(t,n,1)+"Z")}(u,u+w,b)).attr("transform",D(p,m)).call(g,"move");var L,C,P,O,R,N,F=l.frontplot.select(".scatterlayer").selectAll(".trace"),j=F.selectAll(".point"),B=F.selectAll(".textpoint");function U(t,e){var a=S(L+t,C+e),u=_(a-N);O=P+u,l.frontplot.attr("transform",D(r.xOffset2,r.yOffset2)+I([-u,v,y])),r.clipPaths.circle.select("path").attr("transform",D(v,y)+I(u)),j.each(function(){var t=n.select(this),e=c.getTranslate(t);t.attr("transform",D(e.x,e.y)+I([u]))}),B.each(function(){var t=n.select(this),e=t.select("text"),r=c.getTranslate(t);t.attr("transform",I([u,e.attr("x"),e.attr("y")])+D(r.x,r.y))});var h=r.angularAxis;for(var d in h.rotation=M(O),"linear"!==h.type||z(b)||(h.range=R.map(x).map(h.unTransformRad).map(_)),k(h),f.doTicks(i,h,!0),r._hasClipOnAxisFalse&&!z(b)&&(r.sector=[R[0]-u,R[1]-u],F.call(c.hideOutsideRangePoints,r)),r.traceHash)if(o.traceIs(d,"gl")){var p=r.traceHash[d],m=s.filterVisible(p),g=p[0][0].trace._module,w=i._fullLayout[r.id];g.plot(i,r,m,w)}}function V(){B.select("text").attr("transform",null);var t={};t[r.id+".angularaxis.rotation"]=O,a.relayout(i,t)}E.prepFn=function(e,n,i){var a=t[r.id];R=a.sector.slice(),P=a.angularaxis.rotation;var o=T.getBoundingClientRect();L=n-o.left,C=i-o.top,N=S(L,C),E.moveFn=U,E.doneFn=V,d.clearSelect(t._zoomlayer)},h.init(E)},E.isPtWithinSector=function(t){var e=this.sector,r=this.radialAxis,n=r.range,i=r.c2r(t.r),a=w(e[0]),o=w(e[1]);a>o&&(o+=360);var s,l,c=w(_(t.rad)),u=c+360;return n[1]>=n[0]?(s=n[0],l=n[1]):(s=n[1],l=n[0]),i>=s&&i<=l&&(z(e)||c>=a&&c<=o||u>=a&&u<=o)},E.fillViewInitialKey=function(t,e){t in this.viewInitial||(this.viewInitial[t]=e)}},{"../../components/color":598,"../../components/dragelement":620,"../../components/drawing":623,"../../components/fx":640,"../../components/titles":689,"../../constants/alignment":696,"../../lib":724,"../../lib/setcursor":743,"../../plotly":765,"../../registry":854,"../cartesian/axes":770,"../cartesian/dragbox":778,"../cartesian/select":788,"../plots":833,"./constants":834,"./helpers":835,d3:128,tinycolor2:526}],846:[function(t,e,r){"use strict";var n=t("../lib");e.exports=function(t,e,r,i){var a,o,s=i.type,l=i.attributes,c=i.handleDefaults,u=i.partition||"x",f=e._subplots[s],h=f.length;function d(t,e){return n.coerce(a,o,l,t,e)}for(var p=0;p=f&&(d.min=0,p.min=0,m.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}e.exports=function(t,e,r){i(t,e,r,{type:"ternary",attributes:a,handleDefaults:l,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../../components/color":598,"../../subplot_defaults":846,"./axis_defaults":850,"./layout_attributes":852}],852:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("../../domain_attributes"),a=t("./axis_attributes"),o=t("../../../plot_api/edit_types").overrideAll;e.exports=o({domain:i({name:"ternary"}),bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:a,baxis:a,caxis:a},"plot","from-root")},{"../../../components/color/attributes":597,"../../../plot_api/edit_types":754,"../../domain_attributes":796,"./axis_attributes":849}],853:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("../../plotly"),o=t("../../lib"),s=o._,l=t("../../components/color"),c=t("../../components/drawing"),u=t("../cartesian/set_convert"),f=t("../../lib/extend").extendFlat,h=t("../plots"),d=t("../cartesian/axes"),p=t("../../components/dragelement"),m=t("../../components/fx"),v=t("../../components/titles"),g=t("../cartesian/select"),y=t("../cartesian/constants");function b(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework(e)}e.exports=b;var x=b.prototype;x.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={},this.layers={}},x.plot=function(t,e){var r=e[this.id],n=e._size;this._hasClipOnAxisFalse=!1;for(var i=0;i_*b?i=(a=b)*_:a=(i=y)/_,o=v*i/y,s=g*a/b,r=e.l+e.w*p-i/2,n=e.t+e.h*(1-m)-a/2,h.x0=r,h.y0=n,h.w=i,h.h=a,h.sum=x,h.xaxis={type:"linear",range:[w+2*k-x,x-w-2*M],domain:[p-o/2,p+o/2],_id:"x"},u(h.xaxis,h.graphDiv._fullLayout),h.xaxis.setScale(),h.xaxis.isPtWithinRange=function(t){return t.a>=h.aaxis.range[0]&&t.a<=h.aaxis.range[1]&&t.b>=h.baxis.range[1]&&t.b<=h.baxis.range[0]&&t.c>=h.caxis.range[1]&&t.c<=h.caxis.range[0]},h.yaxis={type:"linear",range:[w,x-M-k],domain:[m-s/2,m+s/2],_id:"y"},u(h.yaxis,h.graphDiv._fullLayout),h.yaxis.setScale(),h.yaxis.isPtWithinRange=function(){return!0};var A=h.yaxis.domain[0],T=h.aaxis=f({},t.aaxis,{visible:!0,range:[w,x-M-k],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[A,A+s*_],_axislayer:h.layers.aaxis,_gridlayer:h.layers.agrid,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2});u(T,h.graphDiv._fullLayout),T.setScale();var E=h.baxis=f({},t.baxis,{visible:!0,range:[x-w-k,M],side:"bottom",_counterangle:30,domain:h.xaxis.domain,_axislayer:h.layers.baxis,_gridlayer:h.layers.bgrid,_counteraxis:h.aaxis,_pos:0,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a});u(E,h.graphDiv._fullLayout),E.setScale(),T._counteraxis=E;var S=h.caxis=f({},t.caxis,{visible:!0,range:[x-w-M,k],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[A,A+s*_],_axislayer:h.layers.caxis,_gridlayer:h.layers.cgrid,_counteraxis:h.baxis,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2});u(S,h.graphDiv._fullLayout),S.setScale();var L="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";h.clipDef.select("path").attr("d",L),h.layers.plotbg.select("path").attr("d",L);var C="M0,"+a+"h"+i+"l-"+i/2+",-"+a+"Z";h.clipDefRelative.select("path").attr("d",C);var P="translate("+r+","+n+")";h.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",P),h.clipDefRelative.select("path").attr("transform",null);var z="translate("+(r-E._offset)+","+(n+a)+")";h.layers.baxis.attr("transform",z),h.layers.bgrid.attr("transform",z);var O="translate("+(r+i/2)+","+n+")rotate(30)translate(0,"+-T._offset+")";h.layers.aaxis.attr("transform",O),h.layers.agrid.attr("transform",O);var D="translate("+(r+i/2)+","+n+")rotate(-30)translate(0,"+-S._offset+")";h.layers.caxis.attr("transform",D),h.layers.cgrid.attr("transform",D),h.drawAxes(!0),h.plotContainer.selectAll(".crisp").classed("crisp",!1),h.layers.aline.select("path").attr("d",T.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(l.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),h.layers.bline.select("path").attr("d",E.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(l.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px"),h.layers.cline.select("path").attr("d",S.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(l.stroke,S.linecolor||"#000").style("stroke-width",(S.linewidth||0)+"px"),h.graphDiv._context.staticPlot||h.initInteractions(),c.setClipUrl(h.layers.frontplot,h._hasClipOnAxisFalse?null:h.clipId)},x.drawAxes=function(t){var e=this.graphDiv,r=this.id.substr(7)+"title",n=this.aaxis,i=this.baxis,a=this.caxis;if(d.doTicks(e,n,!0),d.doTicks(e,i,!0),d.doTicks(e,a,!0),t){var o=Math.max(n.showticklabels?n.tickfont.size/2:0,(a.showticklabels?.75*a.tickfont.size:0)+("outside"===a.ticks?.87*a.ticklen:0));this.layers["a-title"]=v.draw(e,"a"+r,{propContainer:n,propName:this.id+".aaxis.title",placeholder:s(e,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-n.titlefont.size/3-o,"text-anchor":"middle"}});var l=(i.showticklabels?i.tickfont.size:0)+("outside"===i.ticks?i.ticklen:0)+3;this.layers["b-title"]=v.draw(e,"b"+r,{propContainer:i,propName:this.id+".baxis.title",placeholder:s(e,"Click to enter Component B title"),attributes:{x:this.x0-l,y:this.y0+this.h+.83*i.titlefont.size+l,"text-anchor":"middle"}}),this.layers["c-title"]=v.draw(e,"c"+r,{propContainer:a,propName:this.id+".caxis.title",placeholder:s(e,"Click to enter Component C title"),attributes:{x:this.x0+this.w+l,y:this.y0+this.h+.83*a.titlefont.size+l,"text-anchor":"middle"}})}};var w=y.MINZOOM/2+.87,M="m-0.87,.5h"+w+"v3h-"+(w+5.2)+"l"+(w/2+2.6)+",-"+(.87*w+4.5)+"l2.6,1.5l-"+w/2+","+.87*w+"Z",k="m0.87,.5h-"+w+"v3h"+(w+5.2)+"l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-2.6,1.5l"+w/2+","+.87*w+"Z",A="m0,1l"+w/2+","+.87*w+"l2.6,-1.5l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-"+(w/2+2.6)+","+(.87*w+4.5)+"l2.6,1.5l"+w/2+",-"+.87*w+"Z",T="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",E=!0;function S(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}x.initInteractions=function(){var t,e,r,n,u,f,h,d,v,b,x=this,w=x.layers.plotbg.select("path").node(),L=x.graphDiv,C=L._fullLayout._zoomlayer,P={element:w,gd:L,plotinfo:{xaxis:x.xaxis,yaxis:x.yaxis},subplot:x.id,prepFn:function(a,o,s){P.xaxes=[x.xaxis],P.yaxes=[x.yaxis];var c=L._fullLayout.dragmode;a.shiftKey&&(c="pan"===c?"zoom":"pan"),P.minDrag="lasso"===c?1:void 0,"zoom"===c?(P.moveFn=I,P.doneFn=R,function(a,o,s){var c=w.getBoundingClientRect();t=o-c.left,e=s-c.top,r={a:x.aaxis.range[0],b:x.baxis.range[1],c:x.caxis.range[1]},u=r,n=x.aaxis.range[1]-r.a,f=i(x.graphDiv._fullLayout[x.id].bgcolor).getLuminance(),h="M0,"+x.h+"L"+x.w/2+", 0L"+x.w+","+x.h+"Z",d=!1,v=C.append("path").attr("class","zoombox").attr("transform","translate("+x.x0+", "+x.y0+")").style({fill:f>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",h),b=C.append("path").attr("class","zoombox-corners").attr("transform","translate("+x.x0+", "+x.y0+")").style({fill:l.background,stroke:l.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),j()}(0,o,s)):"pan"===c?(P.moveFn=N,P.doneFn=F,r={a:x.aaxis.range[0],b:x.baxis.range[1],c:x.caxis.range[1]},u=r,j()):"select"!==c&&"lasso"!==c||g(a,o,s,P,c)},clickFn:function(t,e){if(S(L),2===t){var r={};r[x.id+".aaxis.min"]=0,r[x.id+".baxis.min"]=0,r[x.id+".caxis.min"]=0,L.emit("plotly_doubleclick",null),a.relayout(L,r)}m.click(L,e,x.id)}};function z(t,e){return 1-e/x.h}function O(t,e){return 1-(t+(x.h-e)/Math.sqrt(3))/x.w}function D(t,e){return(t-(x.h-e)/Math.sqrt(3))/x.w}function I(i,a){var o=t+i,s=e+a,l=Math.max(0,Math.min(1,z(0,e),z(0,s))),c=Math.max(0,Math.min(1,O(t,e),O(o,s))),p=Math.max(0,Math.min(1,D(t,e),D(o,s))),m=(l/2+p)*x.w,g=(1-l/2-c)*x.w,w=(m+g)/2,E=g-m,S=(1-l)*x.h,L=S-E/_;E.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),b.transition().style("opacity",1).duration(200),d=!0)}function R(){if(S(L),u!==r){var t={};t[x.id+".aaxis.min"]=u.a,t[x.id+".baxis.min"]=u.b,t[x.id+".caxis.min"]=u.c,a.relayout(L,t),E&&L.data&&L._context.showTips&&(o.notifier(s(L,"Double-click to zoom back out"),"long"),E=!1)}}function N(t,e){var n=t/x.xaxis._m,i=e/x.yaxis._m,a=[(u={a:r.a-i,b:r.b+(n+i)/2,c:r.c-(n-i)/2}).a,u.b,u.c].sort(),o=a.indexOf(u.a),s=a.indexOf(u.b),l=a.indexOf(u.c);a[0]<0&&(a[1]+a[0]/2<0?(a[2]+=a[0]+a[1],a[0]=a[1]=0):(a[2]+=a[0]/2,a[1]+=a[0]/2,a[0]=0),u={a:a[o],b:a[s],c:a[l]},e=(r.a-u.a)*x.yaxis._m,t=(r.c-u.c-r.b+u.b)*x.xaxis._m);var f="translate("+(x.x0+t)+","+(x.y0+e)+")";x.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",f);var h="translate("+-t+","+-e+")";x.clipDefRelative.select("path").attr("transform",h),x.aaxis.range=[u.a,x.sum-u.b-u.c],x.baxis.range=[x.sum-u.a-u.c,u.b],x.caxis.range=[x.sum-u.a-u.b,u.c],x.drawAxes(!1),x.plotContainer.selectAll(".crisp").classed("crisp",!1),x._hasClipOnAxisFalse&&x.plotContainer.select(".scatterlayer").selectAll(".trace").call(c.hideOutsideRangePoints,x)}function F(){var t={};t[x.id+".aaxis.min"]=u.a,t[x.id+".baxis.min"]=u.b,t[x.id+".caxis.min"]=u.c,a.relayout(L,t)}function j(){C.selectAll(".select-outline").remove()}w.onmousemove=function(t){m.hover(L,t,x.id),L._fullLayout._lasthover=w,L._fullLayout._hoversubplot=x.id},w.onmouseout=function(t){L._dragging||p.unhover(L,t)},p.init(P)}},{"../../components/color":598,"../../components/dragelement":620,"../../components/drawing":623,"../../components/fx":640,"../../components/titles":689,"../../lib":724,"../../lib/extend":713,"../../plotly":765,"../cartesian/axes":770,"../cartesian/constants":775,"../cartesian/select":788,"../cartesian/set_convert":789,"../plots":833,d3:128,tinycolor2:526}],854:[function(t,e,r){"use strict";var n=t("./lib/loggers"),i=t("./lib/noop"),a=t("./lib/push_unique"),o=t("./lib/extend"),s=o.extendFlat,l=o.extendDeepAll,c=t("./plots/attributes"),u=t("./plots/layout_attributes");function f(t){if(t.layoutAttributes){var e=t.layoutAttributes._arrayAttrRegexps;if(e)for(var n=0;n-1&&(u[h[r]].title="");for(r=0;r")?"":e.html(t).text()});return e.remove(),r}(_),_=(_=_.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(c,"'"),i.isIE()&&(_=(_=(_=_.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),_}},{"../components/color":598,"../components/drawing":623,"../constants/xmlns_namespaces":704,"../lib":724,d3:128}],863:[function(t,e,r){"use strict";var n=t("../../lib").mergeArray;e.exports=function(t,e){for(var r=0;ra;if(!o)return e}return void 0!==r?r:t.dflt}(t.size,s,n.size),color:function(t,e,r){return a(e).isValid()?e:void 0!==r?r:t.dflt}(t.color,l,n.color)}}function x(t,e){var r;return Array.isArray(t)?e.01?N:function(t,e){return Math.abs(t-e)>=2?N(t):t>e?Math.ceil(t):Math.floor(t)};T=I(T,u=I(u,T)),S=I(S,E=I(E,S))}var R=n.select(this);R.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+u+","+E+"V"+S+"H"+T+"V"+E+"Z"),function(t,e,r,n,i,a,o,l){var u;function f(e,r,n){var i=e.append("text").text(r).attr({class:"bartext bartext-"+u,transform:"","text-anchor":"middle","data-notex":1}).call(c.font,n).call(s.convertToTspans,t);return i}var w=r[0].trace,M=w.orientation,k=function(t,e){var r=x(t.text,e);return _(h,r)}(w,n);if(!k)return;if("none"===(u=function(t,e){var r=x(t.textposition,e);return function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt}(d,r)}(w,n)))return;var A,T,E,S,L,C,P=function(t,e,r){return b(p,t.textfont,e,r)}(w,n,t._fullLayout.font),z=function(t,e,r){return b(m,t.insidetextfont,e,r)}(w,n,P),O=function(t,e,r){return b(v,t.outsidetextfont,e,r)}(w,n,P),D=t._fullLayout.barmode,I="stack"===D||"relative"===D,R=r[n],N=!I||R._outmost,F=Math.abs(a-i)-2*g,j=Math.abs(l-o)-2*g;"outside"===u&&(N||(u="inside"));if("auto"===u)if(N){u="inside",A=f(e,k,z),T=c.bBox(A.node()),E=T.width,S=T.height;var B=E>0&&S>0,U=E<=F&&S<=j,V=E<=j&&S<=F,q="h"===M?F>=E*(j/S):j>=S*(F/E);B&&(U||V||q)?u="inside":(u="outside",A.remove(),A=null)}else u="inside";if(!A&&(A=f(e,k,"outside"===u?O:z),T=c.bBox(A.node()),E=T.width,S=T.height,E<=0||S<=0))return void A.remove();"outside"===u?(C="both"===w.constraintext||"outside"===w.constraintext,L=function(t,e,r,n,i,a,o){var s,l="h"===a?Math.abs(n-r):Math.abs(e-t);l>2*g&&(s=g);var c=1;o&&(c="h"===a?Math.min(1,l/i.height):Math.min(1,l/i.width));var u,f,h,d,p=(i.left+i.right)/2,m=(i.top+i.bottom)/2;u=c*i.width,f=c*i.height,"h"===a?er?(h=(t+e)/2,d=n+s+f/2):(h=(t+e)/2,d=n-s-f/2);return y(p,m,h,d,c,!1)}(i,a,o,l,T,M,C)):(C="both"===w.constraintext||"inside"===w.constraintext,L=function(t,e,r,n,i,a,o){var s,l,c,u,f,h,d,p=i.width,m=i.height,v=(i.left+i.right)/2,b=(i.top+i.bottom)/2,x=Math.abs(e-t),_=Math.abs(n-r);x>2*g&&_>2*g?(x-=2*(f=g),_-=2*f):f=0;p<=x&&m<=_?(h=!1,d=1):p<=_&&m<=x?(h=!0,d=1):pr?(c=(t+e)/2,u=n-f-l/2):(c=(t+e)/2,u=n+f+l/2);return y(v,b,c,u,d,h)}(i,a,o,l,T,M,C));A.attr("transform",L)}(t,R,e,o,u,T,E,S)}else n.select(this).remove();function N(t){return 0===w.bargap&&0===w.bargroupgap?n.round(Math.round(t)-D,2):t}})}),M.call(u.plot,e)}},{"../../components/color":598,"../../components/drawing":623,"../../components/errorbars":629,"../../lib":724,"../../lib/svg_text_utils":747,"./attributes":864,d3:128,"fast-isnumeric":140,tinycolor2:526}],872:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[];if(!1===e)for(r=0;rf+c||!n(u))&&(d=!0,p(h,t))}for(var v=0;v1||0===s.bargap&&0===s.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(e){var r=n.select(this),a=r.selectAll("path"),o=r.selectAll("text"),s=e[0].trace;i.pointStyle(a,s,t),i.selectedPointStyle(a,s),o.each(function(t){var e,r=n.select(this);function a(r){var n=e[r];return Array.isArray(n)?n[t.i]:n}r.classed("bartext-inside")?e=s.insidetextfont:r.classed("bartext-outside")&&(e=s.outsidetextfont),e||(e=s.textfont),i.font(r,a("family"),a("size"),a("color"))}),i.selectedTextStyle(o,s)}),a.style(r)}},{"../../components/drawing":623,"../../components/errorbars":629,d3:128}],876:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width"),r("marker.opacity"),r("selected.marker.color"),r("unselected.marker.color")}},{"../../components/color":598,"../../components/colorscale/defaults":608,"../../components/colorscale/has_colorscale":612}],877:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array",editType:"calc+clearAxisTypes"},x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",editType:"calc+clearAxisTypes"},y0:{valType:"any",editType:"calc+clearAxisTypes"},name:{valType:"string",editType:"calc+clearAxisTypes"},text:a({},n.text,{}),whiskerwidth:{valType:"number",min:0,max:1,dflt:.5,editType:"calcIfAutorange"},notched:{valType:"boolean",editType:"calcIfAutorange"},notchwidth:{valType:"number",min:0,max:.5,dflt:.25,editType:"calcIfAutorange"},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers",editType:"calcIfAutorange"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1,editType:"calcIfAutorange"},jitter:{valType:"number",min:0,max:1,editType:"calcIfAutorange"},pointpos:{valType:"number",min:-2,max:2,editType:"calcIfAutorange"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)",editType:"style"},symbol:a({},o.symbol,{arrayOk:!1,editType:"plot"}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1,editType:"style"}),size:a({},o.size,{arrayOk:!1,editType:"calcIfAutorange"}),color:a({},o.color,{arrayOk:!1,editType:"style"}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine,editType:"style"}),width:a({},s.width,{arrayOk:!1,dflt:0,editType:"style"}),outliercolor:{valType:"color",editType:"style"},outlierwidth:{valType:"number",min:0,dflt:1,editType:"style"},editType:"style"},editType:"plot"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:n.fillcolor,selected:{marker:n.selected.marker,editType:"style"},unselected:{marker:n.unselected.marker,editType:"style"},hoveron:{valType:"flaglist",flags:["boxes","points"],dflt:"boxes+points",editType:"style"}}},{"../../components/color/attributes":597,"../../lib/extend":713,"../scatter/attributes":1048}],878:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=i._,o=t("../../plots/cartesian/axes");function s(t,e,r){var n={text:"tx"};for(var i in n)Array.isArray(e[i])&&(t[n[i]]=e[i][r])}function l(t,e){return t.v-e.v}function c(t){return t.v}e.exports=function(t,e){var r,u,f,h,d,p=t._fullLayout,m=o.getFromId(t,e.xaxis||"x"),v=o.getFromId(t,e.yaxis||"y"),g=[],y="violin"===e.type?"_numViolins":"_numBoxes";"h"===e.orientation?(u=m,f="x",h=v,d="y"):(u=v,f="y",h=m,d="x");var b=u.makeCalcdata(e,f),x=function(t,e,r,a,o){if(e in t)return r.makeCalcdata(t,e);var s;s=e+"0"in t?t[e+"0"]:"name"in t&&("category"===r.type||n(t.name)&&-1!==["linear","log"].indexOf(r.type)||i.isDateTime(t.name)&&"date"===r.type)?t.name:o;var l=r.d2c(s,0,t[e+"calendar"]);return a.map(function(){return l})}(e,d,h,b,p[y]),_=i.distinctVals(x),w=_.vals,M=_.minDiff/2,k=function(t,e){for(var r=t.length,n=new Array(r+1),i=0;i=0&&L0){var P=E[r].sort(l),z=P.map(c),O=z.length,D={pos:w[r],pts:P};D.min=z[0],D.max=z[O-1],D.mean=i.mean(z,O),D.sd=i.stdev(z,O,D.mean),D.q1=i.interp(z,.25),D.med=i.interp(z,.5),D.q3=i.interp(z,.75),D.lf=Math.min(D.q1,z[Math.min(i.findBin(2.5*D.q1-1.5*D.q3,z,!0)+1,O-1)]),D.uf=Math.max(D.q3,z[Math.max(i.findBin(2.5*D.q3-1.5*D.q1,z),0)]),D.lo=4*D.q1-3*D.q3,D.uo=4*D.q3-3*D.q1;var I=1.57*(D.q3-D.q1)/Math.sqrt(O);D.ln=D.med-I,D.un=D.med+I,g.push(D)}return function(t,e){if(Array.isArray(e.selectedpoints))for(var r=0;r0?(g[0].t={num:p[y],dPos:M,posLetter:d,valLetter:f,labels:{med:a(t,"median:"),min:a(t,"min:"),q1:a(t,"q1:"),q3:a(t,"q3:"),max:a(t,"max:"),mean:"sd"===e.boxmean?a(t,"mean \xb1 \u03c3:"):a(t,"mean:"),lf:a(t,"lower fence:"),uf:a(t,"upper fence:")}},e._fullInput&&"candlestick"===e._fullInput.type&&delete g[0].t.labels,p[y]++,g):[{t:{empty:!0}}]}},{"../../lib":724,"../../plots/cartesian/axes":770,"fast-isnumeric":140}],879:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../registry"),a=t("../../components/color"),o=t("./attributes");function s(t,e,r,n){var a,o=r("y"),s=r("x");if(o&&o.length)a="v",s||r("x0");else{if(!s||!s.length)return void(e.visible=!1);a="h",r("y0")}i.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],n),r("orientation",a)}function l(t,e,r,i){var a=i.prefix,s=n.coerce2(t,e,o,"marker.outliercolor"),l=r("marker.line.outliercolor"),c=r(a+"points",s||l?"suspectedoutliers":void 0);c?(r("jitter","all"===c?.3:0),r("pointpos","all"===c?-1.5:0),r("marker.symbol"),r("marker.opacity"),r("marker.size"),r("marker.color",e.line.color),r("marker.line.color"),r("marker.line.width"),"suspectedoutliers"===c&&(r("marker.line.outliercolor",e.marker.color),r("marker.line.outlierwidth")),r("selected.marker.color"),r("unselected.marker.color"),r("selected.marker.size"),r("unselected.marker.size"),r("text")):delete e.marker,r("hoveron"),n.coerceSelectionMarkerOpacity(e,r)}e.exports={supplyDefaults:function(t,e,r,i){function c(r,i){return n.coerce(t,e,o,r,i)}s(t,e,c,i),!1!==e.visible&&(c("line.color",(t.marker||{}).color||r),c("line.width"),c("fillcolor",a.addOpacity(e.line.color,.5)),c("whiskerwidth"),c("boxmean"),c("notched",void 0!==t.notchwidth)&&c("notchwidth"),l(t,e,c,{prefix:"box"}))},handleSampleDefaults:s,handlePointsDefaults:l}},{"../../components/color":598,"../../lib":724,"../../registry":854,"./attributes":877}],880:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib"),a=t("../../components/fx"),o=t("../../components/color"),s=t("../scatter/fill_hover_text");function l(t,e,r,s){var l,c,u,f,h,d,p,m,v,g,y=t.cd,b=t.xa,x=t.ya,_=y[0].trace,w=y[0].t,M="violin"===_.type,k=[],A="closest"!==s||M?w.bdPos:2.5*w.bdPos,T=function(t){return t.pos+w.bPos-d};M&&"both"!==_.side?("positive"===_.side&&(v=function(t){var e=T(t);return a.inbox(e,e+A)}),"negative"===_.side&&(v=function(t){var e=T(t);return a.inbox(e-A,e)})):v=function(t){var e=T(t);return a.inbox(e-A,e+A)},g=M?function(t){return a.inbox(t.span[0]-h,t.span[1]-h)}:function(t){return a.inbox(t.min-h,t.max-h)},"h"===_.orientation?(h=e,d=r,p=g,m=v,l="y",u=x,c="x",f=b):(h=r,d=e,p=v,m=g,l="x",u=b,c="y",f=x);var E=a.getDistanceFunction(s,p,m);if(a.getClosest(y,E,t),!1===t.index)return[];var S=y[t.index],L=_.line.color,C=(_.marker||{}).color;o.opacity(L)&&_.line.width?t.color=L:o.opacity(C)&&_.boxpoints?t.color=C:t.color=_.fillcolor,t[l+"0"]=u.c2p(S.pos+w.bPos-w.bdPos,!0),t[l+"1"]=u.c2p(S.pos+w.bPos+w.bdPos,!0),n.tickText(u,u.c2l(S.pos),"hover").text,t[l+"LabelVal"]=S.pos;var P={},z=["med","min","q1","q3","max"];(_.boxmean||(_.meanline||{}).visible)&&z.push("mean"),(_.boxpoints||_.points)&&z.push("lf","uf");for(var O=0;Ot.uf}),o=Math.max((t.max-t.min)/10,t.q3-t.q1),u=1e-9*o,f=o*c,m=[],v=0;if(r.jitter){if(0===o)for(v=1,m=new Array(a.length),e=0;et.lo&&(w.so=!0)}return a}).enter().append("path").classed("point",!0).call(a.translatePoints,u,f)}function h(t,e,r,a){var o,s,l=e.pos,c=e.val,u=a.bPos,f=a.bPosPxOffset||0;Array.isArray(a.bdPos)?(o=a.bdPos[0],s=a.bdPos[1]):(o=a.bdPos,s=a.bdPos),t.selectAll("path.mean").data(i.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var e=l.c2p(t.pos+u,!0)+f,i=l.c2p(t.pos+u-o,!0)+f,a=l.c2p(t.pos+u+s,!0)+f,h=c.c2p(t.mean,!0),d=c.c2p(t.mean-t.sd,!0),p=c.c2p(t.mean+t.sd,!0);"h"===r.orientation?n.select(this).attr("d","M"+h+","+i+"V"+a+("sd"===r.boxmean?"m0,0L"+d+","+e+"L"+h+","+i+"L"+p+","+e+"Z":"")):n.select(this).attr("d","M"+i+","+h+"H"+a+("sd"===r.boxmean?"m0,0L"+e+","+d+"L"+i+","+h+"L"+e+","+p+"Z":""))})}e.exports={plot:function(t,e,r){var i=t._fullLayout,a=e.xaxis,o=e.yaxis;e.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes").each(function(t){var e,r,s=t[0],l=s.t,c=s.trace,d=s.node3=n.select(this),p=i._numBoxes,m="group"===i.boxmode&&p>1,v=l.dPos*(1-i.boxgap)*(1-i.boxgroupgap)/(m?p:1),g=m?2*l.dPos*((l.num+.5)/p-.5)*(1-i.boxgap):0,y=v*c.whiskerwidth;!0!==c.visible||l.empty?n.select(this).remove():("h"===c.orientation?(e=o,r=a):(e=a,r=o),l.bPos=g,l.bdPos=v,l.wdPos=y,u(d,{pos:e,val:r},c,l),c.boxpoints&&f(d,{x:a,y:o},c,l),c.boxmean&&h(d,{pos:e,val:r},c,l))})},plotBoxAndWhiskers:u,plotPoints:f,plotBoxMean:h}},{"../../components/drawing":623,"../../lib":724,d3:128}],885:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n,i=t.cd,a=t.xaxis,o=t.yaxis,s=[];if(!1===e)for(r=0;r=10)return null;var n=1/0;var i=-1/0;var a=e.length;for(var o=0;o0?Math.floor:Math.ceil,P=S>0?Math.ceil:Math.floor,z=S>0?Math.min:Math.max,O=S>0?Math.max:Math.min,D=C(T+L),I=P(E-L),R=[[u=A(T)]];for(i=D;i*S=0;i--)a[u-i]=t[f][i],o[u-i]=e[f][i];for(s.push({x:a,y:o,bicubic:l}),i=f,a=[],o=[];i>=0;i--)a[f-i]=t[i][0],o[f-i]=e[i][0];return s.push({x:a,y:o,bicubic:c}),s}},{}],900:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib/extend").extendFlat;e.exports=function(t,e,r,a){var o,s,l,c,u,f,h,d,p,m,v,g,y,b,x=t[r],_=t[r+"axis"],w=_._gridlines=[],M=_._minorgridlines=[],k=_._boundarylines=[],A=t[a],T=t[a+"axis"];"array"===_.tickmode&&(_.tickvals=x.slice());var E=t.xctrl,S=t.yctrl,L=E[0].length,C=E.length,P=t.a.length,z=t.b.length;n.calcTicks(_),"array"===_.tickmode&&delete _.tickvals;var O=_.smoothing?3:1;function D(e){var n,i,o,s,l,c,u,f,h,p,m,v,g=[],y=[],b={};if("b"===r)for(i=t.b2j(e),o=Math.floor(Math.max(0,Math.min(z-2,i))),s=i-o,b.length=z,b.crossLength=P,b.xy=function(e){return t.evalxy([],e,i)},b.dxy=function(e,r){return t.dxydi([],e,o,r,s)},n=0;n0&&(h=t.dxydi([],n-1,o,0,s),g.push(l[0]+h[0]/3),y.push(l[1]+h[1]/3),p=t.dxydi([],n-1,o,1,s),g.push(f[0]-p[0]/3),y.push(f[1]-p[1]/3)),g.push(f[0]),y.push(f[1]),l=f;else for(n=t.a2i(e),c=Math.floor(Math.max(0,Math.min(P-2,n))),u=n-c,b.length=P,b.crossLength=z,b.xy=function(e){return t.evalxy([],n,e)},b.dxy=function(e,r){return t.dxydj([],c,e,u,r)},i=0;i0&&(m=t.dxydj([],c,i-1,u,0),g.push(l[0]+m[0]/3),y.push(l[1]+m[1]/3),v=t.dxydj([],c,i-1,u,1),g.push(f[0]-v[0]/3),y.push(f[1]-v[1]/3)),g.push(f[0]),y.push(f[1]),l=f;return b.axisLetter=r,b.axis=_,b.crossAxis=T,b.value=e,b.constvar=a,b.index=d,b.x=g,b.y=y,b.smoothing=T.smoothing,b}function I(e){var n,i,o,s,l,c=[],u=[],f={};if(f.length=x.length,f.crossLength=A.length,"b"===r)for(o=Math.max(0,Math.min(z-2,e)),l=Math.min(1,Math.max(0,e-o)),f.xy=function(r){return t.evalxy([],r,e)},f.dxy=function(e,r){return t.dxydi([],e,o,r,l)},n=0;nx.length-1||w.push(i(I(s),{color:_.gridcolor,width:_.gridwidth}));for(d=f;dx.length-1||v<0||v>x.length-1))for(g=x[l],y=x[v],o=0;o<_.minorgridcount;o++)(b=v-l)<=0||(m=g+(y-g)*(o+1)/(_.minorgridcount+1)*(_.arraydtick/b))x[x.length-1]||M.push(i(D(m),{color:_.minorgridcolor,width:_.minorgridwidth}));_.startline&&k.push(i(I(0),{color:_.startlinecolor,width:_.startlinewidth})),_.endline&&k.push(i(I(x.length-1),{color:_.endlinecolor,width:_.endlinewidth}))}else{for(c=5e-15,f=(u=[Math.floor((x[x.length-1]-_.tick0)/_.dtick*(1+c)),Math.ceil((x[0]-_.tick0)/_.dtick/(1+c))].sort(function(t,e){return t-e}))[0],h=u[1],d=f;d<=h;d++)p=_.tick0+_.dtick*d,w.push(i(D(p),{color:_.gridcolor,width:_.gridwidth}));for(d=f-1;dx[x.length-1]||M.push(i(D(m),{color:_.minorgridcolor,width:_.minorgridwidth}));_.startline&&k.push(i(D(x[0]),{color:_.startlinecolor,width:_.startlinewidth})),_.endline&&k.push(i(D(x[x.length-1]),{color:_.endlinecolor,width:_.endlinewidth}))}}},{"../../lib/extend":713,"../../plots/cartesian/axes":770}],901:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../lib/extend").extendFlat;e.exports=function(t,e){var r,a,o,s=e._labels=[],l=e._gridlines;for(r=0;re.length&&(t=t.slice(0,e.length)):t=[],n=0;ne.length&&(t=t.slice(0,e.length)):t=[],n=0;ne.length&&(t[n]=t[n].slice(0,e.length)):t[n]=[],i=0;i90&&(d-=180,l=-l),{angle:d,flip:l,p:t.c2p(n,e,r),offsetMultplier:c}}},{}],917:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("./map_1d_array"),o=t("./makepath"),s=t("./orient_text"),l=t("../../lib/svg_text_utils"),c=t("../../lib"),u=t("../../constants/alignment");function f(t,e,r){var n=t.selectAll(e+"."+r).data([0]);return n.enter().append(e).classed(r,!0),n}function h(t,e,r){var n=r[0],i=r[0].trace,l=e.xaxis,u=e.yaxis,h=i.aaxis,m=i.baxis,v=t._fullLayout,y=e.plot.selectAll(".carpetlayer"),b=v._clips,x=f(y,"g","carpet"+i.uid).classed("trace",!0),_=f(x,"g","minorlayer"),w=f(x,"g","majorlayer"),M=f(x,"g","boundarylayer"),k=f(x,"g","labellayer");x.style("opacity",i.opacity),d(l,u,w,h,"a",h._gridlines),d(l,u,w,m,"b",m._gridlines),d(l,u,_,h,"a",h._minorgridlines),d(l,u,_,m,"b",m._minorgridlines),d(l,u,M,h,"a-boundary",h._boundarylines),d(l,u,M,m,"b-boundary",m._boundarylines),function(t,e,r,n,i,a,o,l){var u,f,h,d;u=.5*(r.a[0]+r.a[r.a.length-1]),f=r.b[0],h=r.ab2xy(u,f,!0),d=r.dxyda_rough(u,f),void 0===o.angle&&c.extendFlat(o,s(r,i,a,h,r.dxydb_rough(u,f)));g(t,e,r,n,h,d,r.aaxis,i,a,o,"a-title"),u=r.a[0],f=.5*(r.b[0]+r.b[r.b.length-1]),h=r.ab2xy(u,f,!0),d=r.dxydb_rough(u,f),void 0===l.angle&&c.extendFlat(l,s(r,i,a,h,r.dxyda_rough(u,f)));g(t,e,r,n,h,d,r.baxis,i,a,l,"b-title")}(t,k,i,n,l,u,p(t,l,u,i,n,k,h._labels,"a-label"),p(t,l,u,i,n,k,m._labels,"b-label")),function(t,e,r,n,i){var s,l,c,u,h=r.select("#"+t._clipPathId);h.size()||(h=r.append("clipPath").classed("carpetclip",!0));var d=f(h,"path","carpetboundary"),p=e.clipsegments,m=[];for(u=0;u0?"start":"end","data-notex":1}).call(i.font,o.font).text(o.text).call(l.convertToTspans,t),v=i.bBox(this);m.attr("transform","translate("+u.p[0]+","+u.p[1]+") rotate("+u.angle+")translate("+o.axis.labelpadding*h+","+.3*v.height+")"),d=Math.max(d,v.width+o.axis.labelpadding)}),h.exit().remove(),p.maxExtent=d,p}e.exports=function(t,e,r){for(var n=0;n90&&p<270,y=n.select(this);y.text(u.title||"").call(l.convertToTspans,t),g&&(b=(-l.lineCount(y)+v)*m*a-b),y.attr("transform","translate("+e.p[0]+","+e.p[1]+") rotate("+e.angle+") translate(0,"+b+")").classed("user-select-none",!0).attr("text-anchor","middle").call(i.font,u.titlefont)}),y.exit().remove()}},{"../../components/drawing":623,"../../constants/alignment":696,"../../lib":724,"../../lib/svg_text_utils":747,"./makepath":913,"./map_1d_array":914,"./orient_text":916,d3:128}],918:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../lib/search").findBin,a=t("./compute_control_points"),o=t("./create_spline_evaluator"),s=t("./create_i_derivative_evaluator"),l=t("./create_j_derivative_evaluator");e.exports=function(t){var e=t.a,r=t.b,c=t.a.length,u=t.b.length,f=t.aaxis,h=t.baxis,d=e[0],p=e[c-1],m=r[0],v=r[u-1],g=e[e.length-1]-e[0],y=r[r.length-1]-r[0],b=g*n.RELATIVE_CULL_TOLERANCE,x=y*n.RELATIVE_CULL_TOLERANCE;d-=b,p+=b,m-=x,v+=x,t.isVisible=function(t,e){return t>d&&tm&&ep||ev},f.c2p=function(t){return t},h.c2p=function(t){return t},t.setScale=function(){var e=t._x,r=t._y,n=a(t.xctrl,t.yctrl,e,r,f.smoothing,h.smoothing);t.xctrl=n[0],t.yctrl=n[1],t.evalxy=o([t.xctrl,t.yctrl],c,u,f.smoothing,h.smoothing),t.dxydi=s([t.xctrl,t.yctrl],f.smoothing,h.smoothing),t.dxydj=l([t.xctrl,t.yctrl],f.smoothing,h.smoothing)},t.i2a=function(t){var r=Math.max(0,Math.floor(t[0]),c-2),n=t[0]-r;return(1-n)*e[r]+n*e[r+1]},t.j2b=function(t){var e=Math.max(0,Math.floor(t[1]),c-2),n=t[1]-e;return(1-n)*r[e]+n*r[e+1]},t.ij2ab=function(e){return[t.i2a(e[0]),t.j2b(e[1])]},t.a2i=function(t){var r=Math.max(0,Math.min(i(t,e),c-2)),n=e[r],a=e[r+1];return Math.max(0,Math.min(c-1,r+(t-n)/(a-n)))},t.b2j=function(t){var e=Math.max(0,Math.min(i(t,r),u-2)),n=r[e],a=r[e+1];return Math.max(0,Math.min(u-1,e+(t-n)/(a-n)))},t.ab2ij=function(e){return[t.a2i(e[0]),t.b2j(e[1])]},t.i2c=function(e,r){return t.evalxy([],e,r)},t.ab2xy=function(n,i,a){if(!a&&(ne[c-1]|ir[u-1]))return[!1,!1];var o=t.a2i(n),s=t.b2j(i),l=t.evalxy([],o,s);if(a){var f,h,d,p,m=0,v=0,g=[];ne[c-1]?(f=c-2,h=1,m=(n-e[c-1])/(e[c-1]-e[c-2])):h=o-(f=Math.max(0,Math.min(c-2,Math.floor(o)))),ir[u-1]?(d=u-2,p=1,v=(i-r[u-1])/(r[u-1]-r[u-2])):p=s-(d=Math.max(0,Math.min(u-2,Math.floor(s)))),m&&(t.dxydi(g,f,d,h,p),l[0]+=g[0]*m,l[1]+=g[1]*m),v&&(t.dxydj(g,f,d,h,p),l[0]+=g[0]*v,l[1]+=g[1]*v)}return l},t.c2p=function(t,e,r){return[e.c2p(t[0]),r.c2p(t[1])]},t.p2x=function(t,e,r){return[e.p2c(t[0]),r.p2c(t[1])]},t.dadi=function(t){var r=Math.max(0,Math.min(e.length-2,t));return e[r+1]-e[r]},t.dbdj=function(t){var e=Math.max(0,Math.min(r.length-2,t));return r[e+1]-r[e]},t.dxyda=function(e,r,n,i){var a=t.dxydi(null,e,r,n,i),o=t.dadi(e,n);return[a[0]/o,a[1]/o]},t.dxydb=function(e,r,n,i){var a=t.dxydj(null,e,r,n,i),o=t.dbdj(r,i);return[a[0]/o,a[1]/o]},t.dxyda_rough=function(e,r,n){var i=g*(n||.1),a=t.ab2xy(e+i,r,!0),o=t.ab2xy(e-i,r,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dxydb_rough=function(e,r,n){var i=y*(n||.1),a=t.ab2xy(e,r+i,!0),o=t.ab2xy(e,r-i,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dpdx=function(t){return t._m},t.dpdy=function(t){return t._m}}},{"../../lib/search":742,"./compute_control_points":904,"./constants":905,"./create_i_derivative_evaluator":906,"./create_j_derivative_evaluator":907,"./create_spline_evaluator":908}],919:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a,o,s=[],l=[],c=t[0].length,u=t.length;function f(e,r){var n,i=0,a=0;return e>0&&void 0!==(n=t[r][e-1])&&(a++,i+=n),e0&&void 0!==(n=t[r-1][e])&&(a++,i+=n),r0&&a0&&i1e-5);return n.log("Smoother converged to",k,"after",A,"iterations"),t}},{"../../lib":724}],920:[function(t,e,r){"use strict";var n=t("./has_columns"),i=t("../heatmap/convert_column_xyz");e.exports=function(t,e,r){var a=[],o=r("x");o&&!n(o)&&a.push("x"),e._cheater=!o;var s=r("y");if(s&&!n(s)&&a.push("y"),o||s)return a.length&&i(e,e.aaxis,e.baxis,"a","b",a),!0}},{"../heatmap/convert_column_xyz":963,"./has_columns":910}],921:[function(t,e,r){"use strict";var n=t("../scattergeo/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),o=t("../../plots/attributes"),s=t("../../lib/extend"),l=s.extendFlat,c=s.extendDeepAll,u=n.marker.line;e.exports=l({locations:{valType:"data_array",editType:"calc"},locationmode:n.locationmode,z:{valType:"data_array",editType:"calc"},text:l({},n.text,{}),marker:{line:{color:u.color,width:l({},u.width,{dflt:1}),editType:"calc"},opacity:{valType:"number",arrayOk:!0,min:0,max:1,dflt:1,editType:"style"},editType:"calc"},selected:{marker:{opacity:n.selected.marker.opacity,editType:"plot"},editType:"plot"},unselected:{marker:{opacity:n.unselected.marker.opacity,editType:"plot"},editType:"plot"},hoverinfo:l({},o.hoverinfo,{editType:"calc",flags:["location","z","text","name"]})},c({},i,{zmax:{editType:"calc"},zmin:{editType:"calc"}}),{colorbar:a})},{"../../components/colorbar/attributes":599,"../../components/colorscale/attributes":604,"../../lib/extend":713,"../../plots/attributes":768,"../scattergeo/attributes":1086}],922:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../constants/numerical").BADNUM,a=t("../../components/colorscale/calc"),o=t("../scatter/arrays_to_calcdata"),s=t("../scatter/calc_selection");e.exports=function(t,e){for(var r=e.locations.length,l=new Array(r),c=0;cl&&(e.z=u.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),s("marker.opacity"),i(t,e,o,s,{prefix:"",cLetter:"z"}),n.coerceSelectionMarkerOpacity(e,s)):e.visible=!1}else e.visible=!1}},{"../../components/colorscale/defaults":608,"../../lib":724,"./attributes":921}],924:[function(t,e,r){"use strict";e.exports=function(t,e){return t.location=e.location,t.z=e.z,t}},{}],925:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("./attributes"),a=t("../scatter/fill_hover_text");e.exports=function(t,e,r){var o,s,l,c,u=t.cd,f=u[0].trace,h=t.subplot;for(s=0;s")}(t,f,o,h.mockAxis),[t]}},{"../../plots/cartesian/axes":770,"../scatter/fill_hover_text":1056,"./attributes":921}],926:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":801,"../heatmap/colorbar":962,"./attributes":921,"./calc":922,"./defaults":923,"./event_data":924,"./hover":925,"./plot":927,"./select":928,"./style":929}],927:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../lib/polygon"),o=t("../../lib/topojson_utils").getTopojsonFeatures,s=t("../../lib/geo_location_utils").locationToFeature,l=t("./style");function c(t,e){for(var r=t[0].trace,n=t.length,i=o(r,e),a=0;a0&&t[e+1][0]<0)return e;return null}switch(e="RUS"===l||"FJI"===l?function(t){var e;if(null===u(t))e=t;else for(e=new Array(t.length),i=0;ie?r[n++]=[t[i][0]+360,t[i][1]]:i===e?(r[n++]=t[i],r[n++]=[t[i][0],-90]):r[n++]=t[i];var o=a.tester(r);o.pts.pop(),c.push(o)}:function(t){c.push(a.tester(t))},o.type){case"MultiPolygon":for(r=0;r":f.value>h&&(s.prefixBoundary=!0);break;case"<":f.valueh)&&(s.prefixBoundary=!0);break;case"][":a=Math.min.apply(null,f.value),o=Math.max.apply(null,f.value),ah&&(s.prefixBoundary=!0)}}},{}],933:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../components/colorbar/draw"),a=t("./make_color_map"),o=t("./end_plus");e.exports=function(t,e){var r=e[0].trace,s="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+s).remove(),r.showscale){var l=i(t,s);e[0].t.cb=l;var c=r.contours,u=r.line,f=c.size||1,h=c.coloring,d=a(r,{isColorbar:!0});"heatmap"===h&&l.filllevels({start:r.zmin,end:r.zmax,size:(r.zmax-r.zmin)/254}),l.fillcolor("fill"===h||"heatmap"===h?d:"").line({color:"lines"===h?d:u.color,width:!1!==c.showlines?u.width:0,dash:u.dash}).levels({start:c.start,end:o(c),size:f}).options(r.colorbar)()}else n.autoMargin(t,s)}},{"../../components/colorbar/draw":602,"../../plots/plots":833,"./end_plus":941,"./make_color_map":946}],934:[function(t,e,r){"use strict";e.exports={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}}},{}],935:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("./label_defaults"),a=t("../../components/color"),o=a.addOpacity,s=a.opacity,l=t("../../constants/filter_ops"),c=l.CONSTRAINT_REDUCTION,u=l.COMPARISON_OPS2;e.exports=function(t,e,r,a,l,f){var h,d,p,m=e.contours,v=r("contours.operation");(m._operation=c[v],function(t,e){var r;-1===u.indexOf(e.operation)?(t("contours.value",[0,1]),Array.isArray(e.value)?e.value.length>2?e.value=e.value.slice(2):0===e.length?e.value=[0,1]:e.length<2?(r=parseFloat(e.value[0]),e.value=[r,r+1]):e.value=[parseFloat(e.value[0]),parseFloat(e.value[1])]:n(e.value)&&(r=parseFloat(e.value),e.value=[r,r+1])):(t("contours.value",0),n(e.value)||(Array.isArray(e.value)?e.value=parseFloat(e.value[0]):e.value=0))}(r,m),"="===v?h=m.showlines=!0:(h=r("contours.showlines"),p=r("fillcolor",o((t.line||{}).color||l,.5))),h)&&(d=r("line.color",p&&s(p)?o(e.fillcolor,1):l),r("line.width",2),r("line.dash"));r("line.smoothing"),i(r,a,d,f)}},{"../../components/color":598,"../../constants/filter_ops":697,"./label_defaults":945,"fast-isnumeric":140}],936:[function(t,e,r){"use strict";var n=t("../../constants/filter_ops"),i=t("fast-isnumeric");function a(t,e){var r,a=Array.isArray(e);function o(t){return i(t)?+t:null}return-1!==n.COMPARISON_OPS2.indexOf(t)?r=o(a?e[0]:e):-1!==n.INTERVAL_OPS.indexOf(t)?r=a?[o(e[0]),o(e[1])]:[o(e),o(e)]:-1!==n.SET_OPS.indexOf(t)&&(r=a?e.map(o):[o(e)]),r}function o(t){return function(e){e=a(t,e);var r=Math.min(e[0],e[1]),n=Math.max(e[0],e[1]);return{start:r,end:n,size:n-r}}}function s(t){return function(e){return{start:e=a(t,e),end:1/0,size:1/0}}}e.exports={"[]":o("[]"),"][":o("]["),">":s(">"),"<":s("<"),"=":s("=")}},{"../../constants/filter_ops":697,"fast-isnumeric":140}],937:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i=n("contours.start"),a=n("contours.end"),o=!1===i||!1===a,s=r("contours.size");!(o?e.autocontour=!0:r("autocontour",!1))&&s||r("ncontours")}},{}],938:[function(t,e,r){"use strict";var n=t("../../lib");function i(t){return n.extendFlat({},t,{edgepaths:n.extendDeep([],t.edgepaths),paths:n.extendDeep([],t.paths)})}e.exports=function(t,e){var r,a,o,s=function(t){return t.reverse()},l=function(t){return t};switch(e){case"=":case"<":return t;case">":for(1!==t.length&&n.warn("Contour data invalid for the specified inequality operation."),a=t[0],r=0;r1e3){n.warn("Too many contours, clipping at 1000",t);break}return l}},{"../../lib":724,"./constraint_mapping":936,"./end_plus":941}],941:[function(t,e,r){"use strict";e.exports=function(t){return t.end+t.size/1e6}},{}],942:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./constants");function a(t,e,r,n){return Math.abs(t[0]-e[0])20&&e?208===t||1114===t?n=0===r[0]?1:-1:a=0===r[1]?1:-1:-1!==i.BOTTOMSTART.indexOf(t)?a=1:-1!==i.LEFTSTART.indexOf(t)?n=1:-1!==i.TOPSTART.indexOf(t)?a=-1:n=-1;return[n,a]}(h,r,e),p=[s(t,e,[-d[0],-d[1]])],m=d.join(","),v=t.z.length,g=t.z[0].length;for(c=0;c<1e4;c++){if(h>20?(h=i.CHOOSESADDLE[h][(d[0]||d[1])<0?0:1],t.crossings[f]=i.SADDLEREMAINDER[h]):delete t.crossings[f],!(d=i.NEWDELTA[h])){n.log("Found bad marching index:",h,e,t.level);break}p.push(s(t,e,d)),e[0]+=d[0],e[1]+=d[1],a(p[p.length-1],p[p.length-2],o,l)&&p.pop(),f=e.join(",");var y=d[0]&&(e[0]<0||e[0]>g-2)||d[1]&&(e[1]<0||e[1]>v-2);if(f===u&&d.join(",")===m||r&&y)break;h=t.crossings[f]}1e4===c&&n.log("Infinite loop in contour?");var b,x,_,w,M,k,A,T,E,S,L,C,P,z,O,D=a(p[0],p[p.length-1],o,l),I=0,R=.2*t.smoothing,N=[],F=0;for(c=1;c=F;c--)if((b=N[c])=F&&b+N[x]T&&E--,t.edgepaths[E]=L.concat(p,S));break}V||(t.edgepaths[T]=p.concat(S))}for(T=0;Tt?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);return 5===r||10===r?t>(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4?5===r?713:1114:5===r?104:208:15===r?0:r}e.exports=function(t){var e,r,a,o,s,l,c,u,f,h=t[0].z,d=h.length,p=h[0].length,m=2===d||2===p;for(r=0;rt.level}return r?"M"+e.join("L")+"Z":""}(t,e),h=0,d=t.edgepaths.map(function(t,e){return e}),p=!0;function m(t){return Math.abs(t[1]-e[2][1])<.01}function v(t){return Math.abs(t[0]-e[0][0])<.01}function g(t){return Math.abs(t[0]-e[2][0])<.01}for(;d.length;){for(c=a.smoothopen(t.edgepaths[h],t.smoothing),f+=p?c:c.replace(/^M/,"L"),d.splice(d.indexOf(h),1),r=t.edgepaths[h][t.edgepaths[h].length-1],s=-1,o=0;o<4;o++){if(!r){i.log("Missing end?",h,t);break}for(u=r,Math.abs(u[1]-e[0][1])<.01&&!g(r)?n=e[1]:v(r)?n=e[0]:m(r)?n=e[3]:g(r)&&(n=e[2]),l=0;l=0&&(n=y,s=l):Math.abs(r[1]-n[1])<.01?Math.abs(r[1]-y[1])<.01&&(y[0]-r[0])*(n[0]-y[0])>=0&&(n=y,s=l):i.log("endpt to newendpt is not vert. or horz.",r,n,y)}if(r=n,s>=0)break;f+="L"+n}if(s===t.edgepaths.length){i.log("unclosed perimeter path");break}h=s,(p=-1===d.indexOf(h))&&(h=d[0],f+="Z")}for(h=0;hn.center?n.right-s:s-n.left)/(u+Math.abs(Math.sin(c)*o)),d=(l>n.middle?n.bottom-l:l-n.top)/(Math.abs(f)+Math.cos(c)*o);if(h<1||d<1)return 1/0;var p=v.EDGECOST*(1/(h-1)+1/(d-1));p+=v.ANGLECOST*c*c;for(var m=s-u,g=l-f,y=s+u,b=l+f,x=0;x2*v.MAXCOST)break;d&&(s/=2),l=(o=c-s/2)+1.5*s}if(h<=v.MAXCOST)return u},r.addLabelData=function(t,e,r,n){var i=e.width/2,a=e.height/2,o=t.x,s=t.y,l=t.theta,c=Math.sin(l),u=Math.cos(l),f=i*u,h=a*c,d=i*c,p=-a*u,m=[[o-f-h,s-d-p],[o+f-h,s+d-p],[o+f+h,s+d+p],[o-f+h,s-d+p]];r.push({text:e.text,x:o,y:s,dy:e.dy,theta:l,level:e.level,width:e.width,height:e.height}),n.push(m)},r.drawLabels=function(t,e,r,i,a){var s=t.selectAll("text").data(e,function(t){return t.text+","+t.x+","+t.y+","+t.theta});if(s.exit().remove(),s.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var e=t.x+Math.sin(t.theta)*t.dy,i=t.y-Math.cos(t.theta)*t.dy;n.select(this).text(t.text).attr({x:e,y:i,transform:"rotate("+180*t.theta/Math.PI+" "+e+" "+i+")"}).call(o.convertToTspans,r)}),a){for(var l="",c=0;ce.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),i(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var o,s=e.start,l=e.end,c=t._input.contours;if(s>l&&(e.start=c.start=l,l=e.end=c.end=s,s=e.start),!(e.size>0))o=s===l?1:a(s,l,t.ncontours).dtick,c.size=e.size=o}}},{"../../lib":724,"../../plots/cartesian/axes":770}],950:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../heatmap/style"),o=t("./make_color_map");e.exports=function(t){var e=n.select(t).selectAll("g.contour");e.style("opacity",function(t){return t.trace.opacity}),e.each(function(t){var e=n.select(this),r=t.trace,a=r.contours,s=r.line,l=a.size||1,c=a.start,u="constraint"===a.type,f=!u&&"lines"===a.coloring,h=!u&&"fill"===a.coloring,d=f||h?o(r):null;e.selectAll("g.contourlevel").each(function(t){n.select(this).selectAll("path").call(i.lineGroupStyle,s.width,f?d(t.level):s.color,s.dash)});var p=a.labelfont;if(e.selectAll("g.contourlabels text").each(function(t){i.font(n.select(this),{family:p.family,size:p.size,color:p.color||(f?d(t.level):s.color)})}),u)e.selectAll("g.contourfill path").style("fill",r.fillcolor);else if(h){var m;e.selectAll("g.contourfill path").style("fill",function(t){return void 0===m&&(m=t.level),d(t.level+.5*l)}),void 0===m&&(m=c),e.selectAll("g.contourbg path").style("fill",d(m-.5*l))}}),a(t)}},{"../../components/drawing":623,"../heatmap/style":973,"./make_color_map":946,d3:128}],951:[function(t,e,r){"use strict";var n=t("../../components/colorscale/defaults"),i=t("./label_defaults");e.exports=function(t,e,r,a,o){var s,l=r("contours.coloring"),c="";"fill"===l&&(s=r("contours.showlines")),!1!==s&&("lines"!==l&&(c=r("line.color","#000")),r("line.width",.5),r("line.dash")),"none"!==l&&n(t,e,a,r,{prefix:"",cLetter:"z"}),r("line.smoothing"),i(r,a,c,o)}},{"../../components/colorscale/defaults":608,"./label_defaults":945}],952:[function(t,e,r){"use strict";var n=t("../heatmap/attributes"),i=t("../contour/attributes"),a=i.contours,o=t("../scatter/attributes"),s=t("../../components/colorscale/attributes"),l=t("../../components/colorbar/attributes"),c=t("../../lib/extend").extendFlat,u=o.line;e.exports=c({},{carpet:{valType:"string",editType:"calc"},z:n.z,a:n.x,a0:n.x0,da:n.dx,b:n.y,b0:n.y0,db:n.dy,text:n.text,transpose:n.transpose,atype:n.xtype,btype:n.ytype,fillcolor:i.fillcolor,autocontour:i.autocontour,ncontours:i.ncontours,contours:{type:a.type,start:a.start,end:a.end,size:a.size,coloring:{valType:"enumerated",values:["fill","lines","none"],dflt:"fill",editType:"calc"},showlines:a.showlines,showlabels:a.showlabels,labelfont:a.labelfont,labelformat:a.labelformat,operation:a.operation,value:a.value,editType:"calc",impliedEdits:{autocontour:!1}},line:{color:c({},u.color,{}),width:u.width,dash:u.dash,smoothing:c({},u.smoothing,{}),editType:"plot"}},s,{autocolorscale:c({},s.autocolorscale,{dflt:!1})},{colorbar:l})},{"../../components/colorbar/attributes":599,"../../components/colorscale/attributes":604,"../../lib/extend":713,"../contour/attributes":930,"../heatmap/attributes":959,"../scatter/attributes":1048}],953:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc"),i=t("../heatmap/has_columns"),a=t("../heatmap/convert_column_xyz"),o=t("../heatmap/clean_2d_array"),s=t("../heatmap/max_row_length"),l=t("../heatmap/interp2d"),c=t("../heatmap/find_empties"),u=t("../heatmap/make_bound_array"),f=t("./defaults"),h=t("../carpet/lookup_carpetid"),d=t("../contour/set_contours");e.exports=function(t,e){var r=e.carpetTrace=h(t,e);if(r&&r.visible&&"legendonly"!==r.visible){if(!e.a||!e.b){var p=t.data[r.index],m=t.data[e.index];m.a||(m.a=p.a),m.b||(m.b=p.b),f(m,e,e._defaultColor,t._fullLayout)}var v=function(t,e){var r,f,h,d,p,m,v,g=e.carpetTrace,y=g.aaxis,b=g.baxis;y._minDtick=0,b._minDtick=0,i(e)&&a(e,y,b,"a","b",["z"]);r=e.a?y.makeCalcdata(e,"a"):[],d=e.b?b.makeCalcdata(e,"b"):[],f=e.a0||0,h=e.da||1,p=e.b0||0,m=e.db||1,v=o(e.z,e.transpose),e._emptypoints=c(v),e._interpz=l(v,e._emptypoints,e._interpz);var x=s(v),_="scaled"===e.xtype?"":r,w=u(e,_,f,h,x,y),M="scaled"===e.ytype?"":d,k=u(e,M,p,m,v.length,b),A={a:w,b:k,z:v};"levels"===e.contours.type&&n(e,v,"","z");return[A]}(0,e);return d(e),v}}},{"../../components/colorscale/calc":605,"../carpet/lookup_carpetid":912,"../contour/set_contours":949,"../heatmap/clean_2d_array":961,"../heatmap/convert_column_xyz":963,"../heatmap/find_empties":965,"../heatmap/has_columns":966,"../heatmap/interp2d":969,"../heatmap/make_bound_array":970,"../heatmap/max_row_length":971,"./defaults":954}],954:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../heatmap/xyz_defaults"),a=t("./attributes"),o=t("../contour/constraint_defaults"),s=t("../contour/contours_defaults"),l=t("../contour/style_defaults");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,a,r,i)}if(u("carpet"),t.a&&t.b){if(!i(t,e,u,c,"a","b"))return void(e.visible=!1);u("text");var f="constraint"===u("contours.type");f||delete e.showlegend,f?o(t,e,u,c,r,{hasHover:!1}):(s(t,e,u,function(r){return n.coerce2(t,e,a,r)}),l(t,e,u,c,{hasHover:!1}))}else e._defaultColor=r}},{"../../lib":724,"../contour/constraint_defaults":935,"../contour/contours_defaults":937,"../contour/style_defaults":951,"../heatmap/xyz_defaults":975,"./attributes":952}],955:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../contour/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../contour/style"),n.moduleType="trace",n.name="contourcarpet",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","carpet","contour","symbols","showLegend","hasLines","carpetDependent"],n.meta={},e.exports=n},{"../../plots/cartesian":781,"../contour/colorbar":933,"../contour/style":950,"./attributes":952,"./calc":953,"./defaults":954,"./plot":958}],956:[function(t,e,r){"use strict";var n=t("../../components/drawing"),i=t("../carpet/axis_aligned_line"),a=t("../../lib");e.exports=function(t,e,r,o,s,l,c,u){var f,h,d,p,m,v,g,y="",b=e.edgepaths.map(function(t,e){return e}),x=!0,_=1e-4*Math.abs(r[0][0]-r[2][0]),w=1e-4*Math.abs(r[0][1]-r[2][1]);function M(t){return Math.abs(t[1]-r[0][1])=0&&(d=L,m=v):Math.abs(h[1]-d[1])=0&&(d=L,m=v):a.log("endpt to newendpt is not vert. or horz.",h,d,L)}if(m>=0)break;y+=E(h,d),h=d}if(m===e.edgepaths.length){a.log("unclosed perimeter path");break}f=m,(x=-1===b.indexOf(f))&&(f=b[0],y+=E(h,d)+"Z",h=null)}for(f=0;f=0;q--)B=M.clipsegments[q],U=i([],B.x,S.c2p),V=i([],B.y,L.c2p),U.reverse(),V.reverse(),G.push(a(U,V,B.bicubic));var Y="M"+G.join("L")+"Z";!function(t,e,r,n,o,s){var l,c,u,f,h=t.selectAll("g.contourbg").data([0]);h.enter().append("g").classed("contourbg",!0);var d=h.selectAll("path").data("fill"!==s||o?[]:[0]);d.enter().append("path"),d.exit().remove();var p=[];for(f=0;fv&&(n.max=v);n.len=n.max-n.min}(this,r,t,n,c,e.height),!(n.len<(e.width+e.height)*f.LABELMIN)))for(var i=Math.min(Math.ceil(n.len/z),f.LABELMAX),a=0;aP){L("x scale is not linear");break}}if(g.length&&"fast"===S){var z=(g[g.length-1]-g[0])/(g.length-1),O=Math.abs(z/100);for(_=0;_O){L("y scale is not linear");break}}}var D=u(x),I="scaled"===e.xtype?"":r,R=p(e,I,m,v,D,M),N="scaled"===e.ytype?"":g,F=p(e,N,y,b,x.length,k);E||(a.expand(M,R),a.expand(k,F));var j={x:R,y:F,z:x,text:e.text};if(I&&I.length===R.length-1&&(j.xCenter=I),N&&N.length===F.length-1&&(j.yCenter=N),T&&(j.xRanges=w.xRanges,j.yRanges=w.yRanges,j.pts=w.pts),A&&"constraint"===e.contours.type||s(e,x,"","z"),A&&e.contours&&"heatmap"===e.contours.coloring){var B={type:"contour"===e.type?"heatmap":"histogram2d",xcalendar:e.xcalendar,ycalendar:e.ycalendar};j.xfill=p(B,I,m,v,D,M),j.yfill=p(B,N,y,b,x.length,k)}return[j]}},{"../../components/colorscale/calc":605,"../../lib":724,"../../plots/cartesian/axes":770,"../../registry":854,"../histogram2d/calc":992,"./clean_2d_array":961,"./convert_column_xyz":963,"./find_empties":965,"./has_columns":966,"./interp2d":969,"./make_bound_array":970,"./max_row_length":971}],961:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){var r,i,a,o,s,l;function c(t){if(n(t))return+t}if(e){for(r=0,s=0;s=0;o--)(s=((f[[(r=(a=h[o])[0])-1,i=a[1]]]||m)[2]+(f[[r+1,i]]||m)[2]+(f[[r,i-1]]||m)[2]+(f[[r,i+1]]||m)[2])/20)&&(l[a]=[r,i,s],h.splice(o,1),c=!0);if(!c)throw"findEmpties iterated with no new neighbors";for(a in l)f[a]=l[a],u.push(l[a])}return u.sort(function(t,e){return e[2]-t[2]})}},{"./max_row_length":971}],966:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],967:[function(t,e,r){"use strict";var n=t("../../components/fx"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=n.constants.MAXDIST;e.exports=function(t,e,r,s,l,c){if(!(t.distance=x[0].length||d<0||d>x.length)return}else{if(n.inbox(e-y[0],e-y[y.length-1])>o||n.inbox(r-b[0],r-b[b.length-1])>o)return;if(c){var S;for(T=[2*y[0]-y[1]],S=1;Sm&&(g=Math.max(g,Math.abs(t[a][o]-p)/(v-m))))}return g}e.exports=function(t,e,r){var i,s,l=1;if(Array.isArray(r))for(i=0;i.01;i++)l=o(t,e,a(l));return l>.01&&n.log("interp2d didn't converge quickly",l),t}},{"../../lib":724}],970:[function(t,e,r){"use strict";var n=t("../../registry");e.exports=function(t,e,r,i,a,o){var s,l,c,u=[],f=n.traceIs(t,"contour"),h=n.traceIs(t,"histogram"),d=n.traceIs(t,"gl2d");if(Array.isArray(e)&&e.length>1&&!h&&"category"!==o.type){var p=e.length;if(!(p<=a))return f?e.slice(0,a):e.slice(0,a+1);if(f||d)u=e.slice(0,a);else if(1===a)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],c=1;c0;)x=m.c2p(T[k]),k--;for(x0;)M=v.c2p(E[k]),k--;if(M0&&(i=!0);for(var s=0;sa){var o=a-r[t];return r[t]=a,o}}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]c?t>o?t>1.1*i?i:t>1.1*a?a:o:t>s?s:t>l?l:c:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function d(t,e,r,n,a,s){if(n&&t>o){var l=p(e,a,s),c=p(r,a,s),u=t===i?0:1;return l[u]!==c[u]}return Math.floor(r/t)-Math.floor(e/t)>.1}function p(t,e,r){var n=e.c2d(t,i,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}e.exports=function(t,e,r,n,a){var s,l,c=-1.1*e,h=-.1*e,d=t-h,p=r[0],m=r[1],v=Math.min(f(p+h,p+d,n,a),f(m+h,m+d,n,a)),g=Math.min(f(p+c,p+h,n,a),f(m+c,m+h,n,a));if(v>g&&go){var y=s===i?1:6,b=s===i?"M12":"M1";return function(e,r){var o=n.c2d(e,i,a),s=o.indexOf("-",y);s>0&&(o=o.substr(0,s));var c=n.d2c(o,0,a);if(cu.size/1.9?u.size:u.size/Math.ceil(u.size/b);var A=u.start+(u.size-b)/2;x=A-b*Math.ceil((A-x)/b)}for(s=0;s=0&&w=0;n--)s(n);else if("increasing"===e){for(n=1;n=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(p,b.direction,b.currentbin);var Z=Math.min(f.length,p.length),J=[],K=0,Q=Z-1;for(r=0;r=K;r--)if(p[r]){Q=r;break}for(r=K;r<=Q;r++)if(n(f[r])&&n(p[r])){var $={p:f[r],s:p[r],b:0};b.enabled||($.pts=P[r],H?$.p0=$.p1=P[r].length?A[P[r][0]]:f[r]:($.p0=V(E[r]),$.p1=V(E[r+1],!0))),J.push($)}return 1===J.length&&(J[0].width1=a.tickIncrement(J[0].p,k.size,!1,y)-J[0].p),o(J,e),Array.isArray(e.selectedpoints)&&i.tagSelected(J,e,W),J}}},{"../../constants/numerical":702,"../../lib":724,"../../plots/cartesian/axes":770,"../bar/arrays_to_calcdata":863,"./average":980,"./bin_functions":982,"./bin_label_vals":983,"./clean_bins":985,"./norm_functions":990,"fast-isnumeric":140}],985:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib").cleanDate,a=t("../../constants/numerical"),o=a.ONEDAY,s=a.BADNUM;e.exports=function(t,e,r){var a=e.type,l=r+"bins",c=t[l];c||(c=t[l]={});var u="date"===a?function(t){return t||0===t?i(t,s,c.calendar):null}:function(t){return n(t)?Number(t):null};c.start=u(c.start),c.end=u(c.end);var f="date"===a?o:1,h=c.size;if(n(h))c.size=h>0?Number(h):f;else if("string"!=typeof h)c.size=f;else{var d=h.charAt(0),p=h.substr(1);((p=n(p)?Number(p):0)<=0||"date"!==a||"M"!==d||p!==Math.round(p))&&(c.size=f)}var m="autobin"+r;"boolean"!=typeof t[m]&&(t[m]=t._fullInput[m]=t._input[m]=!((c.start||0===c.start)&&(c.end||0===c.end))),t[m]||(delete t["nbins"+r],delete t._fullInput["nbins"+r])}},{"../../constants/numerical":702,"../../lib":724,"fast-isnumeric":140}],986:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/color"),o=t("./bin_defaults"),s=t("../bar/style_defaults"),l=t("../../components/errorbars/defaults"),c=t("./attributes");e.exports=function(t,e,r,u){function f(r,n){return i.coerce(t,e,c,r,n)}var h=f("x"),d=f("y");f("cumulative.enabled")&&(f("cumulative.direction"),f("cumulative.currentbin")),f("text");var p=f("orientation",d&&!h?"h":"v"),m=e["v"===p?"x":"y"];m&&m.length?(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],u),e["h"===p?"x":"y"]&&f("histfunc"),o(t,e,f,"h"===p?["y"]:["x"]),s(t,e,f,r,u),l(t,e,a.defaultLine,{axis:"y"}),l(t,e,a.defaultLine,{axis:"x",inherit:"y"}),i.coerceSelectionMarkerOpacity(e,f)):e.visible=!1}},{"../../components/color":598,"../../components/errorbars/defaults":628,"../../lib":724,"../../registry":854,"../bar/style_defaults":876,"./attributes":979,"./bin_defaults":981}],987:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){if(t.x="xVal"in e?e.xVal:e.x,t.y="yVal"in e?e.yVal:e.y,e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),!(r.cumulative||{}).enabled){var a,o=Array.isArray(i)?n[0].pts[i[0]][i[1]]:n[i].pts;if(t.pointNumbers=o,t.binNumber=t.pointNumber,delete t.pointNumber,delete t.pointIndex,r._indexToPoints){a=[];for(var s=0;sA&&v.splice(A,v.length-A),y.length>A&&y.splice(A,y.length-A),u(e,"x",v,m,_,M,b),u(e,"y",y,g,w,k,x);var T=[],E=[],S=[],L="string"==typeof e.xbins.size,C="string"==typeof e.ybins.size,P=[],z=[],O=L?P:e.xbins,D=C?z:e.ybins,I=0,R=[],N=[],F=e.histnorm,j=e.histfunc,B=-1!==F.indexOf("density"),U="max"===j||"min"===j?null:0,V=a.count,q=o[F],H=!1,G=[],Y=[],W="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";W&&"count"!==j&&(H="avg"===j,V=a[j]);var X=e.xbins,Z=_(X.start),J=_(X.end)+(Z-i.tickIncrement(Z,X.size,!1,b))/1e6;for(r=Z;r=0&&c=0&&p0)c=o(t.alphahull,u);else{var d=["x","y","z"].indexOf(t.delaunayaxis);c=a(u.map(function(t){return[t[(d+1)%3],t[(d+2)%3]]}))}var p={positions:u,cells:c,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:l(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",p.vertexIntensity=t.intensity,p.vertexIntensityBounds=[t.cmin,t.cmax],p.colormap=t.colorscale.map(function(t){var e=t[0],r=i(t[1]).toRgb();return{index:e,rgb:[r.r,r.g,r.b,1]}})):t.vertexcolor?(this.color=t.vertexcolor[0],p.vertexColors=f(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],p.cellColors=f(t.facecolor)):(this.color=t.color,p.meshColor=l(t.color)),this.mesh.update(p)},u.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=function(t,e){var r=t.glplot.gl,i=n({gl:r}),a=new c(t,i,e.uid);return i._trace=a,a.update(e),t.glplot.add(i),a}},{"../../lib/str2rgbarray":746,"alpha-shape":47,"convex-hull":109,"delaunay-triangulate":130,"gl-mesh3d":201,tinycolor2:526}],1004:[function(t,e,r){"use strict";var n=t("../../registry"),i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}function c(t){var e=t.map(function(t){var e=l(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var u=c(["x","y","z"]),f=c(["i","j","k"]);u?(f&&f.forEach(function(t){for(var e=0;er?e=!0:n1)){var f=i.simpleMap(u.x,e.d2c,0,r.xcalendar),h=i.distinctVals(f).minDiff;o=Math.min(o,h)}}for(o===1/0&&(o=1),s=0;s");E.push(o,o,o,o,o,o,null)},B=0;Bs&&(n.log("parcoords traces support up to "+s+" dimensions at the moment"),l.splice(s)),o=0;o0)&&(f("label"),f("tickvals"),f("ticktext"),f("tickformat"),f("range"),f("constraintrange"),u=Math.min(u,a.values.length)),a._index=o,c.push(a));if(isFinite(u))for(o=0;ou&&(a.values=a.values.slice(0,u));return c}(t,e);!function(t,e,r,i,s){s("line.color",r),a(t,"line")&&n.isArray(t.line.color)?(s("line.colorscale"),o(t,e,i,s,{prefix:"line.",cLetter:"c"})):s("line.color",r)}(t,e,r,l,c),c("domain.x"),c("domain.y"),Array.isArray(u)&&u.length||(e.visible=!1);var f={family:l.font.family,size:Math.round(l.font.size*(10/12)),color:l.font.color};n.coerceFont(c,"labelfont",f),n.coerceFont(c,"tickfont",f),n.coerceFont(c,"rangefont",f)}},{"../../components/colorscale/defaults":608,"../../components/colorscale/has_colorscale":612,"../../lib":724,"./attributes":1013,"./constants":1017}],1019:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.colorbar=t("./colorbar"),n.moduleType="trace",n.name="parcoords",n.basePlotModule=t("./base_plot"),n.categories=["gl","regl","noOpacity"],n.meta={},e.exports=n},{"./attributes":1013,"./base_plot":1014,"./calc":1015,"./colorbar":1016,"./defaults":1018,"./plot":1022}],1020:[function(t,e,r){"use strict";var n=t("glslify"),i=t("./constants"),a=n(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nuniform float scatter;\n\nvarying vec4 fragColor;\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nvoid main() {\n\n float x = 0.5 * sign(pf[3]) + 0.5;\n float prominence = abs(pf[3]);\n float depth = 1.0 - prominence;\n\n mat4 pA = mat4(p0, p1, p2, p3);\n mat4 pB = mat4(p4, p5, p6, p7);\n mat4 pC = mat4(p8, p9, pa, pb);\n mat4 pD = mat4(pc, pd, pe, abs(pf));\n\n float show = float(mshow(pA, loA, hiA) &&\n mshow(pB, loB, hiB) &&\n mshow(pC, loC, hiC) &&\n mshow(pD, loD, hiD));\n\n vec2 yy = show * vec2(val(pA, dim2A) + val(pB, dim2B) + val(pC, dim2C) + val(pD, dim2D),\n val(pA, dim1A) + val(pB, dim1B) + val(pC, dim1C) + val(pD, dim1D));\n\n vec2 dimensionToggle = vec2(x, 1.0 - x);\n\n vec2 scatterToggle = vec2(scatter, 1.0 - scatter);\n\n float y = dot(yy, dimensionToggle);\n mat2 xy = mat2(viewBoxSize * yy + dimensionToggle, viewBoxSize * vec2(x, y));\n\n vec2 viewBoxXY = viewBoxPosition + xy * scatterToggle;\n\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n gl_Position = vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n\n // visible coloring\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),o=n(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nuniform float scatter;\n\nvarying vec4 fragColor;\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nvoid main() {\n\n float x = 0.5 * sign(pf[3]) + 0.5;\n float prominence = abs(pf[3]);\n float depth = 1.0 - prominence;\n\n mat4 pA = mat4(p0, p1, p2, p3);\n mat4 pB = mat4(p4, p5, p6, p7);\n mat4 pC = mat4(p8, p9, pa, pb);\n mat4 pD = mat4(pc, pd, pe, abs(pf));\n\n float show = float(mshow(pA, loA, hiA) &&\n mshow(pB, loB, hiB) &&\n mshow(pC, loC, hiC) &&\n mshow(pD, loD, hiD));\n\n vec2 yy = show * vec2(val(pA, dim2A) + val(pB, dim2B) + val(pC, dim2C) + val(pD, dim2D),\n val(pA, dim1A) + val(pB, dim1B) + val(pC, dim1C) + val(pD, dim1D));\n\n vec2 dimensionToggle = vec2(x, 1.0 - x);\n\n vec2 scatterToggle = vec2(scatter, 1.0 - scatter);\n\n float y = dot(yy, dimensionToggle);\n mat2 xy = mat2(viewBoxSize * yy + dimensionToggle, viewBoxSize * vec2(x, y));\n\n vec2 viewBoxXY = viewBoxPosition + xy * scatterToggle;\n\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n gl_Position = vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n\n // pick coloring\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]),s=n(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]),l=1e-6,c=64,u=2,f=4,h=[119,119,119],d=new Uint8Array(4),p=new Uint8Array(4);function m(t,e,r,n,i){var a=t._gl;a.enable(a.SCISSOR_TEST),a.scissor(e,r,n,i),t.clear({color:[0,0,0,0],depth:1})}function v(t,e,r,n,i,a){var o=a.key;r.drawCompleted||(!function(t){t.read({x:0,y:0,width:1,height:1,data:d})}(t),r.drawCompleted=!0),function s(l){var c;c=Math.min(n,i-l*n),a.offset=u*l*n,a.count=u*c,0===l&&(window.cancelAnimationFrame(r.currentRafs[o]),delete r.currentRafs[o],m(t,a.scissorX,a.scissorY,a.scissorWidth,a.viewBoxSize[1])),r.clearOnly||(e(a),l*n+c>>8*e)%256/255}function y(t,e){var r={};return[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map(function(r){return function(t,e,r){var n,i,a,o=[];for(i=0;i=c-4?g(o,c-2-s):.5);return a}(C,L,S,z),N=y(C,R),F=e.regl,j=F.texture({shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest",data:function(t,e,r){for(var n=[],i=0;i<256;i++){var a=t(i/255);n.push((e?h:a).concat(r))}return n}(k,A,Math.round(255*(A?O:1)))}),B=F({profile:!1,blend:{enable:P,func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:1,dstAlpha:1},equation:{rgb:"add",alpha:"add"},color:[0,0,0,0]},depth:{enable:!P,mask:!0,func:"less",range:[0,1]},cull:{enable:!0,face:"back"},scissor:{enable:!0,box:{x:F.prop("scissorX"),y:F.prop("scissorY"),width:F.prop("scissorWidth"),height:F.prop("scissorHeight")}},viewport:{x:F.prop("viewportX"),y:F.prop("viewportY"),width:F.prop("viewportWidth"),height:F.prop("viewportHeight")},dither:!1,vert:T?o:a,frag:s,primitive:"lines",lineWidth:1,attributes:N,uniforms:{resolution:F.prop("resolution"),viewBoxPosition:F.prop("viewBoxPosition"),viewBoxSize:F.prop("viewBoxSize"),dim1A:F.prop("dim1A"),dim2A:F.prop("dim2A"),dim1B:F.prop("dim1B"),dim2B:F.prop("dim2B"),dim1C:F.prop("dim1C"),dim2C:F.prop("dim2C"),dim1D:F.prop("dim1D"),dim2D:F.prop("dim2D"),loA:F.prop("loA"),hiA:F.prop("hiA"),loB:F.prop("loB"),hiB:F.prop("hiB"),loC:F.prop("loC"),hiC:F.prop("hiC"),loD:F.prop("loD"),hiD:F.prop("hiD"),palette:j,colorClamp:F.prop("colorClamp"),scatter:F.prop("scatter")},offset:F.prop("offset"),count:F.prop("count")}),U=[0,1];var V=[];function q(t,e,r,a,o,s,l,c,u,h,d){var p,m,v,g,y=[t,e],w=i.verticalPadding/s,M=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})}),k=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(p=0;p<2;p++)for(g=y[p],m=0;m<4;m++)for(v=0;v<16;v++){var T=v+16*m;M[p][m][v]=v+16*m===g?1:0,k[p][m][v]=(!A&&b(v,16*m,I)?S[0===T?0:1+(T-1)%(S.length-1)].filter[p]:p)+(2*p-1)*w}return{key:l,resolution:[x,_],viewBoxPosition:[r+D,a],viewBoxSize:[o,s],i:t,ii:e,dim1A:M[0][0],dim1B:M[0][1],dim1C:M[0][2],dim1D:M[0][3],dim2A:M[1][0],dim2B:M[1][1],dim2C:M[1][2],dim2D:M[1][3],loA:k[0][0],loB:k[0][1],loC:k[0][2],loD:k[0][3],hiA:k[1][0],hiB:k[1][1],hiC:k[1][2],hiD:k[1][3],colorClamp:U,scatter:c||0,scissorX:(u===h?0:r+D)+(n.pad.l-D)+n.layoutWidth*f.x[0],scissorWidth:(u===d?x-r+D:o+.5)+(u===h?r+D:0),scissorY:a+n.pad.b+n.layoutHeight*f.y[0],scissorHeight:s,viewportX:n.pad.l-D+n.layoutWidth*f.x[0],viewportY:n.pad.b+n.layoutHeight*f.y[0],viewportWidth:x,viewportHeight:_}}return{setColorDomain:function(t){U[0]=t[0],U[1]=t[1]},render:function(t,e,n){var i,a,o,s=1/0,l=-1/0;for(i=0;il&&(l=t[i].dim2.canvasX,o=i),t[i].dim1.canvasXi)return a;i=o,a=n[r]}return n[n.length-1]}function p(t){return o.scale.linear().domain(h(t))}function m(t,e,r){var n=u(e),s=n.trace,l=n.lineColor,c=n.cscale,h=s.line,d=s.domain,m=s.dimensions,v=t.width,g=s.labelfont,y=s.tickfont,b=s.rangefont,x=a.extendDeep({},h,{color:l.map(p({values:l,range:[h.cmin,h.cmax]})),blockLineCount:i.blockLineCount,canvasOverdrag:i.overdrag*i.canvasPixelRatio}),_=Math.floor(v*(d.x[1]-d.x[0])),w=Math.floor(t.height*(d.y[1]-d.y[0])),M=t.margin||{l:80,r:80,t:100,b:80},k=_,A=w;return{key:r,colCount:m.filter(f).length,dimensions:m,tickDistance:i.tickDistance,unitToColor:function(t){var e=t.map(function(t){return t[0]}),r=t.map(function(t){return t[1]}).map(function(t){return o.rgb(t)}),n="rgb".split("").map(function(t){return o.scale.linear().clamp(!0).domain(e).range(r.map((n=t,function(t){return t[n]})));var n});return function(t){return n.map(function(e){return e(t)})}}(c),lines:x,labelFont:g,tickFont:y,rangeFont:b,layoutWidth:v,layoutHeight:t.height,domain:d,translateX:d.x[0]*v,translateY:t.height-d.y[1]*t.height,pad:M,canvasWidth:k*i.canvasPixelRatio+2*x.canvasOverdrag,canvasHeight:A*i.canvasPixelRatio,width:k,height:A,canvasPixelRatio:i.canvasPixelRatio}}function v(t){var e=t.width,r=t.height,n=t.dimensions,a=t.canvasPixelRatio,s=function(r){return e*r/Math.max(1,t.colCount-1)},l=i.verticalPadding/(r*a),c=1-2*l,u=function(t){return l+c*t},d={key:t.key,xScale:s,model:t},m={};return d.dimensions=n.filter(f).map(function(e,n){var l=p(e),c=m[e.label];return m[e.label]=(c||0)+1,{key:e.label+(c?"__"+c:""),label:e.label,tickFormat:e.tickformat,tickvals:e.tickvals,ticktext:e.ticktext,ordinal:!!e.tickvals,scatter:i.scatter||e.scatter,xIndex:n,crossfilterDimensionIndex:n,visibleIndex:e._index,height:r,values:e.values,paddedUnitValues:e.values.map(l).map(u),xScale:s,x:s(n),canvasX:s(n)*a,unitScale:function(t,e){return o.scale.linear().range([t-e,e])}(r,i.verticalPadding),domainScale:function(t,e,r){var n=h(r),i=r.ticktext;return r.tickvals?o.scale.ordinal().domain(r.tickvals.map(function(t,e){return function(r,n){if(e){var i=e[n];return null===i||void 0===i?t(r):i}return t(r)}}(o.format(r.tickformat),i))).range(r.tickvals.map(function(t){return(t-n[0])/(n[1]-n[0])}).map(function(r){return t-e+r*(e-(t-e))})):o.scale.linear().domain(n).range([t-e,e])}(r,i.verticalPadding,e),ordinalScale:function(t){var e=h(t);return t.tickvals&&o.scale.ordinal().domain(t.tickvals).range(t.tickvals.map(function(t){return(t-e[0])/(e[1]-e[0])}))}(e),domainToUnitScale:l,filter:e.constraintrange?e.constraintrange.map(l):[0,1],parent:d,model:t}}),d}function g(t){t.classed(i.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}e.exports=function(t,e,r,f,h,p){var y=!1,b=!0;var x=f.filter(function(t){return u(t).trace.visible}).map(m.bind(0,h)).map(v);r.each(function(t,e){return a.extendFlat(t,x[e])});var _=r.selectAll(".gl-canvas").each(function(t){t.viewModel=x[0],t.model=t.viewModel?t.viewModel.model:null}),w={renderers:[],dimensions:[]},M=null;_.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(t){if(b&&t.lineLayer&&p&&p.hover){var e=o.event,r=this.width,n=this.height,i=o.mouse(this),a=i[0],s=i[1];if(a<0||s<0||a>=r||s>=n)return;var l=t.lineLayer.readPixel(a,n-1-s),c=0!==l[3],u=c?l[2]+256*(l[1]+256*l[0]):null,f={x:a,y:s,clientX:e.clientX,clientY:e.clientY,dataIndex:t.model.key,curveNumber:u};u!==M&&(c?p.hover(f):p.unhover&&p.unhover(f),M=u)}}),_.style("opacity",function(t){return t.pick?.01:1}),e.style("background","rgba(255, 255, 255, 0)");var k=e.selectAll("."+i.cn.parcoords).data(x,l);k.exit().remove(),k.enter().append("g").classed(i.cn.parcoords,!0).attr("overflow","visible").style("box-sizing","content-box").style("position","absolute").style("left",0).style("overflow","visible").style("shape-rendering","crispEdges").style("pointer-events","none").call(function(t){var e=t.selectAll("defs").data(c,l);e.enter().append("defs");var r=e.selectAll("#"+i.id.filterBarPattern).data(c,l);r.enter().append("pattern").attr("id",i.id.filterBarPattern).attr("patternUnits","userSpaceOnUse"),r.attr("x",-i.bar.width).attr("width",i.bar.capturewidth).attr("height",function(t){return t.model.height});var n=r.selectAll("rect").data(c,l);n.enter().append("rect").attr("shape-rendering","crispEdges"),n.attr("height",function(t){return t.model.height}).attr("width",i.bar.width).attr("x",i.bar.width/2).attr("fill",i.bar.fillcolor).attr("fill-opacity",i.bar.fillopacity).attr("stroke",i.bar.strokecolor).attr("stroke-opacity",i.bar.strokeopacity).attr("stroke-width",i.bar.strokewidth)}),k.attr("width",function(t){return t.model.width+t.model.pad.l+t.model.pad.r}).attr("height",function(t){return t.model.height+t.model.pad.t+t.model.pad.b}).attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var A=k.selectAll("."+i.cn.parcoordsControlView).data(c,l);A.enter().append("g").classed(i.cn.parcoordsControlView,!0).style("box-sizing","content-box"),A.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var T=A.selectAll("."+i.cn.yAxis).data(function(t){return t.dimensions},l);function E(t){return t.dimensions.some(function(t){return 0!==t.filter[0]||1!==t.filter[1]})}function S(t,e){return(i.scatter?function(t,e){for(var r=e.panels||(e.panels=[]),n=t.each(function(t){return t})[e.key].map(function(t){return t.__data__}),i=n.length-1,a=i,o=0;oline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),C.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var P=L.selectAll("."+i.cn.axisHeading).data(c,l);P.enter().append("g").classed(i.cn.axisHeading,!0);var z=P.selectAll("."+i.cn.axisTitle).data(c,l);z.enter().append("text").classed(i.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),z.attr("transform","translate(0,"+-i.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){s.font(z,t.model.labelFont)});var O=L.selectAll("."+i.cn.axisExtent).data(c,l);O.enter().append("g").classed(i.cn.axisExtent,!0);var D=O.selectAll("."+i.cn.axisExtentTop).data(c,l);D.enter().append("g").classed(i.cn.axisExtentTop,!0),D.attr("transform","translate(0,"+-i.axisExtentOffset+")");var I=D.selectAll("."+i.cn.axisExtentTopText).data(c,l);function R(t){return t.ordinal?function(){return""}:o.format(t.tickFormat)}I.enter().append("text").classed(i.cn.axisExtentTopText,!0).call(g),I.text(function(t){return R(t)(t.domainScale.domain().slice(-1)[0])}).each(function(t){s.font(I,t.model.rangeFont)});var N=O.selectAll("."+i.cn.axisExtentBottom).data(c,l);N.enter().append("g").classed(i.cn.axisExtentBottom,!0),N.attr("transform",function(t){return"translate(0,"+(t.model.height+i.axisExtentOffset)+")"});var F=N.selectAll("."+i.cn.axisExtentBottomText).data(c,l);F.enter().append("text").classed(i.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(g),F.text(function(t){return R(t)(t.domainScale.domain()[0])}).each(function(t){s.font(F,t.model.rangeFont)});var j=L.selectAll("."+i.cn.axisBrush).data(c,l),B=j.enter().append("g").classed(i.cn.axisBrush,!0);j.each(function(t){t.brush||(t.brush=o.svg.brush().y(t.unitScale).on("brushstart",q).on("brush",H).on("brushend",G),0===t.filter[0]&&1===t.filter[1]||t.brush.extent(t.filter),o.select(this).call(t.brush))}),B.selectAll("rect").attr("x",-i.bar.capturewidth/2).attr("width",i.bar.capturewidth),B.selectAll("rect.extent").attr("fill","url(#"+i.id.filterBarPattern+")").style("cursor","ns-resize").filter(function(t){return 0===t.filter[0]&&1===t.filter[1]}).attr("y",-100),B.selectAll(".resize rect").attr("height",i.bar.handleheight).attr("opacity",0).style("visibility","visible"),B.selectAll(".resize.n rect").style("cursor","n-resize").attr("y",i.bar.handleoverlap-i.bar.handleheight),B.selectAll(".resize.s rect").style("cursor","s-resize").attr("y",i.bar.handleoverlap);var U=!1,V=!1;function q(){U=!0,y=!0}function H(t){b=!1;var e=t.parent,r=t.brush.extent(),n=e.dimensions,i=n[t.xIndex].filter,a=U&&r[0]===r[1];a&&(t.brush.clear(),o.select(this).select("rect.extent").attr("y",-100));var s=a?[0,1]:r.slice();if(s[0]!==i[0]||s[1]!==i[1]){n[t.xIndex].filter=s,e.focusLayer&&e.focusLayer.render(e.panels,!0);var l=E(e);!V&&l?(e.contextLayer&&e.contextLayer.render(e.panels,!0),V=!0):V&&!l&&(e.contextLayer&&e.contextLayer.render(e.panels,!0,!0),V=!1)}U=!1}function G(t){var e=t.parent,r=t.brush.extent(),n=r[0]===r[1],i=e.dimensions[t.xIndex].filter;if(!n&&t.ordinal&&(i[0]=d(t.ordinalScale,i[0]),i[1]=d(t.ordinalScale,i[1]),i[0]===i[1]&&(i[0]=Math.max(0,i[0]-.05),i[1]=Math.min(1,i[1]+.05)),o.select(this).transition().duration(150).call(t.brush.extent(i)),e.focusLayer.render(e.panels,!0)),e.pickLayer&&e.pickLayer.render(e.panels,!0),b=!0,y="ending",p&&p.filterChanged){var a=t.domainToUnitScale.invert,s=i.map(a);p.filterChanged(e.key,t.visibleIndex,s)}}return w}},{"../../components/drawing":623,"../../lib":724,"../../lib/gup":721,"./constants":1017,"./lines":1020,d3:128}],1022:[function(t,e,r){(function(r){"use strict";var n=t("./parcoords"),i=t("regl");e.exports=function(t,e){var a=t._fullLayout,o=a._toppaper,s=a._paperdiv,l=a._glcontainer;a._glcanvas.each(function(e){e.regl||(e.regl=i({canvas:this,attributes:{antialias:!e.pick,preserveDrawingBuffer:!0},pixelRatio:t._context.plotGlPixelRatio||r.devicePixelRatio}))});var c={},u={},f=a._size;e.forEach(function(e,r){c[r]=t.data[r].dimensions,u[r]=t.data[r].dimensions.slice()});n(s,o,l,e,{width:f.w,height:f.h,margin:{t:f.t,r:f.r,b:f.b,l:f.l}},{filterChanged:function(e,r,n){var i=u[e][r],a=i.constraintrange;a&&2===a.length||(a=i.constraintrange=[]),a[0]=n[0],a[1]=n[1],t.emit("plotly_restyle")},hover:function(e){t.emit("plotly_hover",e)},unhover:function(e){t.emit("plotly_unhover",e)},axesMoved:function(e,r){function n(t){return!("visible"in t)||t.visible}function i(t,e,r){var n=e.indexOf(r),i=t.indexOf(n);return-1===i&&(i+=e.length),i}var a=function(t){return function(e,n){return i(r,t,e)-i(r,t,n)}}(u[e].filter(n));c[e].sort(a),u[e].filter(function(t){return!n(t)}).sort(function(t){return u[e].indexOf(t)}).forEach(function(t){c[e].splice(c[e].indexOf(t),1),c[e].splice(u[e].indexOf(t),0,t)}),t.emit("plotly_restyle")}})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./parcoords":1021,regl:486}],1023:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),i=t("../../plots/font_attributes"),a=t("../../plots/attributes"),o=t("../../plots/domain_attributes"),s=t("../../lib/extend").extendFlat,l=i({editType:"calc",colorEditType:"style"});e.exports={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:n.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:s({},a.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:s({},l,{}),insidetextfont:s({},l,{}),outsidetextfont:s({},l,{}),domain:o({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"}}},{"../../components/color/attributes":597,"../../lib/extend":713,"../../plots/attributes":768,"../../plots/domain_attributes":796,"../../plots/font_attributes":797}],1024:[function(t,e,r){"use strict";var n=t("../../registry");r.name="pie",r.plot=function(t){var e=n.getModule("pie"),r=function(t,e){for(var r=[],n=0;n")}}return g}},{"../../components/color":598,"./helpers":1028,"fast-isnumeric":140,tinycolor2:526}],1026:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values"),c=o("labels");if(!Array.isArray(c)){if(!Array.isArray(l)||!l.length)return void(e.visible=!1);o("label0"),o("dlabel")}o("marker.line.width")&&o("marker.line.color"),o("marker.colors"),o("scalegroup");var u=o("text"),f=o("textinfo",Array.isArray(u)?"text+percent":"percent");if(o("hovertext"),f&&"none"!==f){var h=o("textposition"),d=Array.isArray(h)||"auto"===h,p=d||"inside"===h,m=d||"outside"===h;if(p||m){var v=s(o,"textfont",a.font);p&&s(o,"insidetextfont",v),m&&s(o,"outsidetextfont",v)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":724,"./attributes":1023}],1027:[function(t,e,r){"use strict";var n=t("../../components/fx/helpers").appendArrayMultiPointValues;e.exports=function(t,e){var r={curveNumber:e.index,pointNumbers:t.pts,data:e._input,fullData:e,label:t.label,color:t.color,value:t.v,v:t.v};return 1===t.pts.length&&(r.pointNumber=r.i=t.pts[0]),n(r,e,t.pts),r}},{"../../components/fx/helpers":637}],1028:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)},r.getFirstFilled=function(t,e){if(Array.isArray(t))for(var r=0;r0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}e.exports=function(t,e){var r=t._fullLayout;!function(t,e){var r,n,i,a,o,s,l,c,u,f=[];for(i=0;il&&(l=s.pull[a]);o.r=Math.min(r,n)/(2+2*l),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===f.indexOf(s.scalegroup)&&f.push(s.scalegroup)}for(a=0;ai.vTotal/2?1:0)}(e),h.each(function(){var h=n.select(this).selectAll("g.slice").data(e);h.enter().append("g").classed("slice",!0),h.exit().remove();var m=[[[],[]],[[],[]]],v=!1;h.each(function(e){if(e.hidden)n.select(this).selectAll("path,g").remove();else{e.pointNumber=e.i,e.curveNumber=p.index,m[e.pxmid[1]<0?0:1][e.pxmid[0]<0?0:1].push(e);var a=d.cx,h=d.cy,g=n.select(this),y=g.selectAll("path.surface").data([e]),b=!1,x=!1;if(y.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),g.select("path.textline").remove(),g.on("mouseover",function(){var o=t._fullLayout,s=t._fullData[p.index];if(!t._dragging&&!1!==o.hovermode){var f=s.hoverinfo;if(Array.isArray(f)&&(f=i.castHoverinfo({hoverinfo:[l.castOption(f,e.pts)],_module:p._module},o,0)),"all"===f&&(f="label+text+value+percent+name"),"none"!==f&&"skip"!==f&&f){var m=u(e,d),v=a+e.pxmid[0]*(1-m),g=h+e.pxmid[1]*(1-m),y=r.separators,_=[];if(-1!==f.indexOf("label")&&_.push(e.label),-1!==f.indexOf("text")){var w=l.castOption(s.hovertext||s.text,e.pts);w&&_.push(w)}-1!==f.indexOf("value")&&_.push(l.formatPieValue(e.v,y)),-1!==f.indexOf("percent")&&_.push(l.formatPiePercent(e.v/d.vTotal,y));var M=p.hoverlabel,k=M.font;i.loneHover({x0:v-m*d.r,x1:v+m*d.r,y:g,text:_.join("
"),name:-1!==f.indexOf("name")?s.name:void 0,idealAlign:e.pxmid[0]<0?"left":"right",color:l.castOption(M.bgcolor,e.pts)||e.color,borderColor:l.castOption(M.bordercolor,e.pts),fontFamily:l.castOption(k.family,e.pts),fontSize:l.castOption(k.size,e.pts),fontColor:l.castOption(k.color,e.pts)},{container:o._hoverlayer.node(),outerContainer:o._paper.node(),gd:t}),b=!0}t.emit("plotly_hover",{points:[c(e,s)],event:n.event}),x=!0}}).on("mouseout",function(r){var a=t._fullLayout,o=t._fullData[p.index];x&&(r.originalEvent=n.event,t.emit("plotly_unhover",{points:[c(e,o)],event:n.event}),x=!1),b&&(i.loneUnhover(a._hoverlayer.node()),b=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[p.index];t._dragging||!1===r.hovermode||(t._hoverdata=[c(e,a)],i.click(t,n.event))}),p.pull){var _=+l.castOption(p.pull,e.pts)||0;_>0&&(a+=_*e.pxmid[0],h+=_*e.pxmid[1])}e.cxFinal=a,e.cyFinal=h;var w=p.hole;if(e.v===d.vTotal){var M="M"+(a+e.px0[0])+","+(h+e.px0[1])+S(e.px0,e.pxmid,!0,1)+S(e.pxmid,e.px0,!0,1)+"Z";w?y.attr("d","M"+(a+w*e.px0[0])+","+(h+w*e.px0[1])+S(e.px0,e.pxmid,!1,w)+S(e.pxmid,e.px0,!1,w)+"Z"+M):y.attr("d",M)}else{var k=S(e.px0,e.px1,!0,1);if(w){var A=1-w;y.attr("d","M"+(a+w*e.px1[0])+","+(h+w*e.px1[1])+S(e.px1,e.px0,!1,w)+"l"+A*e.px0[0]+","+A*e.px0[1]+k+"Z")}else y.attr("d","M"+a+","+h+"l"+e.px0[0]+","+e.px0[1]+k+"Z")}var T=l.castOption(p.textposition,e.pts),E=g.selectAll("g.slicetext").data(e.text&&"none"!==T?[0]:[]);E.enter().append("g").classed("slicetext",!0),E.exit().remove(),E.each(function(){var r=n.select(this).selectAll("text").data([0]);r.enter().append("text").attr("data-notex",1),r.exit().remove(),r.text(e.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(o.font,"outside"===T?p.outsidetextfont:p.insidetextfont).call(s.convertToTspans,t);var i,l=o.bBox(r.node());"outside"===T?i=f(l,e):(i=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),i=t.width/t.height,a=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,s=u(e,r),l={scale:s*r.r*2/n,rCenter:1-s,rotate:0};if(l.scale>=1)return l;var c=i+1/(2*Math.tan(a)),f=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(i*i+o/2)+i)),h={scale:2*f/t.height,rCenter:Math.cos(f/r.r)-f*i/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},d=1/i,p=d+1/(2*Math.tan(a)),m=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),o/(Math.sqrt(d*d+o/2)+d)),v={scale:2*m/t.width,rCenter:Math.cos(m/r.r)-m/i/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},g=v.scale>h.scale?v:h;return l.scale<1&&g.scale>l.scale?g:l}(l,e,d),"auto"===T&&i.scale<1&&(r.call(o.font,p.outsidetextfont),p.outsidetextfont.family===p.insidetextfont.family&&p.outsidetextfont.size===p.insidetextfont.size||(l=o.bBox(r.node())),i=f(l,e)));var c=a+e.pxmid[0]*i.rCenter+(i.x||0),m=h+e.pxmid[1]*i.rCenter+(i.y||0);i.outside&&(e.yLabelMin=m-l.height/2,e.yLabelMid=m,e.yLabelMax=m+l.height/2,e.labelExtraX=0,e.labelExtraY=0,v=!0),r.attr("transform","translate("+c+","+m+")"+(i.scale<1?"scale("+i.scale+")":"")+(i.rotate?"rotate("+i.rotate+")":"")+"translate("+-(l.left+l.right)/2+","+-(l.top+l.bottom)/2+")")})}function S(t,r,n,i){return"a"+i*d.r+","+i*d.r+" 0 "+e.largeArc+(n?" 1 ":" 0 ")+i*(r[0]-t[0])+","+i*(r[1]-t[1])}}),v&&function(t,e){var r,n,i,a,o,s,c,u,f,h,d,p,m;function v(t,e){return t.pxmid[1]-e.pxmid[1]}function g(t,e){return e.pxmid[1]-t.pxmid[1]}function y(t,r){r||(r={});var i,u,f,d,p,m,v=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),g=n?t.yLabelMin:t.yLabelMax,y=n?t.yLabelMax:t.yLabelMin,b=t.cyFinal+o(t.px0[1],t.px1[1]),x=v-g;if(x*c>0&&(t.labelExtraY=x),Array.isArray(e.pull))for(u=0;u=(l.castOption(e.pull,f.pts)||0)||((t.pxmid[1]-f.pxmid[1])*c>0?(d=f.cyFinal+o(f.px0[1],f.px1[1]),(x=d-g-t.labelExtraY)*c>0&&(t.labelExtraY+=x)):(y+t.labelExtraY-b)*c>0&&(i=3*s*Math.abs(u-h.indexOf(t)),p=f.cxFinal+a(f.px0[0],f.px1[0]),(m=p+i-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*s>0&&(t.labelExtraX+=m)))}for(n=0;n<2;n++)for(i=n?v:g,o=n?Math.max:Math.min,c=n?1:-1,r=0;r<2;r++){for(a=r?Math.max:Math.min,s=r?1:-1,(u=t[n][r]).sort(i),f=t[1-n][r],h=f.concat(u),p=[],d=0;dMath.abs(c)?o+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(i+t.labelExtraX+s):o+="l"+t.labelExtraX+","+l+"v"+(c-l)+"h"+s}else o+="V"+(t.yLabelMid+t.labelExtraY)+"h"+s;e.append("path").classed("textline",!0).call(a.stroke,p.outsidetextfont.color).attr({"stroke-width":Math.min(2,p.outsidetextfont.size/8),d:o,fill:"none"})}})})}),setTimeout(function(){h.selectAll("tspan").each(function(){var t=n.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":598,"../../components/drawing":623,"../../components/fx":640,"../../lib/svg_text_utils":747,"./event_data":1027,"./helpers":1028,d3:128}],1033:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0].trace,r=n.select(this);r.style({opacity:e.opacity}),r.selectAll("path.surface").each(function(t){n.select(this).call(i,t,e)})})}},{"./style_one":1034,d3:128}],1034:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("./helpers").castOption;e.exports=function(t,e,r){var a=r.marker.line,o=i(a.color,e.pts)||n.defaultLine,s=i(a.width,e.pts)||0;t.style({"stroke-width":s}).call(n.fill,e.color).call(n.stroke,o)}},{"../../components/color":598,"./helpers":1028}],1035:[function(t,e,r){"use strict";var n=t("../scatter/attributes");e.exports={x:n.x,y:n.y,xy:{valType:"data_array",editType:"calc"},indices:{valType:"data_array",editType:"calc"},xbounds:{valType:"data_array",editType:"calc"},ybounds:{valType:"data_array",editType:"calc"},text:n.text,marker:{color:{valType:"color",arrayOk:!1,editType:"calc"},opacity:{valType:"number",min:0,max:1,dflt:1,arrayOk:!1,editType:"calc"},blend:{valType:"boolean",dflt:null,editType:"calc"},sizemin:{valType:"number",min:.1,max:2,dflt:.5,editType:"calc"},sizemax:{valType:"number",min:.1,dflt:20,editType:"calc"},border:{color:{valType:"color",arrayOk:!1,editType:"calc"},arearatio:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},editType:"calc"},editType:"calc"}}},{"../scatter/attributes":1048}],1036:[function(t,e,r){"use strict";var n=t("gl-pointcloud2d"),i=t("../../lib/str2rgbarray"),a=t("../scatter/get_trace_color"),o=["xaxis","yaxis"];function s(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=n(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var l=s.prototype;l.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},l.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=a(t,{})},l.updateFast=function(t){var e,r,n,a,o,s,l=this.xData=this.pickXData=t.x,c=this.yData=this.pickYData=t.y,u=this.pickXYData=t.xy,f=t.xbounds&&t.ybounds,h=t.indices,d=this.bounds;if(u){if(n=u,e=u.length>>>1,f)d[0]=t.xbounds[0],d[2]=t.xbounds[1],d[1]=t.ybounds[0],d[3]=t.ybounds[1];else for(s=0;sd[2]&&(d[2]=a),od[3]&&(d[3]=o);if(h)r=h;else for(r=new Int32Array(e),s=0;sd[2]&&(d[2]=a),od[3]&&(d[3]=o);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var p=i(t.marker.color),m=i(t.marker.border.color),v=t.opacity*t.marker.opacity;p[3]*=v,this.pointcloudOptions.color=p;var g=t.marker.blend;if(null===g){g=l.length<100||c.length<100}this.pointcloudOptions.blend=g,m[3]*=v,this.pointcloudOptions.borderColor=m;var y=t.marker.sizemin,b=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=y,this.pointcloudOptions.sizeMax=b,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions),this.expandAxesFast(d,b/2)},l.expandAxesFast=function(t,e){for(var r,n,i,a=e||.5,s=0;s<2;s++)(n=(r=this.scene[o[s]])._min)||(n=[]),n.push({val:t[s],pad:a}),(i=r._max)||(i=[]),i.push({val:t[s+2],pad:a})},l.dispose=function(){this.pointcloud.dispose()},e.exports=function(t,e){var r=new s(t,e.uid);return r.update(e),r}},{"../../lib/str2rgbarray":746,"../scatter/get_trace_color":1058,"gl-pointcloud2d":212}],1037:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r){function a(r,a){return n.coerce(t,e,i,r,a)}a("x"),a("y"),a("xbounds"),a("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),a("text"),a("marker.color",r),a("marker.opacity"),a("marker.blend"),a("marker.sizemin"),a("marker.sizemax"),a("marker.border.color",r),a("marker.border.arearatio")}},{"../../lib":724,"./attributes":1035}],1038:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../scatter3d/calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="pointcloud",n.basePlotModule=t("../../plots/gl2d"),n.categories=["gl","gl2d","showLegend"],n.meta={},e.exports=n},{"../../plots/gl2d":810,"../scatter3d/calc":1074,"./attributes":1035,"./convert":1036,"./defaults":1037}],1039:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../../plots/attributes"),a=t("../../components/color/attributes"),o=t("../../components/fx/attributes"),s=t("../../plots/domain_attributes"),l=t("../../lib/extend").extendFlat,c=t("../../plot_api/edit_types").overrideAll;e.exports=c({hoverinfo:l({},i.hoverinfo,{flags:["label","text","value","percent","name"]}),hoverlabel:o.hoverlabel,domain:s({name:"sankey",trace:!0}),orientation:{valType:"enumerated",values:["v","h"],dflt:"h"},valueformat:{valType:"string",dflt:".3s"},valuesuffix:{valType:"string",dflt:""},arrangement:{valType:"enumerated",values:["snap","perpendicular","freeform","fixed"],dflt:"snap"},textfont:n({}),node:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:a.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:.5,arrayOk:!0}},pad:{valType:"number",arrayOk:!1,min:0,dflt:20},thickness:{valType:"number",arrayOk:!1,min:1,dflt:20}},link:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:a.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:0,arrayOk:!0}},source:{valType:"data_array",dflt:[]},target:{valType:"data_array",dflt:[]},value:{valType:"data_array",dflt:[]}}},"calc","nested")},{"../../components/color/attributes":597,"../../components/fx/attributes":632,"../../lib/extend":713,"../../plot_api/edit_types":754,"../../plots/attributes":768,"../../plots/domain_attributes":796,"../../plots/font_attributes":797}],1040:[function(t,e,r){"use strict";var n=t("../../plot_api/edit_types").overrideAll,i=t("../../plots/get_data").getModuleCalcData,a=t("./plot"),o=t("../../components/fx/layout_attributes");r.name="sankey",r.baseLayoutAttrOverrides=n({hoverlabel:o.hoverlabel},"plot","nested"),r.plot=function(t){var e=i(t.calcdata,"sankey");a(t,e)},r.clean=function(t,e,r,n){var i=n._has&&n._has("sankey"),a=e._has&&e._has("sankey");i&&!a&&n._paperdiv.selectAll(".sankey").remove()}},{"../../components/fx/layout_attributes":641,"../../plot_api/edit_types":754,"../../plots/get_data":807,"./plot":1045}],1041:[function(t,e,r){"use strict";var n=t("strongly-connected-components"),i=t("../../lib"),a=t("../../lib/gup").wrap;e.exports=function(t,e){return function(t,e,r){for(var i=t.map(function(){return[]}),a=0;a1})}(e.node.label,e.link.source,e.link.target)&&(i.error("Circularity is present in the Sankey data. Removing all nodes and links."),e.link.label=[],e.link.source=[],e.link.target=[],e.link.value=[],e.link.color=[],e.node.label=[],e.node.color=[]),a({link:e.link,node:e.node})}},{"../../lib":724,"../../lib/gup":721,"strongly-connected-components":517}],1042:[function(t,e,r){"use strict";e.exports={nodeTextOffsetHorizontal:4,nodeTextOffsetVertical:3,nodePadAcross:10,sankeyIterations:50,forceIterations:5,forceTicksPerFrame:10,duration:500,ease:"cubic-in-out",cn:{sankey:"sankey",sankeyLinks:"sankey-links",sankeyLink:"sankey-link",sankeyNodeSet:"sankey-node-set",sankeyNode:"sankey-node",nodeRect:"node-rect",nodeCapture:"node-capture",nodeCentered:"node-entered",nodeLabelGuide:"node-label-guide",nodeLabel:"node-label",nodeLabelTextPath:"node-label-text-path"}}},{}],1043:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("../../components/color"),o=t("tinycolor2");e.exports=function(t,e,r,s){function l(r,a){return n.coerce(t,e,i,r,a)}l("node.label"),l("node.pad"),l("node.thickness"),l("node.line.color"),l("node.line.width");var c=s.colorway;l("node.color",e.node.label.map(function(t,e){return a.addOpacity(function(t){return c[t%c.length]}(e),.8)})),l("link.label"),l("link.source"),l("link.target"),l("link.value"),l("link.line.color"),l("link.line.width"),l("link.color",e.link.value.map(function(){return o(s.paper_bgcolor).getLuminance()<.333?"rgba(255, 255, 255, 0.6)":"rgba(0, 0, 0, 0.2)"})),l("domain.x"),l("domain.y"),l("orientation"),l("valueformat"),l("valuesuffix"),l("arrangement"),n.coerceFont(l,"textfont",n.extendFlat({},s.font));e.node.label.some(function(t,r){return-1===e.link.source.indexOf(r)&&-1===e.link.target.indexOf(r)})&&n.warn("Some of the nodes are neither sources nor targets, they will not be displayed.")}},{"../../components/color":598,"../../lib":724,"./attributes":1039,tinycolor2:526}],1044:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.moduleType="trace",n.name="sankey",n.basePlotModule=t("./base_plot"),n.categories=["noOpacity"],n.meta={},e.exports=n},{"./attributes":1039,"./base_plot":1040,"./calc":1041,"./defaults":1043,"./plot":1045}],1045:[function(t,e,r){"use strict";var n=t("d3"),i=t("./render"),a=t("../../components/fx"),o=t("../../components/color"),s=t("../../lib"),l=t("./constants").cn,c=s._;function u(t){return""!==t}function f(t,e){return t.filter(function(t){return t.key===e.traceId})}function h(t,e){n.select(t).select("path").style("fill-opacity",e),n.select(t).select("rect").style("fill-opacity",e)}function d(t){n.select(t).select("text.name").style("fill","black")}function p(t){return function(e){return-1!==t.node.sourceLinks.indexOf(e.link)||-1!==t.node.targetLinks.indexOf(e.link)}}function m(t){return function(e){return-1!==e.node.sourceLinks.indexOf(t.link)||-1!==e.node.targetLinks.indexOf(t.link)}}function v(t,e,r){e&&r&&f(r,e).selectAll("."+l.sankeyLink).filter(p(e)).call(y.bind(0,e,r,!1))}function g(t,e,r){e&&r&&f(r,e).selectAll("."+l.sankeyLink).filter(p(e)).call(b.bind(0,e,r,!1))}function y(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",.4),i&&f(e,t).selectAll("."+l.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",.4),r&&f(e,t).selectAll("."+l.sankeyNode).filter(m(t)).call(v)}function b(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",function(t){return t.tinyColorAlpha}),i&&f(e,t).selectAll("."+l.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",function(t){return t.tinyColorAlpha}),r&&f(e,t).selectAll(l.sankeyNode).filter(m(t)).call(g)}function x(t,e){var r=t.hoverlabel||{},n=s.nestedProperty(r,e).get();return!Array.isArray(n)&&n}e.exports=function(t,e){var r=t._fullLayout,s=r._paper,f=r._size,p=c(t,"source:")+" ",m=c(t,"target:")+" ",_=c(t,"incoming flow count:")+" ",w=c(t,"outgoing flow count:")+" ";i(s,e,{width:f.w,height:f.h,margin:{t:f.t,r:f.r,b:f.b,l:f.l}},{linkEvents:{hover:function(e,r,i){n.select(e).call(y.bind(0,r,i,!0)),t.emit("plotly_hover",{event:n.event,points:[r.link]})},follow:function(e,i){var s=i.link.trace,l=t._fullLayout._paperdiv.node().getBoundingClientRect(),c=e.getBoundingClientRect(),f=c.left+c.width/2,v=c.top+c.height/2,g=a.loneHover({x:f-l.left,y:v-l.top,name:n.format(i.valueFormat)(i.link.value)+i.valueSuffix,text:[i.link.label||"",p+i.link.source.label,m+i.link.target.label].filter(u).join("
"),color:x(s,"bgcolor")||o.addOpacity(i.tinyColorHue,1),borderColor:x(s,"bordercolor"),fontFamily:x(s,"font.family"),fontSize:x(s,"font.size"),fontColor:x(s,"font.color"),idealAlign:n.event.x"),color:x(o,"bgcolor")||i.tinyColorHue,borderColor:x(o,"bordercolor"),fontFamily:x(o,"font.family"),fontSize:x(o,"font.size"),fontColor:x(o,"font.color"),idealAlign:"left"},{container:r._hoverlayer.node(),outerContainer:r._paper.node(),gd:t});h(g,.85),d(g)},unhover:function(e,i,o){n.select(e).call(g,i,o),t.emit("plotly_unhover",{event:n.event,points:[i.node]}),a.loneUnhover(r._hoverlayer.node())},select:function(e,r,i){var o=r.node;o.originalEvent=n.event,t._hoverdata=[o],n.select(e).call(g,r,i),a.click(t,{target:!0})}}})}},{"../../components/color":598,"../../components/fx":640,"../../lib":724,"./constants":1042,"./render":1046,d3:128}],1046:[function(t,e,r){"use strict";var n=t("./constants"),i=t("d3"),a=t("tinycolor2"),o=t("../../components/color"),s=t("../../components/drawing"),l=t("@plotly/d3-sankey").sankey,c=t("d3-force"),u=t("../../lib"),f=t("../../lib/gup").keyFun,h=t("../../lib/gup").repeat,d=t("../../lib/gup").unwrap;function p(t){t.lastDraggedX=t.x,t.lastDraggedY=t.y}function m(t){return function(e){return e.node.originalX===t.node.originalX}}function v(t){for(var e=0;e1||t.linkLineWidth>0}function M(t){return"translate("+t.translateX+","+t.translateY+")"+(t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)")}function k(t){return"translate("+(t.horizontal?0:t.labelY)+" "+(t.horizontal?t.labelY:0)+")"}function A(t){return i.svg.line()([[t.horizontal?t.left?-t.sizeAcross:t.visibleWidth+n.nodeTextOffsetHorizontal:n.nodeTextOffsetHorizontal,0],[t.horizontal?t.left?-n.nodeTextOffsetHorizontal:t.sizeAcross:t.visibleHeight-n.nodeTextOffsetHorizontal,0]])}function T(t){return t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)"}function E(t){return t.horizontal?"scale(1 1)":"scale(-1 1)"}function S(t){return t.darkBackground&&!t.horizontal?"rgb(255,255,255)":"rgb(0,0,0)"}function L(t){return t.horizontal&&t.left?"100%":"0%"}function C(t,e,r){t.on(".basic",null).on("mouseover.basic",function(t){t.interactionState.dragInProgress||(r.hover(this,t,e),t.interactionState.hovered=[this,t])}).on("mousemove.basic",function(t){t.interactionState.dragInProgress||(r.follow(this,t),t.interactionState.hovered=[this,t])}).on("mouseout.basic",function(t){t.interactionState.dragInProgress||(r.unhover(this,t,e),t.interactionState.hovered=!1)}).on("click.basic",function(t){t.interactionState.hovered&&(r.unhover(this,t,e),t.interactionState.hovered=!1),t.interactionState.dragInProgress||r.select(this,t,e)})}function P(t,e,r){var a=i.behavior.drag().origin(function(t){return t.node}).on("dragstart",function(i){if("fixed"!==i.arrangement&&(u.raiseToTop(this),i.interactionState.dragInProgress=i.node,p(i.node),i.interactionState.hovered&&(r.nodeEvents.unhover.apply(0,i.interactionState.hovered),i.interactionState.hovered=!1),"snap"===i.arrangement)){var a=i.traceId+"|"+Math.floor(i.node.originalX);i.forceLayouts[a]?i.forceLayouts[a].alpha(1):function(t,e,r){var i=r.sankey.nodes().filter(function(t){return t.originalX===r.node.originalX});r.forceLayouts[e]=c.forceSimulation(i).alphaDecay(0).force("collide",c.forceCollide().radius(function(t){return t.dy/2+r.nodePad/2}).strength(1).iterations(n.forceIterations)).force("constrain",function(t,e,r,i){return function(){for(var t=0,a=0;a0&&i.forceLayouts[e].alpha(0)}}(0,e,i,r)).stop()}(0,a,i),function(t,e,r,i){window.requestAnimationFrame(function a(){for(var o=0;o0&&window.requestAnimationFrame(a)})}(t,e,i,a)}}).on("drag",function(r){if("fixed"!==r.arrangement){var n=i.event.x,a=i.event.y;"snap"===r.arrangement?(r.node.x=n,r.node.y=a):("freeform"===r.arrangement&&(r.node.x=n),r.node.y=Math.max(r.node.dy/2,Math.min(r.size-r.node.dy/2,a))),p(r.node),"snap"!==r.arrangement&&(r.sankey.relayout(),x(t.filter(m(r)),e))}}).on("dragend",function(t){t.interactionState.dragInProgress=!1});t.on(".drag",null).call(a)}e.exports=function(t,e,r,i){var c=t.selectAll("."+n.cn.sankey).data(e.filter(function(t){return d(t).trace.visible}).map(function(t,e,r){for(var i,a=d(e).trace,o=a.domain,s=a.node,c=a.link,f=a.arrangement,h="h"===a.orientation,p=a.node.pad,m=a.node.thickness,g=a.node.line.color,y=a.node.line.width,b=a.link.line.color,x=a.link.line.width,_=a.valueformat,w=a.valuesuffix,M=a.textfont,k=t.width*(o.x[1]-o.x[0]),A=t.height*(o.y[1]-o.y[0]),T=s.label.map(function(t,e){return{pointNumber:e,label:t,color:u.isArray(s.color)?s.color[e]:s.color}}),E=c.value.map(function(t,e){return{pointNumber:e,label:c.label[e],color:u.isArray(c.color)?c.color[e]:c.color,source:c.source[e],target:c.target[e],value:t}}),S=l().size(h?[k,A]:[A,k]).nodeWidth(m).nodePadding(p).nodes(T).links(E).layout(n.sankeyIterations),L=S.nodes(),C=0;C5?t.node.label:""}).attr("text-anchor",function(t){return t.horizontal&&t.left?"end":"start"}),N.transition().ease(n.ease).duration(n.duration).attr("startOffset",L).style("fill",S)}},{"../../components/color":598,"../../components/drawing":623,"../../lib":724,"../../lib/gup":721,"./constants":1042,"@plotly/d3-sankey":41,d3:128,"d3-force":124,tinycolor2:526}],1047:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){for(var r=0;r=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}}},{}],1052:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/plots"),o=t("../../components/colorscale"),s=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,l=r.marker,c="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+c).remove(),void 0!==l&&l.showscale){var u=l.color,f=l.cmin,h=l.cmax;n(f)||(f=i.aggNums(Math.min,null,u)),n(h)||(h=i.aggNums(Math.max,null,u));var d=e[0].t.cb=s(t,c),p=o.makeColorScaleFunc(o.extractScale(l.colorscale,f,h),{noNumericCheck:!0});d.fillcolor(p).filllevels({start:f,end:h,size:(h-f)/254}).options(l.colorbar)()}else a.autoMargin(t,c)}},{"../../components/colorbar/draw":602,"../../components/colorscale":613,"../../lib":724,"../../plots/plots":833,"fast-isnumeric":140}],1053:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){a.hasLines(t)&&n(t,"line")&&i(t,t.line.color,"line","c"),a.hasMarkers(t)&&(n(t,"marker")&&i(t,t.marker.color,"marker","c"),n(t,"marker.line")&&i(t,t.marker.line.color,"marker.line","c"))}},{"../../components/colorscale/calc":605,"../../components/colorscale/has_colorscale":612,"./subtypes":1070}],1054:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20}},{}],1055:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./constants"),o=t("./subtypes"),s=t("./xy_defaults"),l=t("./marker_defaults"),c=t("./line_defaults"),u=t("./line_shape_defaults"),f=t("./text_defaults"),h=t("./fillcolor_defaults"),d=t("../../components/errorbars/defaults");e.exports=function(t,e,r,p){function m(r,a){return n.coerce(t,e,i,r,a)}var v=s(t,e,p,m),g=vU!=(O=S[T][1])>=U&&(C=S[T-1][0],P=S[T][0],O-z&&(L=C+(P-C)*(U-z)/(O-z),N=Math.min(N,L),F=Math.max(F,L)));N=Math.max(N,0),F=Math.min(F,d._length);var V=s.defaultLine;return s.opacity(h.fillcolor)?V=h.fillcolor:s.opacity((h.line||{}).color)&&(V=h.line.color),n.extendFlat(t,{distance:c+10,x0:N,x1:F,y0:U,y1:U,color:V}),delete t.index,h.text&&!Array.isArray(h.text)?t.text=String(h.text):t.text=h.name,[t]}}}},{"../../components/color":598,"../../components/errorbars":629,"../../components/fx":640,"../../lib":724,"./fill_hover_text":1056,"./get_trace_color":1058}],1060:[function(t,e,r){"use strict";var n={},i=t("./subtypes");n.hasLines=i.hasLines,n.hasMarkers=i.hasMarkers,n.hasText=i.hasText,n.isBubble=i.isBubble,n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.cleanData=t("./clean_data"),n.calc=t("./calc").calc,n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.colorbar=t("./colorbar"),n.style=t("./style").style,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.animatable=!0,n.moduleType="trace",n.name="scatter",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","symbols","markerColorscale","errorBarsOK","showLegend","scatter-like"],n.meta={},e.exports=n},{"../../plots/cartesian":781,"./arrays_to_calcdata":1047,"./attributes":1048,"./calc":1049,"./clean_data":1051,"./colorbar":1052,"./defaults":1055,"./hover":1059,"./plot":1067,"./select":1068,"./style":1069,"./subtypes":1070}],1061:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults");e.exports=function(t,e,r,a,o,s){var l=(t.marker||{}).color;(o("line.color",r),n(t,"line"))?i(t,e,a,o,{prefix:"line.",cLetter:"c"}):o("line.color",!Array.isArray(l)&&l||r);o("line.width"),(s||{}).noDash||o("line.dash")}},{"../../components/colorscale/defaults":608,"../../components/colorscale/has_colorscale":612}],1062:[function(t,e,r){"use strict";var n=t("../../constants/numerical").BADNUM,i=t("../../lib"),a=i.segmentsIntersect,o=i.constrain,s=t("./constants");e.exports=function(t,e){var r,l,c,u,f,h,d,p,m,v,g,y,b,x,_,w,M=e.xaxis,k=e.yaxis,A=e.simplify,T=e.connectGaps,E=e.baseTolerance,S=e.shape,L="linear"===S,C=[],P=s.minTolerance,z=new Array(t.length),O=0;function D(e){var r=t[e],i=M.c2p(r.x),a=k.c2p(r.y);return i===n||a===n?r.intoCenter||!1:[i,a]}function I(t){var e=t[0]/M._length,r=t[1]/k._length;return(1+s.toleranceGrowth*Math.max(0,-e,e-1,-r,r-1))*E}function R(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}A||(E=P=-1);var N,F,j,B,U,V,q,H=s.maxScreensAway,G=-M._length*H,Y=M._length*(1+H),W=-k._length*H,X=k._length*(1+H),Z=[[G,W,Y,W],[Y,W,Y,X],[Y,X,G,X],[G,X,G,W]];function J(t){if(t[0]Y||t[1]X)return[o(t[0],G,Y),o(t[1],W,X)]}function K(t,e){return t[0]===e[0]&&(t[0]===G||t[0]===Y)||(t[1]===e[1]&&(t[1]===W||t[1]===X)||void 0)}function Q(t,e,r){return function(n,a){var o=J(n),s=J(a),l=[];if(o&&s&&K(o,s))return l;o&&l.push(o),s&&l.push(s);var c=2*i.constrain((n[t]+a[t])/2,e,r)-((o||n)[t]+(s||a)[t]);c&&((o&&s?c>0==o[t]>s[t]?o:s:o||s)[t]+=c);return l}}function $(t){var e=t[0],r=t[1],n=e===z[O-1][0],i=r===z[O-1][1];if(!n||!i)if(O>1){var a=e===z[O-2][0],o=r===z[O-2][1];n&&(e===G||e===Y)&&a?o?O--:z[O-1]=t:i&&(r===W||r===X)&&o?a?O--:z[O-1]=t:z[O++]=t}else z[O++]=t}function tt(t){z[O-1][0]!==t[0]&&z[O-1][1]!==t[1]&&$([j,B]),$(t),U=null,j=B=0}function et(t){if(N=t[0]Y?Y:0,F=t[1]X?X:0,N||F){if(O)if(U){var e=q(U,t);e.length>1&&(tt(e[0]),z[O++]=e[1])}else V=q(z[O-1],t)[0],z[O++]=V;else z[O++]=[N||t[0],F||t[1]];var r=z[O-1];N&&F&&(r[0]!==N||r[1]!==F)?(U&&(j!==N&&B!==F?$(j&&B?(n=U,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?G:Y,X]:[o>0?Y:G,W]):[j||N,B||F]):j&&B&&$([j,B])),$([N,F])):j-N&&B-F&&$([N||j,F||B]),U=t,j=N,B=F}else U&&tt(q(U,t)[0]),z[O++]=t;var n,i,a,o}for("linear"===S||"spline"===S?q=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var o=Z[i],s=a(t[0],t[1],e[0],e[1],o[0],o[1],o[2],o[3]);s&&(!n||Math.abs(s.x-r[0][0])>1||Math.abs(s.y-r[0][1])>1)&&(s=[s.x,s.y],n&&R(s,t)I(h))break;c=h,(b=m[0]*p[0]+m[1]*p[1])>g?(g=b,u=h,d=!1):b=t.length||!h)break;et(h),l=h}}else et(u)}U&&$([j||U[0],B||U[1]]),C.push(z.slice(0,O))}return C}},{"../../constants/numerical":702,"../../lib":724,"./constants":1054}],1063:[function(t,e,r){"use strict";e.exports=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")}},{}],1064:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,i,a=null;for(i=0;i0?Math.max(e,i):0}}},{"fast-isnumeric":140}],1066:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l,c){var u=o.isBubble(t),f=(t.line||{}).color;(c=c||{},f&&(r=f),l("marker.symbol"),l("marker.opacity",u?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),c.noSelect||(l("selected.marker.color"),l("unselected.marker.color"),l("selected.marker.size"),l("unselected.marker.size")),c.noLine||(l("marker.line.color",f&&!Array.isArray(f)&&e.marker.color!==f?f:u?n.background:n.defaultLine),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",u?1:0)),u&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode")),c.gradient)&&("none"!==l("marker.gradient.type")&&l("marker.gradient.color"))}},{"../../components/color":598,"../../components/colorscale/defaults":608,"../../components/colorscale/has_colorscale":612,"./subtypes":1070}],1067:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=t("../../components/errorbars"),s=t("./subtypes"),l=t("./line_points"),c=t("./link_traces"),u=t("../../lib/polygon").tester;function f(t,e,r,c,f,h,d){var p,m;!function(t,e,r,a,o){var l=r.xaxis,c=r.yaxis,u=n.extent(i.simpleMap(l.range,l.r2c)),f=n.extent(i.simpleMap(c.range,c.r2c)),h=a[0].trace;if(!s.hasMarkers(h))return;var d=h.marker.maxdisplayed;if(0===d)return;var p=a.filter(function(t){return t.x>=u[0]&&t.x<=u[1]&&t.y>=f[0]&&t.y<=f[1]}),m=Math.ceil(p.length/d),v=0;o.forEach(function(t,r){var n=t[0].trace;s.hasMarkers(n)&&n.marker.maxdisplayed>0&&r0;function g(t){return v?t.transition():t}var y=r.xaxis,b=r.yaxis,x=c[0].trace,_=x.line,w=n.select(h);if(w.call(o.plot,r,d),!0===x.visible){var M,k;g(w).style("opacity",x.opacity);var A=x.fill.charAt(x.fill.length-1);"x"!==A&&"y"!==A&&(A=""),c[0].node3=w;var T="",E=[],S=x._prevtrace;S&&(T=S._prevRevpath||"",k=S._nextFill,E=S._polygons);var L,C,P,z,O,D,I,R,N,F="",j="",B=[],U=i.noop;if(M=x._ownFill,s.hasLines(x)||"none"!==x.fill){for(k&&k.datum(c),-1!==["hv","vh","hvh","vhv"].indexOf(_.shape)?(P=a.steps(_.shape),z=a.steps(_.shape.split("").reverse().join(""))):P=z="spline"===_.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?a.smoothclosed(t.slice(1),_.smoothing):a.smoothopen(t,_.smoothing)}:function(t){return"M"+t.join("L")},O=function(t){return z(t.reverse())},B=l(c,{xaxis:y,yaxis:b,connectGaps:x.connectgaps,baseTolerance:Math.max(_.width||1,3)/4,shape:_.shape,simplify:_.simplify}),N=x._polygons=new Array(B.length),m=0;m1){var r=n.select(this);if(r.datum(c),t)g(r.style("opacity",0).attr("d",L).call(a.lineGroupStyle)).style("opacity",1);else{var i=g(r);i.attr("d",L),a.singleLineStyle(c,i)}}}}}var V=w.selectAll(".js-line").data(B);g(V.exit()).style("opacity",0).remove(),V.each(U(!1)),V.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(a.lineGroupStyle).each(U(!0)),a.setClipUrl(V,r.layerClipId),B.length?(M?D&&R&&(A?("y"===A?D[1]=R[1]=b.c2p(0,!0):"x"===A&&(D[0]=R[0]=y.c2p(0,!0)),g(M).attr("d","M"+R+"L"+D+"L"+F.substr(1)).call(a.singleFillStyle)):g(M).attr("d",F+"Z").call(a.singleFillStyle)):k&&("tonext"===x.fill.substr(0,6)&&F&&T?("tonext"===x.fill?g(k).attr("d",F+"Z"+T+"Z").call(a.singleFillStyle):g(k).attr("d",F+"L"+T.substr(1)+"Z").call(a.singleFillStyle),x._polygons=x._polygons.concat(E)):(H(k),x._polygons=null)),x._prevRevpath=j,x._prevPolygons=N):(M?H(M):k&&H(k),x._polygons=x._prevRevpath=x._prevPolygons=null);var q=w.selectAll(".points");p=q.data([c]),q.each(Z),p.enter().append("g").classed("points",!0).each(Z),p.exit().remove(),p.each(function(t){var e=!1===t[0].trace.cliponaxis;a.setClipUrl(n.select(this),e?null:r.layerClipId)})}function H(t){g(t).attr("d","M0,0Z")}function G(t){return t.filter(function(t){return t.vis})}function Y(t){return t.id}function W(t){if(t.ids)return Y}function X(){return!1}function Z(e){var o,l=e[0].trace,c=n.select(this),u=s.hasMarkers(l),f=s.hasText(l),h=W(l),d=X,p=X;u&&(d=l.marker.maxdisplayed||l._needsCull?G:i.identity),f&&(p=l.marker.maxdisplayed||l._needsCull?G:i.identity);var m=(o=c.selectAll("path.point").data(d,h)).enter().append("path").classed("point",!0);v&&m.call(a.pointStyle,l,t).call(a.translatePoints,y,b).style("opacity",0).transition().style("opacity",1);var x=u&&a.tryColorscale(l.marker,""),_=u&&a.tryColorscale(l.marker,"line");o.order(),o.each(function(e){var i=n.select(this),o=g(i);a.translatePoint(e,o,y,b)?(a.singlePointStyle(e,o,l,x,_,t),r.layerClipId&&a.hideOutsideRangePoint(e,o,y,b,l.xcalendar,l.ycalendar),l.customdata&&i.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):o.remove()}),v?o.exit().transition().style("opacity",0).remove():o.exit().remove(),(o=c.selectAll("g").data(p,h)).enter().append("g").classed("textpoint",!0).append("text"),o.order(),o.each(function(t){var e=n.select(this),i=g(e.select("text"));a.translatePoint(t,i,y,b)?r.layerClipId&&a.hideOutsideRangePoint(t,e,y,b,l.xcalendar,l.ycalendar):e.remove()}),o.selectAll("text").call(a.textPointStyle,l,t).each(function(t){var e=y.c2p(t.x),r=b.c2p(t.y);n.select(this).selectAll("tspan.line").each(function(){g(n.select(this)).attr({x:e,y:r})})}),o.exit().remove()}}e.exports=function(t,e,r,i,o){var s,l,u,h,d=e.plot.select("g.scatterlayer"),p=!i,m=!!i&&i.duration>0;for((u=d.selectAll("g.trace").data(r,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),c(t,e,r),function(t,e,r){var i;e.selectAll("g.trace").each(function(t){var e=n.select(this);if((i=t[0].trace)._nexttrace){if(i._nextFill=e.select(".js-fill.js-tonext"),!i._nextFill.size()){var o=":first-child";e.select(".js-fill.js-tozero").size()&&(o+=" + *"),i._nextFill=e.insert("path",o).attr("class","js-fill js-tonext")}}else e.selectAll(".js-fill.js-tonext").remove(),i._nextFill=null;i.fill&&("tozero"===i.fill.substr(0,6)||"toself"===i.fill||"to"===i.fill.substr(0,2)&&!i._prevtrace)?(i._ownFill=e.select(".js-fill.js-tozero"),i._ownFill.size()||(i._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),i._ownFill=null),e.selectAll(".js-fill").call(a.setClipUrl,r.layerClipId)})}(0,d,e),s=0,l={};sl[e[0].trace.uid]?1:-1}),m)?(o&&(h=o()),n.transition().duration(i.duration).ease(i.easing).each("end",function(){h&&h()}).each("interrupt",function(){h&&h()}).each(function(){d.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)})})):d.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)});p&&u.exit().remove(),d.selectAll("path:not([d])").remove()}},{"../../components/drawing":623,"../../components/errorbars":629,"../../lib":724,"../../lib/polygon":736,"./line_points":1062,"./link_traces":1064,"./subtypes":1070,d3:128}],1068:[function(t,e,r){"use strict";var n=t("./subtypes");e.exports=function(t,e){var r,i,a,o,s=t.cd,l=t.xaxis,c=t.yaxis,u=[],f=s[0].trace;if(!n.hasMarkers(f)&&!n.hasText(f))return[];if(!1===e)for(r=0;r=0&&(d[1]+=1),h.indexOf("top")>=0&&(d[1]-=1),h.indexOf("left")>=0&&(d[0]-=1),h.indexOf("right")>=0&&(d[0]+=1),d)),r.textColor=u(e.textfont,1,L),r.textSize=b(e.textfont.size,L,l.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var D=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;n<3;++n){var I=e.projection[D[n]];(r.project[n]=I.show)&&(r.projectOpacity[n]=I.opacity,r.projectScale[n]=I.scale)}r.errorBounds=p(e,x);var R=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=c(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=c(e.surfacecolor),r}function _(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}v.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels?void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel=this.textLabels:t.textLabel="";var e=t.index=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},v.update=function(t){var e,r,l,c,u=this.scene.glplot.gl,f=h.solid;this.data=t;var d=x(this.scene,t);"mode"in d&&(this.mode=d.mode),"lineDashes"in d&&d.lineDashes in h&&(f=h[d.lineDashes]),this.color=_(d.scatterColor)||_(d.lineColor),this.dataPoints=d.position,e={gl:u,position:d.position,color:d.lineColor,lineWidth:d.lineWidth||1,dashes:f[0],dashScale:f[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=n(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var p=t.opacity;if(t.marker&&t.marker.opacity&&(p*=t.marker.opacity),r={gl:u,position:d.position,color:d.scatterColor,size:d.scatterSize,glyph:d.scatterMarker,opacity:p,orthographic:!0,lineWidth:d.scatterLineWidth,lineColor:d.scatterLineColor,project:d.project,projectScale:d.projectScale,projectOpacity:d.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=i(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),c={gl:u,position:d.position,glyph:d.text,color:d.textColor,size:d.textSize,angle:d.textAngle,alignment:d.textOffset,font:d.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(c):(this.textMarkers=i(c),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),l={gl:u,position:d.position,color:d.errorColor,error:d.errorBounds,lineWidth:d.errorLineWidth,capSize:d.errorCapSize,opacity:t.opacity},this.errorBars?d.errorBounds?this.errorBars.update(l):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):d.errorBounds&&(this.errorBars=a(l),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),d.delaunayAxis>=0){var m=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],l=[];for(n=0;n=0&&h("surfacecolor",d||p);for(var m=["x","y","z"],v=0;v<3;++v){var g="projection."+m[v];h(g+".show")&&(h(g+".opacity"),h(g+".scale"))}c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}else e.visible=!1}},{"../../components/errorbars/defaults":628,"../../lib":724,"../../registry":854,"../scatter/line_defaults":1061,"../scatter/marker_defaults":1066,"../scatter/subtypes":1070,"../scatter/text_defaults":1071,"./attributes":1073}],1078:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl3d_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl3d_markers":700,"../../plots/gl3d":813,"../scatter/colorbar":1052,"./attributes":1073,"./calc":1074,"./convert":1076,"./defaults":1077}],1079:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/colorscale/color_attributes"),o=t("../../components/colorbar/attributes"),s=t("../../lib/extend").extendFlat,l=n.marker,c=n.line,u=l.line;e.exports={carpet:{valType:"string",editType:"calc"},a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},mode:s({},n.mode,{dflt:"markers"}),text:s({},n.text,{}),line:{color:c.color,width:c.width,dash:c.dash,shape:s({},c.shape,{values:["linear","spline"]}),smoothing:c.smoothing,editType:"calc"},connectgaps:n.connectgaps,fill:s({},n.fill,{values:["none","toself","tonext"]}),fillcolor:n.fillcolor,marker:s({symbol:l.symbol,opacity:l.opacity,maxdisplayed:l.maxdisplayed,size:l.size,sizeref:l.sizeref,sizemin:l.sizemin,sizemode:l.sizemode,line:s({width:u.width,editType:"calc"},a("marker".line)),gradient:l.gradient,editType:"calc"},a("marker"),{showscale:l.showscale,colorbar:o}),textfont:n.textfont,textposition:n.textposition,selected:n.selected,unselected:n.unselected,hoverinfo:s({},i.hoverinfo,{flags:["a","b","text","name"]}),hoveron:n.hoveron}},{"../../components/colorbar/attributes":599,"../../components/colorscale/color_attributes":606,"../../lib/extend":713,"../../plots/attributes":768,"../scatter/attributes":1048}],1080:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../scatter/colorscale_calc"),a=t("../scatter/arrays_to_calcdata"),o=t("../scatter/calc_selection"),s=t("../scatter/calc").calcMarkerSize,l=t("../carpet/lookup_carpetid");e.exports=function(t,e){var r=e.carpetTrace=l(t,e);if(r&&r.visible&&"legendonly"!==r.visible){var c;e.xaxis=r.xaxis,e.yaxis=r.yaxis;var u,f,h=e.a.length,d=new Array(h),p=!1;for(c=0;c"),a}function w(t,e){var r;r=t.labelprefix&&t.labelprefix.length>0?t.labelprefix.replace(/ = $/,""):t._hovertitle,m.push(r+": "+e.toFixed(3)+t.labelsuffix)}}},{"../scatter/hover":1059}],1084:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../scatter/style").style,n.hoverPoints=t("./hover"),n.selectPoints=t("../scatter/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="scattercarpet",n.basePlotModule=t("../../plots/cartesian"),n.categories=["carpet","symbols","markerColorscale","showLegend","carpetDependent"],n.meta={},e.exports=n},{"../../plots/cartesian":781,"../scatter/colorbar":1052,"../scatter/select":1068,"../scatter/style":1069,"./attributes":1079,"./calc":1080,"./defaults":1081,"./event_data":1082,"./hover":1083,"./plot":1085}],1085:[function(t,e,r){"use strict";var n=t("../scatter/plot"),i=t("../../plots/cartesian/axes"),a=t("../../components/drawing");e.exports=function(t,e,r){var o,s,l,c=r[0][0].carpet,u={xaxis:i.getFromId(t,c.xaxis||"x"),yaxis:i.getFromId(t,c.yaxis||"y"),plot:e.plot};for(n(t,u,r),o=0;o")}(u,v,d.mockAxis,c[0].t.labels),[t]}}},{"../../components/fx":640,"../../constants/numerical":702,"../../plots/cartesian/axes":770,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058,"./attributes":1086}],1091:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scattergeo",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","symbols","markerColorscale","showLegend","scatter-like"],n.meta={},e.exports=n},{"../../plots/geo":801,"../scatter/colorbar":1052,"./attributes":1086,"./calc":1087,"./defaults":1088,"./event_data":1089,"./hover":1090,"./plot":1092,"./select":1093,"./style":1094}],1092:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../constants/numerical").BADNUM,o=t("../../lib/topojson_utils").getTopojsonFeatures,s=t("../../lib/geo_location_utils").locationToFeature,l=t("../../lib/geojson_utils"),c=t("../scatter/subtypes"),u=t("./style");function f(t,e){var r=t[0].trace;if(Array.isArray(r.locations))for(var n=o(r,e),i=r.locationmode,l=0;l1,c=r.error_x&&!0===r.error_x.visible,f=r.error_y&&!0===r.error_y.visible,h=c||f,v=u.hasMarkers(r),g=!!r.fill&&"none"!==r.fill);var I=h?a.calcFromTrace(r,E):null;if(c){(_={}).positions=n;var N=new Float64Array(4*S);if("log"===O.type)for(i=0;iz?"rect":v?"rect":"round",B&&r.connectgaps){var U=T[0],V=T[1];for(i=0;iv?p.slice(0,v):p,y="log"===h.type||m.length>v?m.slice(0,v):m,b="log"===u.type?u.d2l:parseFloat,x="log"===h.type?h.d2l:parseFloat;for(r=new Array(2*v),n=0;ni&&(k[0]=i),k[1]a&&(T[0]=a),T[1]=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),h=e-f;if(n.getClosest(s,function(t){var e=t.lonlat;if(e[0]===o)return 1/0;var n=Math.abs(c.c2p(e)-c.c2p([h,e[1]])),i=Math.abs(u.c2p(e)-u.c2p([e[0],r])),a=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(n*n+i*i)-a,1-3/a)},t),!1!==t.index){var d=s[t.index],p=d.lonlat,m=[p[0]+f,p[1]],v=c.c2p(m),g=u.c2p(m),y=d.mrc||1;return t.x0=v-y,t.x1=v+y,t.y0=g-y,t.y1=g+y,t.color=i(l,d),t.extraText=function(t,e,r){var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),o=-1!==n.indexOf("lon"),s=-1!==n.indexOf("lat"),l=e.lonlat,c=[];function u(t){return t+"\xb0"}i||o&&s?c.push("("+u(l[0])+", "+u(l[1])+")"):o?c.push(r.lon+u(l[0])):s&&c.push(r.lat+u(l[1]));(i||-1!==n.indexOf("text"))&&a(e,t,c);return c.join("
")}(l,d,s[0].t.labels),[t]}}},{"../../components/fx":640,"../../constants/numerical":702,"../scatter/fill_hover_text":1056,"../scatter/get_trace_color":1058}],1103:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("../scattergeo/calc"),n.plot=t("./plot"),n.hoverPoints=t("./hover"),n.eventData=t("./event_data"),n.selectPoints=t("./select"),n.style=function(t,e){e&&e[0].trace._glTrace.update(e)},n.moduleType="trace",n.name="scattermapbox",n.basePlotModule=t("../../plots/mapbox"),n.categories=["mapbox","gl","symbols","markerColorscale","showLegend","scatterlike"],n.meta={},e.exports=n},{"../../plots/mapbox":827,"../scatter/colorbar":1052,"../scattergeo/calc":1087,"./attributes":1098,"./defaults":1100,"./event_data":1101,"./hover":1102,"./plot":1104,"./select":1105}],1104:[function(t,e,r){"use strict";var n=t("./convert");function i(t,e){this.mapbox=t,this.map=t.map,this.uid=e,this.idSourceFill=e+"-source-fill",this.idSourceLine=e+"-source-line",this.idSourceCircle=e+"-source-circle",this.idSourceSymbol=e+"-source-symbol",this.idLayerFill=e+"-layer-fill",this.idLayerLine=e+"-layer-line",this.idLayerCircle=e+"-layer-circle",this.idLayerSymbol=e+"-layer-symbol",this.mapbox.initSource(this.idSourceFill),this.mapbox.initSource(this.idSourceLine),this.mapbox.initSource(this.idSourceCircle),this.mapbox.initSource(this.idSourceSymbol),this.map.addLayer({id:this.idLayerFill,source:this.idSourceFill,type:"fill"}),this.map.addLayer({id:this.idLayerLine,source:this.idSourceLine,type:"line"}),this.map.addLayer({id:this.idLayerCircle,source:this.idSourceCircle,type:"circle"}),this.map.addLayer({id:this.idLayerSymbol,source:this.idSourceSymbol,type:"symbol"})}var a=i.prototype;function o(t){return"visible"===t.layout.visibility}a.update=function(t){var e=this.mapbox,r=n(t);e.setOptions(this.idLayerFill,"setLayoutProperty",r.fill.layout),e.setOptions(this.idLayerLine,"setLayoutProperty",r.line.layout),e.setOptions(this.idLayerCircle,"setLayoutProperty",r.circle.layout),e.setOptions(this.idLayerSymbol,"setLayoutProperty",r.symbol.layout),o(r.fill)&&(e.setSourceData(this.idSourceFill,r.fill.geojson),e.setOptions(this.idLayerFill,"setPaintProperty",r.fill.paint)),o(r.line)&&(e.setSourceData(this.idSourceLine,r.line.geojson),e.setOptions(this.idLayerLine,"setPaintProperty",r.line.paint)),o(r.circle)&&(e.setSourceData(this.idSourceCircle,r.circle.geojson),e.setOptions(this.idLayerCircle,"setPaintProperty",r.circle.paint)),o(r.symbol)&&(e.setSourceData(this.idSourceSymbol,r.symbol.geojson),e.setOptions(this.idLayerSymbol,"setPaintProperty",r.symbol.paint)),t[0].trace._glTrace=this},a.dispose=function(){var t=this.map;t.removeLayer(this.idLayerFill),t.removeLayer(this.idLayerLine),t.removeLayer(this.idLayerCircle),t.removeLayer(this.idLayerSymbol),t.removeSource(this.idSourceFill),t.removeSource(this.idSourceLine),t.removeSource(this.idSourceCircle),t.removeSource(this.idSourceSymbol)},e.exports=function(t,e){var r=new i(t,e[0].trace.uid);return r.update(e),r}},{"./convert":1099}],1105:[function(t,e,r){"use strict";var n=t("../scatter/subtypes");e.exports=function(t,e){var r,i,a,o,s,l=t.cd,c=t.xaxis,u=t.yaxis,f=[],h=l[0].trace;if(!n.hasMarkers(h))return[];if(!1===e)for(s=0;s")}e.exports={hoverPoints:function(t,e,r,i){var a=n(t,e,r,i);if(a&&!1!==a[0].index){var s=a[0];if(void 0===s.index)return a;var l=t.subplot,c=s.cd[s.index],u=s.trace;if(l.isPtWithinSector(c))return s.xLabelVal=void 0,s.yLabelVal=void 0,s.extraText=o(c,u,l),a}},makeHoverPointText:o}},{"../../lib":724,"../../plots/cartesian/axes":770,"../scatter/hover":1059}],1110:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"scatterpolar",basePlotModule:t("../../plots/polar"),categories:["polar","symbols","markerColorscale","showLegend","scatter-like"],attributes:t("./attributes"),supplyDefaults:t("./defaults"),calc:t("./calc"),plot:t("./plot"),style:t("../scatter/style").style,hoverPoints:t("./hover").hoverPoints,selectPoints:t("../scatter/select"),meta:{}}},{"../../plots/polar":836,"../scatter/select":1068,"../scatter/style":1069,"./attributes":1106,"./calc":1107,"./defaults":1108,"./hover":1109,"./plot":1111}],1111:[function(t,e,r){"use strict";var n=t("../scatter/plot"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e,r){var a,o,s,l={xaxis:e.xaxis,yaxis:e.yaxis,plot:e.framework,layerClipId:e._hasClipOnAxisFalse?e.clipIds.circle:null},c=e.radialAxis,u=c.range;for(s=u[0]>u[1]?function(t){return t<=0}:function(t){return t>=0},a=0;a=0?(m=o.c2r(p)-l[0],A=v,g=s.c2rad(A,b.thetaunit),S[d]=E[2*d]=m*Math.cos(g),L[d]=E[2*d+1]=m*Math.sin(g)):S[d]=L[d]=E[2*d]=E[2*d+1]=NaN;var C=a.sceneOptions(t,e,b,E);C.fill&&!u.fill2d&&(u.fill2d=!0),C.marker&&!u.scatter2d&&(u.scatter2d=!0),C.line&&!u.line2d&&(u.line2d=!0),!C.errorX&&!C.errorY||u.error2d||(u.error2d=!0),c.hasMarkers(b)&&(C.selected.positions=C.unselected.positions=C.marker.positions),u.lineOptions.push(C.line),u.errorXOptions.push(C.errorX),u.errorYOptions.push(C.errorY),u.fillOptions.push(C.fill),u.markerOptions.push(C.marker),u.selectedOptions.push(C.selected),u.unselectedOptions.push(C.unselected),u.count=r.length,x.scene=u,x.index=h,x.x=S,x.y=L,x.rawx=S,x.rawy=L,x.r=_,x.theta=w,x.positions=E,x.count=T,x.tree=n(E,512)}}),a.plot(t,e,r)},hoverPoints:function(t,e,r,n){var i=t.cd[0].t,o=i.r,s=i.theta,c=a.hoverPoints(t,e,r,n);if(c&&!1!==c[0].index){var u=c[0];if(void 0===u.index)return c;var f=t.subplot,h=f.angularAxis,d=u.cd[u.index],p=u.trace;if(d.r=o[u.index],d.theta=s[u.index],d.rad=h.c2rad(d.theta,p.thetaunit),f.isPtWithinSector(d))return u.xLabelVal=void 0,u.yLabelVal=void 0,u.extraText=l(d,p,f),c}},style:a.style,selectPoints:a.selectPoints,meta:{}}},{"../../plots/cartesian/axes":770,"../../plots/polar":836,"../scatter/colorscale_calc":1053,"../scatter/subtypes":1070,"../scattergl":1097,"../scatterpolar/hover":1109,"./attributes":1112,"./defaults":1113,"fast-isnumeric":140,kdgrass:272}],1115:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/colorscale/color_attributes"),o=t("../../components/colorbar/attributes"),s=t("../../components/drawing/attributes").dash,l=t("../../lib/extend").extendFlat,c=n.marker,u=n.line,f=c.line;e.exports={a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},c:{valType:"data_array",editType:"calc"},sum:{valType:"number",dflt:0,min:0,editType:"calc"},mode:l({},n.mode,{dflt:"markers"}),text:l({},n.text,{}),hovertext:l({},n.hovertext,{}),line:{color:u.color,width:u.width,dash:s,shape:l({},u.shape,{values:["linear","spline"]}),smoothing:u.smoothing,editType:"calc"},connectgaps:n.connectgaps,cliponaxis:n.cliponaxis,fill:l({},n.fill,{values:["none","toself","tonext"]}),fillcolor:n.fillcolor,marker:l({symbol:c.symbol,opacity:c.opacity,maxdisplayed:c.maxdisplayed,size:c.size,sizeref:c.sizeref,sizemin:c.sizemin,sizemode:c.sizemode,line:l({width:f.width,editType:"calc"},a("marker.line")),gradient:c.gradient,editType:"calc"},a("marker"),{showscale:c.showscale,colorbar:o}),textfont:n.textfont,textposition:n.textposition,selected:n.selected,unselected:n.unselected,hoverinfo:l({},i.hoverinfo,{flags:["a","b","c","text","name"]}),hoveron:n.hoveron}},{"../../components/colorbar/attributes":599,"../../components/colorscale/color_attributes":606,"../../components/drawing/attributes":622,"../../lib/extend":713,"../../plots/attributes":768,"../scatter/attributes":1048}],1116:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../scatter/colorscale_calc"),a=t("../scatter/arrays_to_calcdata"),o=t("../scatter/calc_selection"),s=t("../scatter/calc").calcMarkerSize,l=["a","b","c"],c={a:["b","c"],b:["a","c"],c:["a","b"]};e.exports=function(t,e){var r,u,f,h,d,p,m=t._fullLayout[e.subplot].sum,v=e.sum||m,g={a:e.a,b:e.b,c:e.c};for(r=0;r"),o}function g(t,e){v.push(t._hovertitle+": "+i.tickText(t,e,"hover").text)}}},{"../../plots/cartesian/axes":770,"../scatter/hover":1059}],1120:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("../scatter/style").style,n.hoverPoints=t("./hover"),n.selectPoints=t("../scatter/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","markerColorscale","showLegend","scatter-like"],n.meta={},e.exports=n},{"../../plots/ternary":847,"../scatter/colorbar":1052,"../scatter/select":1068,"../scatter/style":1069,"./attributes":1115,"./calc":1116,"./defaults":1117,"./event_data":1118,"./hover":1119,"./plot":1121}],1121:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e,r){var i=e.plotContainer;i.select(".scatterlayer").selectAll("*").remove();var a={xaxis:e.xaxis,yaxis:e.yaxis,plot:i,layerClipId:e._hasClipOnAxisFalse?e.clipIdRelative:null};n(t,a,r)}},{"../scatter/plot":1067}],1122:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),o=t("../../plots/attributes"),s=t("../../lib/extend").extendFlat,l=t("../../plot_api/edit_types").overrideAll;function c(t){return{show:{valType:"boolean",dflt:!1},project:{x:{valType:"boolean",dflt:!1},y:{valType:"boolean",dflt:!1},z:{valType:"boolean",dflt:!1}},color:{valType:"color",dflt:n.defaultLine},usecolormap:{valType:"boolean",dflt:!1},width:{valType:"number",min:1,max:16,dflt:2},highlight:{valType:"boolean",dflt:!0},highlightcolor:{valType:"color",dflt:n.defaultLine},highlightwidth:{valType:"number",min:1,max:16,dflt:2}}}var u=e.exports=l({z:{valType:"data_array"},x:{valType:"data_array"},y:{valType:"data_array"},text:{valType:"string",dflt:"",arrayOk:!0},surfacecolor:{valType:"data_array"},cauto:i.zauto,cmin:i.zmin,cmax:i.zmax,colorscale:i.colorscale,autocolorscale:s({},i.autocolorscale,{dflt:!1}),reversescale:i.reversescale,showscale:i.showscale,colorbar:a,contours:{x:c(),y:c(),z:c()},hidesurface:{valType:"boolean",dflt:!1},lightposition:{x:{valType:"number",min:-1e5,max:1e5,dflt:10},y:{valType:"number",min:-1e5,max:1e5,dflt:1e4},z:{valType:"number",min:-1e5,max:1e5,dflt:0}},lighting:{ambient:{valType:"number",min:0,max:1,dflt:.8},diffuse:{valType:"number",min:0,max:1,dflt:.8},specular:{valType:"number",min:0,max:2,dflt:.05},roughness:{valType:"number",min:0,max:1,dflt:.5},fresnel:{valType:"number",min:0,max:5,dflt:.2}},opacity:{valType:"number",min:0,max:1,dflt:1},_deprecated:{zauto:s({},i.zauto,{}),zmin:s({},i.zmin,{}),zmax:s({},i.zmax,{})},hoverinfo:s({},o.hoverinfo)},"calc","nested");u.x.editType=u.y.editType=u.z.editType="calc+clearAxisTypes"},{"../../components/color":598,"../../components/colorbar/attributes":599,"../../components/colorscale/attributes":604,"../../lib/extend":713,"../../plot_api/edit_types":754,"../../plots/attributes":768}],1123:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){e.surfacecolor?n(e,e.surfacecolor,"","c"):n(e,e.z,"","c")}},{"../../components/colorscale/calc":605}],1124:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/plots"),o=t("../../components/colorscale"),s=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,l="cb"+r.uid,c=r.cmin,u=r.cmax,f=r.surfacecolor||r.z;if(n(c)||(c=i.aggNums(Math.min,null,f)),n(u)||(u=i.aggNums(Math.max,null,f)),t._fullLayout._infolayer.selectAll("."+l).remove(),r.showscale){var h=e[0].t.cb=s(t,l),d=o.makeColorScaleFunc(o.extractScale(r.colorscale,c,u),{noNumericCheck:!0});h.fillcolor(d).filllevels({start:c,end:u,size:(u-c)/254}).options(r.colorbar)()}else a.autoMargin(t,l)}},{"../../components/colorbar/draw":602,"../../components/colorscale":613,"../../lib":724,"../../plots/plots":833,"fast-isnumeric":140}],1125:[function(t,e,r){"use strict";var n=t("gl-surface3d"),i=t("ndarray"),a=t("ndarray-homography"),o=t("ndarray-fill"),s=t("ndarray-ops"),l=t("tinycolor2"),c=t("../../lib/str2rgbarray"),u=128;function f(t,e,r){this.scene=t,this.uid=r,this.surface=e,this.data=null,this.showContour=[!1,!1,!1],this.dataScale=1}var h=f.prototype;function d(t){var e=t.shape,r=[e[0]+2,e[1]+2],n=i(new Float32Array(r[0]*r[1]),r);return s.assign(n.lo(1,1).hi(e[0],e[1]),t),s.assign(n.lo(1).hi(e[0],1),t.hi(e[0],1)),s.assign(n.lo(1,r[1]-1).hi(e[0],1),t.lo(0,e[1]-1).hi(e[0],1)),s.assign(n.lo(0,1).hi(1,e[1]),t.hi(1)),s.assign(n.lo(r[0]-1,1).hi(1,e[1]),t.lo(e[0]-1)),n.set(0,0,t.get(0,0)),n.set(0,r[1]-1,t.get(0,e[1]-1)),n.set(r[0]-1,0,t.get(e[0]-1,0)),n.set(r[0]-1,r[1]-1,t.get(e[0]-1,e[1]-1)),n}h.handlePick=function(t){if(t.object===this.surface){var e=t.index=[Math.min(0|Math.round(t.data.index[0]/this.dataScale-1),this.data.z[0].length-1),Math.min(0|Math.round(t.data.index[1]/this.dataScale-1),this.data.z.length-1)],r=[0,0,0];Array.isArray(this.data.x)?Array.isArray(this.data.x[0])?r[0]=this.data.x[e[1]][e[0]]:r[0]=this.data.x[e[0]]:r[0]=e[0],Array.isArray(this.data.y)?Array.isArray(this.data.y[0])?r[1]=this.data.y[e[1]][e[0]]:r[1]=this.data.y[e[1]]:r[1]=e[1],r[2]=this.data.z[e[1]][e[0]],t.traceCoordinate=r;var n=this.scene.fullSceneLayout;t.dataCoordinate=[n.xaxis.d2l(r[0],0,this.data.xcalendar)*this.scene.dataScale[0],n.yaxis.d2l(r[1],0,this.data.ycalendar)*this.scene.dataScale[1],n.zaxis.d2l(r[2],0,this.data.zcalendar)*this.scene.dataScale[2]];var i=this.data.text;return Array.isArray(i)&&i[e[1]]&&void 0!==i[e[1]][e[0]]?t.textLabel=i[e[1]][e[0]]:t.textLabel=i||"",t.data.dataCoordinate=t.dataCoordinate.slice(),this.surface.highlight(t.data),this.scene.glplot.spikes.position=t.dataCoordinate,!0}},h.setContourLevels=function(){for(var t=[[],[],[]],e=!1,r=0;r<3;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},h.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,s=this.surface,f=t.opacity,h=function(t,e){return void 0===e&&(e=1),t.map(function(t){var r=t[0],n=l(t[1]).toRgb();return{index:r,rgb:[n.r,n.g,n.b,e]}})}(t.colorscale,f),p=t.z,m=t.x,v=t.y,g=n.xaxis,y=n.yaxis,b=n.zaxis,x=r.dataScale,_=p[0].length,w=t._ylength,M=[i(new Float32Array(_*w),[_,w]),i(new Float32Array(_*w),[_,w]),i(new Float32Array(_*w),[_,w])],k=M[0],A=M[1],T=r.contourLevels;this.data=t;var E=t.xcalendar,S=t.ycalendar,L=t.zcalendar;o(M[2],function(t,e){return b.d2l(p[e][t],0,L)*x[2]}),Array.isArray(m)?Array.isArray(m[0])?o(k,function(t,e){return g.d2l(m[e][t],0,E)*x[0]}):o(k,function(t){return g.d2l(m[t],0,E)*x[0]}):o(k,function(t){return g.d2l(t,0,E)*x[0]}),Array.isArray(m)?Array.isArray(v[0])?o(A,function(t,e){return y.d2l(v[e][t],0,S)*x[1]}):o(A,function(t,e){return y.d2l(v[e],0,S)*x[1]}):o(A,function(t,e){return y.d2l(e,0,E)*x[1]});var C={colormap:h,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:t.opacity};if(C.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var P=i(new Float32Array(_*w),[_,w]);o(P,function(e,r){return t.surfacecolor[r][e]}),M.push(P)}else C.intensityBounds[0]*=x[2],C.intensityBounds[1]*=x[2];this.dataScale=function(t){var e=Math.max(t[0].shape[0],t[0].shape[1]);if(e",maxDimensionCount:60,overdrag:45,releaseTransitionDuration:120,releaseTransitionEase:"cubic-out",scrollbarCaptureWidth:18,scrollbarHideDelay:1e3,scrollbarHideDuration:1e3,scrollbarOffset:5,scrollbarWidth:8,transitionDuration:100,transitionEase:"cubic-out",uplift:5,wrapSpacer:" ",wrapSplitCharacter:" ",cn:{table:"table",tableControlView:"table-control-view",scrollBackground:"scroll-background",yColumn:"y-column",columnBlock:"column-block",scrollAreaClip:"scroll-area-clip",scrollAreaClipRect:"scroll-area-clip-rect",columnBoundary:"column-boundary",columnBoundaryClippath:"column-boundary-clippath",columnBoundaryRect:"column-boundary-rect",columnCells:"column-cells",columnCell:"column-cell",cellRect:"cell-rect",cellText:"cell-text",cellTextHolder:"cell-text-holder",scrollbarKit:"scrollbar-kit",scrollbar:"scrollbar",scrollbarSlider:"scrollbar-slider",scrollbarGlyph:"scrollbar-glyph",scrollbarCaptureZone:"scrollbar-capture-zone"}}},{}],1132:[function(t,e,r){"use strict";var n=t("./constants"),i=t("../../lib/extend").extendFlat,a=t("fast-isnumeric");function o(t){return t.calcdata.columns.reduce(function(e,r){return r.xIndex=e||c===t.length-1)&&(n[i]=o,o.key=l++,o.firstRowIndex=s,o.lastRowIndex=c,o={firstRowIndex:null,lastRowIndex:null,rows:[]},i+=a,s=c+1,a=0);return n}e.exports=function(t,e){var r=e.cells.values,c=function(t){return t.slice(e.header.values.length,t.length)},u=e.header.values.map(function(t){return Array.isArray(t)?t:[t]}).concat(c(r).map(function(){return[""]})),f=e.domain,h=Math.floor(t._fullLayout._size.w*(f.x[1]-f.x[0])),d=Math.floor(t._fullLayout._size.h*(f.y[1]-f.y[0])),p=e.header.values.length?u[0].map(function(){return e.header.height}):[n.emptyHeaderHeight],m=r.length?r[0].map(function(){return e.cells.height}):[],v=p.reduce(function(t,e){return t+e},0),g=l(m,d-v+n.uplift),y=s(l(p,v),[]),b=s(g,y),x={},_=e._fullInput.columnorder.concat(c(r.map(function(t,e){return e}))),w=u.map(function(t,r){var n=Array.isArray(e.columnwidth)?e.columnwidth[Math.min(r,e.columnwidth.length-1)]:e.columnwidth;return a(n)?Number(n):1}),M=w.reduce(function(t,e){return t+e},0);w=w.map(function(t){return t/M*h});var k={key:e.index,translateX:f.x[0]*t._fullLayout._size.w,translateY:t._fullLayout._size.h*(1-f.y[1]),size:t._fullLayout._size,width:h,height:d,columnOrder:_,groupHeight:d,rowBlocks:b,headerRowBlocks:y,scrollY:0,cells:e.cells,headerCells:i({},e.header,{values:u}),gdColumns:u.map(function(t){return t[0]}),gdColumnsOriginalOrder:u.map(function(t){return t[0]}),prevPages:[0,0],scrollbarState:{scrollbarScrollInProgress:!1},columns:u.map(function(t,e){var r=x[t];return x[t]=(r||0)+1,{key:t+"__"+x[t],label:t,specIndex:e,xIndex:_[e],xScale:o,x:void 0,calcdata:void 0,columnWidth:w[e]}})};return k.columns.forEach(function(t){t.calcdata=k,t.x=o(t)}),k}},{"../../lib/extend":713,"./constants":1131,"fast-isnumeric":140}],1133:[function(t,e,r){"use strict";var n=t("../../lib/extend").extendFlat;r.splitToPanels=function(t){var e=[0,0],r=n({},t,{key:"header",type:"header",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!0,values:t.calcdata.headerCells.values[t.specIndex],rowBlocks:t.calcdata.headerRowBlocks,calcdata:n({},t.calcdata,{cells:t.calcdata.headerCells})});return[n({},t,{key:"cells1",type:"cells",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),n({},t,{key:"cells2",type:"cells",page:1,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),r]},r.splitToCells=function(t){var e=function(t){var e=t.rowBlocks[t.page],r=e?e.rows[0].rowIndex:0,n=e?r+e.rows.length:0;return[r,n]}(t);return(t.values||[]).slice(e[0],e[1]).map(function(r,n){return{keyWithinBlock:n+("string"==typeof r&&r.match(/[<$&> ]/)?"_keybuster_"+Math.random():""),key:e[0]+n,column:t,calcdata:t.calcdata,page:t.page,rowBlocks:t.rowBlocks,value:r}})}},{"../../lib/extend":713}],1134:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}o("domain.x"),o("domain.y"),o("columnwidth"),o("header.values"),o("header.format"),o("header.align"),o("header.prefix"),o("header.suffix"),o("header.height"),o("header.line.width"),o("header.line.color"),o("header.fill.color"),n.coerceFont(o,"header.font",n.extendFlat({},a.font)),function(t,e){for(var r=t.columnorder||[],n=t.header.values.length,i=r.slice(0,n),a=i.slice().sort(function(t,e){return t-e}),o=i.map(function(t){return a.indexOf(t)}),s=o.length;s/i),l=!o||s;t.mayHaveMarkup=o&&a.match(/[<&>]/);var c,u="string"==typeof(c=a)&&c.match(n.latexCheck);t.latex=u;var f,h,d=u?"":x(t.calcdata.cells.prefix,e,r)||"",p=u?"":x(t.calcdata.cells.suffix,e,r)||"",m=u?null:x(t.calcdata.cells.format,e,r)||null,v=d+(m?i.format(m)(t.value):t.value)+p;if(t.wrappingNeeded=!t.wrapped&&!l&&!u&&(f=b(v)),t.cellHeightMayIncrease=s||u||t.mayHaveMarkup||(void 0===f?b(v):f),t.needsConvertToTspans=t.mayHaveMarkup||t.wrappingNeeded||t.latex,t.wrappingNeeded){var g=(" "===n.wrapSplitCharacter?v.replace(/i&&n.push(a),i+=l}return n}(i,l,s);1===c.length&&(c[0]===i.length-1?c.unshift(c[0]-1):c.push(c[0]+1)),c[0]%2&&c.reverse(),e.each(function(t,e){t.page=c[e],t.scrollY=l}),e.attr("transform",function(t){return"translate(0 "+(z(t.rowBlocks,t.page)-t.scrollY)+")"}),t&&(E(t,r,e,c,n.prevPages,n,0),E(t,r,e,c,n.prevPages,n,1),v(r,t))}}function T(t,e,r,a){return function(o){var s=o.calcdata?o.calcdata:o,l=e.filter(function(t){return s.key===t.key}),c=r||s.scrollbarState.dragMultiplier;s.scrollY=void 0===a?s.scrollY+c*i.event.dy:a;var u=l.selectAll("."+n.cn.yColumn).selectAll("."+n.cn.columnBlock).filter(w);A(t,u,l)}}function E(t,e,r,n,i,a,o){n[o]!==i[o]&&(clearTimeout(a.currentRepaint[o]),a.currentRepaint[o]=setTimeout(function(){var a=r.filter(function(t,e){return e===o&&n[e]!==i[e]});g(t,e,a,r),i[o]=n[o]}))}function S(t,e,r){return function(){var a=i.select(e.parentNode);a.each(function(t){var e=t.fragments;a.selectAll("tspan.line").each(function(t,r){e[r].width=this.getComputedTextLength()});var r,i,o=e[e.length-1].width,s=e.slice(0,-1),l=[],c=0,u=t.column.columnWidth-2*n.cellPad;for(t.value="";s.length;)c+(i=(r=s.shift()).width+o)>u&&(t.value+=l.join(n.wrapSpacer)+n.lineBreaker,l=[],c=0),l.push(r.text),c+=i;c&&(t.value+=l.join(n.wrapSpacer)),t.wrapped=!0}),a.selectAll("tspan.line").remove(),y(a.select("."+n.cn.cellText),r,t),i.select(e.parentNode.parentNode).call(P)}}function L(t,e,r,a,o){return function(){if(!o.settledY){var s=i.select(e.parentNode),l=I(o),c=o.key-l.firstRowIndex,u=l.rows[c].rowHeight,f=o.cellHeightMayIncrease?e.parentNode.getBoundingClientRect().height+2*n.cellPad:u,h=Math.max(f,u);h-l.rows[c].rowHeight&&(l.rows[c].rowHeight=h,t.selectAll("."+n.cn.columnCell).call(P),A(null,t.filter(w),0),v(r,a,!0)),s.attr("transform",function(){var t=this.parentNode.getBoundingClientRect(),e=i.select(this.parentNode).select("."+n.cn.cellRect).node().getBoundingClientRect(),r=this.transform.baseVal.consolidate(),a=e.top-t.top+(r?r.matrix.f:n.cellPad);return"translate("+C(o,i.select(this.parentNode).select("."+n.cn.cellTextHolder).node().getBoundingClientRect().width)+" "+a+")"}),o.settledY=!0}}}function C(t,e){switch(t.align){case"left":return n.cellPad;case"right":return t.column.columnWidth-(e||0)-n.cellPad;case"center":return(t.column.columnWidth-(e||0))/2;default:return n.cellPad}}function P(t){t.attr("transform",function(t){var e=t.rowBlocks[0].auxiliaryBlocks.reduce(function(t,e){return t+O(e,1/0)},0);return"translate(0 "+(O(I(t),t.key)+e)+")"}).selectAll("."+n.cn.cellRect).attr("height",function(t){return(e=I(t),r=t.key,e.rows[r-e.firstRowIndex]).rowHeight;var e,r})}function z(t,e){for(var r=0,n=e-1;n>=0;n--)r+=D(t[n]);return r}function O(t,e){for(var r=0,n=0;n0){var y,b,x,_,w,M=t.xa,k=t.ya;"h"===h.orientation?(w=e,y="y",x=k,b="x",_=M):(w=r,y="x",x=M,b="y",_=k);var A=f[t.index];if(w>=A.span[0]&&w<=A.span[1]){var T=n.extendFlat({},t),E=_.c2p(w,!0),S=o.getKdeValue(A,h,w),L=o.getPositionOnKdePath(A,h,E),C=x._offset,P=x._length;T[y+"0"]=L[0],T[y+"1"]=L[1],T[b+"0"]=T[b+"1"]=E,T[b+"Label"]=b+": "+i.hoverLabelText(_,w)+", "+f[0].t.labels.kde+" "+S.toFixed(3),v.push(T),(u={stroke:t.color})[y+"1"]=n.constrain(C+L[0],C,C+P),u[y+"2"]=n.constrain(C+L[1],C,C+P),u[b+"1"]=u[b+"2"]=_._offset+E}}}-1!==d.indexOf("points")&&(c=a.hoverOnPoints(t,e,r));var z=l.selectAll(".violinline-"+h.uid).data(u?[0]:[]);return z.enter().append("line").classed("violinline-"+h.uid,!0).attr("stroke-width",1.5),z.exit().remove(),z.attr(u),"closest"===s?c?[c]:v:c?(v.push(c),v):v}},{"../../lib":724,"../../plots/cartesian/axes":770,"../box/hover":880,"./helpers":1140}],1142:[function(t,e,r){"use strict";e.exports={attributes:t("./attributes"),layoutAttributes:t("./layout_attributes"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),setPositions:t("./set_positions"),plot:t("./plot"),style:t("./style"),hoverPoints:t("./hover"),selectPoints:t("../box/select"),moduleType:"trace",name:"violin",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","symbols","oriented","box-violin","showLegend"],meta:{}}},{"../../plots/cartesian":781,"../box/select":885,"./attributes":1137,"./calc":1138,"./defaults":1139,"./hover":1141,"./layout_attributes":1143,"./layout_defaults":1144,"./plot":1145,"./set_positions":1146,"./style":1147}],1143:[function(t,e,r){"use strict";var n=t("../box/layout_attributes"),i=t("../../lib").extendFlat;e.exports={violinmode:i({},n.boxmode,{}),violingap:i({},n.boxgap,{}),violingroupgap:i({},n.boxgroupgap,{})}},{"../../lib":724,"../box/layout_attributes":882}],1144:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes"),a=t("../box/layout_defaults");e.exports=function(t,e,r){a._supply(t,e,r,function(r,a){return n.coerce(t,e,i,r,a)},"violin")}},{"../../lib":724,"../box/layout_defaults":883,"./layout_attributes":1143}],1145:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../lib"),a=t("../../components/drawing"),o=t("../box/plot"),s=t("../scatter/line_points"),l=t("./helpers");e.exports=function(t,e,r){var c=t._fullLayout,u=e.xaxis,f=e.yaxis;function h(t){var e=s(t,{xaxis:u,yaxis:f,connectGaps:!0,baseTolerance:.75,shape:"spline",simplify:!0});return a.smoothopen(e[0],1)}e.plot.select(".violinlayer").selectAll("g.trace.violins").data(r).enter().append("g").attr("class","trace violins").each(function(t){var r=t[0],a=r.t,s=r.trace,d=r.node3=n.select(this),p=c._numViolins,m="group"===c.violinmode&&p>1,v=a.bdPos=a.dPos*(1-c.violingap)*(1-c.violingroupgap)/(m?p:1),g=a.bPos=m?2*a.dPos*((a.num+.5)/p-.5)*(1-c.violingap):0;if(!0!==s.visible||a.empty)n.select(this).remove();else{var y=e[a.valLetter+"axis"],b=e[a.posLetter+"axis"],x="both"===s.side,_=x||"positive"===s.side,w=x||"negative"===s.side,M=s.box&&s.box.visible,k=s.meanline&&s.meanline.visible,A=c._violinScaleGroupStats[s.scalegroup];if(d.selectAll("path.violin").data(i.identity).enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin").each(function(t){var e,r,i,o,l,c,u,f,d=n.select(this),p=t.density,m=p.length,M=t.pos+g,k=b.c2p(M);switch(s.scalemode){case"width":e=A.maxWidth/v;break;case"count":e=A.maxWidth/v*(A.maxCount/t.pts.length)}if(_){for(u=new Array(m),l=0;la&&(a=u,o=c)}}return a?i(o):s};case"rms":return function(t,e){for(var r=0,a=0,o=0;o":return function(t){return h(t)>s};case">=":return function(t){return h(t)>=s};case"[]":return function(t){var e=h(t);return e>=s[0]&&e<=s[1]};case"()":return function(t){var e=h(t);return e>s[0]&&e=s[0]&&es[0]&&e<=s[1]};case"][":return function(t){var e=h(t);return e<=s[0]||e>=s[1]};case")(":return function(t){var e=h(t);return es[1]};case"](":return function(t){var e=h(t);return e<=s[0]||e>s[1]};case")[":return function(t){var e=h(t);return e=s[1]};case"{}":return function(t){return-1!==s.indexOf(h(t))};case"}{":return function(t){return-1===s.indexOf(h(t))}}}(r,a.getDataToCoordFunc(t,e,s,i),h),y={},b={},x=0;r.preservegaps?(m=function(t){y[t.astr]=n.extendDeep([],t.get()),t.set(new Array(f))},v=function(t,e){var r=y[t.astr][e];t.get()[e]=r}):(m=function(t){y[t.astr]=n.extendDeep([],t.get()),t.set([])},v=function(t,e){var r=y[t.astr][e];t.get().push(r)}),M(m);for(var _=o(e.transforms,r),w=0;w1?"%{group} (%{trace})":"%{group}");var l=t.styles,c=o.styles=[];if(l)for(a=0;a. + +from time import sleep + +import datetime +import math +import os +import platform +import re +import sys + +try: + from urllib import urlencode # Python2 +except ImportError: + import urllib + from urllib.parse import urlencode # Python3 + +try: + import urllib.request as urllib2 +except ImportError: + import urllib2 + +from sickbeard import logger +from sickbeard.helpers import getURL, tryInt + +try: + from lxml import etree +except ImportError: + try: + import xml.etree.cElementTree as etree + except ImportError: + import xml.etree.ElementTree as etree + + +class Plex: + def __init__(self, settings=None): + + settings = settings or {} + self._plex_host = settings.get('plex_host') or '127.0.0.1' + self.plex_port = settings.get('plex_port') or '32400' + + self.username = settings.get('username', '') + self.password = settings.get('password', '') + self.token = settings.get('token', '') + + self.device_name = settings.get('device_name', '') + self.client_id = settings.get('client_id') or '5369636B47656172' + self.machine_client_identifier = '' + + self.default_home_users = settings.get('default_home_users', '') + + # Progress percentage to consider video as watched + # if set to anything > 0, videos with watch progress greater than this will be considered watched + self.default_progress_as_watched = settings.get('default_progress_as_watched', 0) + + # Sections to scan. If empty all sections will be looked at, + # the section id should be used which is the number found be in the url on PlexWeb after /section/[ID] + self.section_list = settings.get('section_list', []) + + # Sections to skip scanning, for use when Settings['section_list'] is not specified, + # the same as section_list, the section id should be used + self.ignore_sections = settings.get('ignore_sections', []) + + # Filter sections by paths that are in this array + self.section_filter_path = settings.get('section_filter_path', []) + + # Results + self.show_states = {} + self.file_count = 0 + + # Conf + self.config_version = 2.0 + self.use_logger = False + self.test = None + self.home_user_tokens = {} + + if self.username and '' == self.token: + self.token = self.get_token(self.username, self.password) + + @property + def plex_host(self): + + if not self._plex_host.startswith('http'): + return 'http://%s' % self.plex_host + return self._plex_host + + @plex_host.setter + def plex_host(self, value): + + self._plex_host = value + + def log(self, msg, debug=True): + + try: + if self.use_logger: + msg = 'Plex:: ' + msg + if debug: + logger.log(msg, logger.DEBUG) + else: + logger.log(msg) + # else: + # print(msg.encode('ascii', 'replace').decode()) + except (StandardError, Exception): + pass + + def get_token(self, user, passw): + + auth = '' + try: + auth = getURL('https://plex.tv/users/sign_in.json', + headers={'X-Plex-Device-Name': 'SickGear', + 'X-Plex-Platform': platform.system(), 'X-Plex-Device': platform.system(), + 'X-Plex-Platform-Version': platform.release(), + 'X-Plex-Provides': 'Python', 'X-Plex-Product': 'Python', + 'X-Plex-Client-Identifier': self.client_id, + 'X-Plex-Version': str(self.config_version), + 'X-Plex-Username': user + }, + json=True, + data=urlencode({b'user[login]': user, b'user[password]': passw}).encode('utf-8') + )['user']['authentication_token'] + except IndexError: + self.log('Error getting Plex Token') + + return auth + + def get_access_token(self, token): + + resources = self.get_url_x('https://plex.tv/api/resources?includeHttps=1', token=token) + if None is resources: + return '' + + devices = resources.findall('Device') + for device in devices: + if 1 == len(devices) \ + or self.machine_client_identifier == device.get('clientIdentifier') \ + or (self.device_name + and (self.device_name.lower() in device.get('name').lower() + or self.device_name.lower() in device.get('clientIdentifier').lower()) + ): + access_token = device.get('accessToken') + if not access_token: + return '' + return access_token + + connections = device.findall('Connection') + for connection in connections: + if self.plex_host == connection.get('address'): + access_token = device.get('accessToken') + if not access_token: + return '' + uri = connection.get('uri') + match = re.compile('(http[s]?://.*?):(\d*)').match(uri) + if match: + self.plex_host = match.group(1) + self.plex_port = match.group(2) + return access_token + return '' + + def get_plex_home_user_tokens(self): + + user_tokens = {} + + # check Plex is contactable + home_users = self.get_url_x('https://plex.tv/api/home/users') + if None is not home_users: + for user in home_users.findall('User'): + user_id = user.get('id') + # use empty byte data to force POST + switch_page = self.get_url_x('https://plex.tv/api/home/users/%s/switch' % user_id, data=b'') + if None is not switch_page: + home_token = 'user' == switch_page.tag and switch_page.get('authenticationToken') + if home_token: + username = switch_page.get('title') + user_tokens[username] = self.get_access_token(home_token) + return user_tokens + + def get_url_x(self, url, token=None, **kwargs): + + if not token: + token = self.token + if not url.startswith('http'): + url = 'http://' + url + + for x in range(0, 3): + if 0 < x: + sleep(0.5) + try: + headers = {'X-Plex-Device-Name': 'SickGear', + 'X-Plex-Platform': platform.system(), 'X-Plex-Device': platform.system(), + 'X-Plex-Platform-Version': platform.release(), + 'X-Plex-Provides': 'controller', 'X-Plex-Product': 'Python', + 'X-Plex-Client-Identifier': self.client_id, + 'X-Plex-Version': str(self.config_version), + 'X-Plex-Token': token, + 'Accept': 'application/xml' + } + if self.username: + headers.update({'X-Plex-Username': self.username}) + page = getURL(url, headers=headers, **kwargs) + if page: + parsed = etree.fromstring(page) + if None is not parsed and len(parsed): + return parsed + return None + + except Exception as e: + self.log('Error requesting page: %s' % e) + continue + return None + + # uses the Plex API to delete files instead of system functions, useful for remote installations + def delete_file(self, media_id=0): + + try: + endpoint = ('/library/metadata/%s' % str(media_id)) + req = urllib2.Request('%s:%s%s' % (self.plex_host, self.plex_port, endpoint), + None, {'X-Plex-Token': self.token}) + req.get_method = lambda: 'DELETE' + urllib2.urlopen(req) + except (StandardError, Exception): + return False + return True + + @staticmethod + def get_media_info(video_node): + + progress = 0 + if None is not video_node.get('viewOffset') and None is not video_node.get('duration'): + progress = tryInt(video_node.get('viewOffset')) * 100 / tryInt(video_node.get('duration')) + + for media in video_node.findall('Media'): + for part in media.findall('Part'): + file_name = part.get('file') + # if '3' > sys.version: # remove HTML quoted characters, only works in python < 3 + # file_name = urllib2.unquote(file_name.encode('utf-8', errors='replace')) + # else: + file_name = urllib2.unquote(file_name) + + return {'path_file': file_name, 'media_id': video_node.get('ratingKey'), + 'played': int(video_node.get('viewCount') or 0), 'progress': progress} + + def check_users_watched(self, users, media_id): + + if not self.home_user_tokens: + self.home_user_tokens = self.get_plex_home_user_tokens() + + result = {} + if 'all' in users: + users = self.home_user_tokens.keys() + + for user in users: + user_media_page = self.get_url_pms('/library/metadata/%s' % media_id, token=self.home_user_tokens[user]) + if None is not user_media_page: + video_node = user_media_page.find('Video') + + progress = 0 + if None is not video_node.get('viewOffset') and None is not video_node.get('duration'): + progress = tryInt(video_node.get('viewOffset')) * 100 / tryInt(video_node.get('duration')) + + played = int(video_node.get('viewCount') or 0) + if not progress and not played: + continue + + date_watched = 0 + if (0 < tryInt(video_node.get('viewCount'))) or (0 < self.default_progress_as_watched < progress): + last_viewed_at = video_node.get('lastViewedAt') + if last_viewed_at and last_viewed_at not in ('', '0'): + date_watched = last_viewed_at + + if date_watched: + result[user] = dict(played=played, progress=progress, date_watched=date_watched) + else: + self.log('Do not have the token for %s.' % user) + + return result + + def get_url_pms(self, endpoint=None, **kwargs): + + return endpoint and self.get_url_x( + '%s:%s%s' % (self.plex_host, self.plex_port, endpoint), **kwargs) + + # parse episode information from season pages + def stat_show(self, node): + + episodes = [] + if 'directory' == node.tag.lower() and 'show' == node.get('type'): + show = self.get_url_pms(node.get('key')) + if None is show: # Check if show page is None or empty + self.log('Failed to load show page. Skipping...') + return None + + for season_node in show.findall('Directory'): # Each directory is a season + if 'season' != season_node.get('type'): # skips Specials + continue + + season_key = season_node.get('key') + season = self.get_url_pms(season_key) + if None is not season: + episodes += [season] + + elif 'mediacontainer' == node.tag.lower() and 'episode' == node.get('viewGroup'): + episodes = [node] + + check_users = [] + if self.default_home_users: + check_users = self.default_home_users.strip(' ,').lower().split(',') + for k in range(0, len(check_users)): # Remove extra spaces and commas + check_users[k] = check_users[k].strip(', ') + + for episode_node in episodes: + for video_node in episode_node.findall('Video'): + + media_info = self.get_media_info(video_node) + + if check_users: + user_info = self.check_users_watched(check_users, media_info['media_id']) + for user_name, user_media_info in user_info.items(): + self.show_states.update({len(self.show_states): dict( + path_file=media_info['path_file'], + media_id=media_info['media_id'], + played=(100 * user_media_info['played']) or user_media_info['progress'] or 0, + label=user_name, + date_watched=user_media_info['date_watched'])}) + else: + self.show_states.update({len(self.show_states): dict( + path_file=media_info['path_file'], + media_id=media_info['media_id'], + played=(100 * media_info['played']) or media_info['progress'] or 0, + label=self.username, + date_watched=video_node.get('lastViewedAt'))}) + + self.file_count += 1 + + return True + + def fetch_show_states(self, fetch_all=False): + + error_log = [] + self.show_states = {} + + server_check = self.get_url_pms('/') + if None is server_check or 'MediaContainer' != server_check.tag: + error_log.append('Cannot reach server!') + + else: + if not self.device_name: + self.device_name = server_check.get('friendlyName') + + if not self.machine_client_identifier: + self.machine_client_identifier = server_check.get('machineIdentifier') + + access_token = None + if self.token: + access_token = self.get_access_token(self.token) + if access_token: + self.token = access_token + if not self.home_user_tokens: + self.home_user_tokens = self.get_plex_home_user_tokens() + else: + error_log.append('Access Token not found') + + resp_sections = None + if None is access_token or len(access_token): + resp_sections = self.get_url_pms('/library/sections/') + + if None is not resp_sections: + + unpather = [] + for loc in self.section_filter_path: + loc = re.sub(r'[/\\]+', '/', loc.lower()) + loc = re.sub(r'^(.{,2})[/\\]', '', loc) + unpather.append(loc) + self.section_filter_path = unpather + + for section in resp_sections.findall('Directory'): + if 'show' != section.get('type') or not section.findall('Location'): + continue + + section_path = re.sub(r'[/\\]+', '/', section.find('Location').get('path').lower()) + section_path = re.sub(r'^(.{,2})[/\\]', '', section_path) + if not any([section_path in path for path in self.section_filter_path]): + continue + + if section.get('key') not in self.ignore_sections \ + and section.get('title') not in self.ignore_sections: + section_key = section.get('key') + + for (user, token) in (self.home_user_tokens or {'': None}).iteritems(): + self.username = user + + resp_section = self.get_url_pms('/library/sections/%s/%s' % ( + section_key, ('recentlyViewed', 'all')[fetch_all]), token=token) + if None is not resp_section: + view_group = 'MediaContainer' == resp_section.tag and \ + resp_section.get('viewGroup') or '' + if 'show' == view_group and fetch_all: + for DirectoryNode in resp_section.findall('Directory'): + self.stat_show(DirectoryNode) + elif 'episode' == view_group and not fetch_all: + self.stat_show(resp_section) + + if 0 < len(error_log): + self.log('Library errors...') + for item in error_log: + self.log(item) + + return 0 < len(error_log) diff --git a/readme.md b/readme.md index d1c6c09..88d46c3 100644 --- a/readme.md +++ b/readme.md @@ -1,57 +1,76 @@
SickGear
-**SickGear**, a usenet and bittorrent PVR +*SickGear*, a usenet and bittorrent PVR
-_Please note you should know how to use git and setup basic requirements in order to run this software._ -SickGear provides management of TV shows and/or Anime, it can detect new episodes, link to downloader apps, and more. SickGear is a proud descendant of Sick Beard and is humbled to have been endorsed by one of its former lead developers. +SickGear provides management of TV shows and/or Anime, it detects new episodes, links downloader apps, and more. -Why SickGear? -* SickGear maintains perfect uptime with the longest track record of being stable, reliable and trusted to work -* SickGear delivers quality from active development with a wealth of options on a dark or light themed interface +#### Why SickGear? +* SickGear maintains a perfect uptime with the longest track record of being stable, reliable and trusted to work +* SickGear delivers valued quality from active development with a wealth of options on a dark or light themed interface + +#### What now? +* [Install guides](https://github.com/SickGear/SickGear/wiki/Installation-Instructions) for many platforms * [Migrating](https://github.com/SickGear/SickGear/wiki/Install-SickGear-%5B0%5D-Migrate) to a hassle free and feature rich set up is super simple -## Features include +Or read more below... + +## Some innovative SickGear features +* Ideas of shows to add from Trakt, IMDb, and AniDB categories; anticipating, new seasons, new shows, popular, and more +* Advanced add show finder that near always returns results sorted A-Z, Aired, or Relevancy, with known shows separated +* Releases can be searched during adding a show (e.g. optionally fetch oldest and/or newest without further effort) +* Advanced automated search that always works to prevent you wasting time manually scanning result lists +* Choose to delete watched episodes from a list built directly from played media at Kodi, Emby, and/or Plex (No Trakt!) +* Smart custom qualities selector system that helps achieve an optimal quality selection for automated episode search +* Choose to have episodes upgraded in quality, or keep existing archive quality, and upgrade future episodes either way +* Natively use a most powerful regex pattern matching system for superior information handling +* Select a UI style anytime; Regular, Proview I, or Proview II - independently for Episode View, and for Display Show +* Smart fanart system allows you to rate avoid/prefer. UI can be moved or toggled off/on to fully appreciate a fanart +* Episode View Layout "Day by Day" displays a fanart background from randomly selected imminent releases +* Configure from 0 to 500 fanart images to cache per show, default is 3. +* Provider server failure charts display what failed, when and why +* Provider server failure handler that pauses connecting the more a server fails +* Provider server activity graph and stats display how each are performing +* Built-in providers that have proved over time to deliver leading durability among its application class and third parties +* Built-in Kodi repository service to maintain SickGear add-ons, the first add-on is Watched State Updater +* Separate Plex server and Plex client settings, multiple LAN Plex server support, and Plex Home multiple user support +* Intelligent library updates target the actual Plex server that carries the show of an episode (multi LAN server) +* Communicate directly with NZBGet using a dedicated integration script +* Communicate directly with qBittorrent/Deluge/Transmission etc. using a dedicated integration script +* Proxy auto-config (PAC) support to define when a proxy is used instead of using one for every system request +* Change file date, to the date that the episode aired (yup, the feature was first created here for XBMC file sorting) +* Visual percentage progress of managed episodes +* Configure an episode status for removed media files +* Configurable default home page + +Features above link to the UI; innovations also exist in core, we often inspire imitators, but you can [get the real deal!](https://github.com/SickGear/SickGear/wiki/Installation-Instructions) + +Other features and worthy points; * Stable, quality assured testing and development cycle -* Innovations that inspire imitators -* Compatible with any platform via a familiar web interface * Most comprehensive selection of usenet and torrent sources +* Compatible with any platform via a familiar web interface * Episode management + * Group shows into personalised sections * View missed and upcoming shows at a glance with "day by day" and other layouts - * Group shows into personalised sections in a full show list view - * Automatic and manual search for availability of wanted episodes - * Set what episodes you want and how to receive them - * Uses well known established index sites to gather show information - * Searches for known alternatively named shows with a fallback to user edited names - * Searches for known alternatively numbered episodes with a fallback to user edited numbers - * Searches for known alternatively numbered seasons with a fallback to user edited numbers - * Forward search results to a downloader (e.g. NZBGet, SABNZBd, uTorrent, and others) - * Save search results to a "blackhole" folder that can be periodically scanned for taking action - * Post-process downloaded episodes into customisable layouts, with or without extra metadata - * Advanced Failed Download Handling (FDH) - * Overview of seasons, episodes, rating, version, airdate, episode status ([their meaning](https://github.com/SickGear/SickGear/wiki/Status-Modes)) -* Processing nzb/torrents with your downloader application at your chosen qualities -* Subtitle management + * Automatic and manual search for availability of episodes you want + * Well known established sources are used to gather reliable show information + * Known and user added alternative show names can be searched + * Known and user added alternative numbered seasons and/or episodes can be searched + * Forward search results directly to clients like NZBGet, SABNZBd, qBitTorrent, Deluge and others + * Save search results to a "blackhole" folder, a place designated for clients to auto scan + * Built-in post processing of episodes, with renaming to custom folder and/or file names + * Fetch metadata like fanart, poster and banner images, nfo's for clients like Kodi, Plex and many more + * Native advanced automated handling of failed downloads to ensure a success after failure + * Overview of episodes, rating, version, airdate, episode status ([their meaning](https://github.com/SickGear/SickGear/wiki/Status-Modes)) + * Support for specials and multi episode media files +* Automated subtitle management * Notification - * Home Theater/NAS (Emby, Kodi, Plex, Syno, Tivo, and more) + * Home Theater/NAS (Emby, Kodi, Plex, Syno, Tivo, and more) can be notified to update their library * Social notifiers (Trakt, Slack, Gitter, Discord, E-mail, and more) * Device notifiers (Boxcar2, Notify My Android, Growl, Prowl, and more) -* Server friendly with minimal number of calls (e.g. one request per chosen snatch, not per result) -* Can recommend trendy and/or personally tailored shows from Trakt, IMDb, AniDB +* Server friendly with minimal number of API calls using both active and passive search tech * Automated alternative show names and episode numbering from XEM -Some of our innovative features; -* Automated search after adding a show -* Desktop notifications -* Enhanced Anime features when adding shows -* Visual percentage progress of managed episodes -* Separate Plex server and Plex client settings -* Intelligent library updates that target Plex servers that list the show of an episode -* Configurable episode status for removed media files -* Configurable default home page -* Source providers -* User Interface - ## Screenies @@ -103,15 +122,15 @@ If your pull request is a new feature, please try explaining its function to a l ## Contributors #### To core -MidgetSpy, zoggy, 1337, Tolstyak, Mr_Orange, Bricky, JackDandy, Prinz23, Supremicus, adam111316, and zanaga +MidgetSpy, zoggy, 1337, Tolstyak, Mr_Orange, Bricky, JackDandy, Prinz23, Supremicus, adam111316, and zanaga #### In other areas, testers and QA -Warm thanks to tehspede, CtrlAltDefeat, Mike, vergessen (betrayed), and Rawh for their keen eye, all around help, and making sure all manner of things work as expected +Warm thanks to tehspede, CtrlAltDefeat, Mike, vergessen (betrayed), and Rawh for their keen eye, all around help, and making sure all manner of things work as expected #### Provider code -Thanks also, to unsung heroes that added source providers; Idan Gutman, Daniel Heimans, jkaberg, and Seedboy +Thanks also, to unsung heroes that added source providers; Idan Gutman, Daniel Heimans, jkaberg, and Seedboy -Finally, a massive thanks to all those that remain in the shadows, the quiet ones who welcome folk to special places, we salute you for your hospitality and for tirelessly keeping up operations. +Finally, a massive thanks to all those that remain in the shadows, the quiet ones who welcome folk to special places, we salute you for your hospitality and for tirelessly keeping up operations. ## Community * web based (most likely one on one with a dev) diff --git a/sickbeard/__init__.py b/sickbeard/__init__.py index 505704d..8897e94 100755 --- a/sickbeard/__init__.py +++ b/sickbeard/__init__.py @@ -37,12 +37,14 @@ sys.path.insert(1, os.path.abspath('../lib')) from sickbeard import helpers, encodingKludge as ek from sickbeard import db, image_cache, logger, naming, metadata, providers, scene_exceptions, scene_numbering, \ scheduler, auto_post_processer, search_queue, search_propers, search_recent, search_backlog, \ - show_queue, show_updater, subtitles, traktChecker, version_checker, indexermapper, classes, properFinder -from sickbeard.config import CheckSection, check_setting_int, check_setting_str, ConfigMigrator, minimax + show_queue, show_updater, subtitles, traktChecker, version_checker, indexermapper, classes, properFinder, \ + watchedstate_queue +from sickbeard.config import check_section, check_setting_int, check_setting_str, ConfigMigrator, minimax from sickbeard.common import SD, SKIPPED from sickbeard.databases import mainDB, cache_db, failed_db from sickbeard.exceptions import ex from sickbeard.providers.generic import GenericProvider +from sickbeard.watchedstate import EmbyWatchedStateUpdater, PlexWatchedStateUpdater from indexers.indexer_config import INDEXER_TVDB from indexers.indexer_api import indexerApi from indexers.indexer_exceptions import indexer_shownotfound, indexer_exception, indexer_error, \ @@ -85,6 +87,9 @@ autoPostProcesserScheduler = None subtitlesFinderScheduler = None # traktCheckerScheduler = None background_mapping_task = None +embyWatchedStateScheduler = None +plexWatchedStateScheduler = None +watchedStateQueueScheduler = None provider_ping_thread_pool = {} @@ -226,12 +231,15 @@ DEFAULT_AUTOPOSTPROCESSER_FREQUENCY = 10 DEFAULT_RECENTSEARCH_FREQUENCY = 40 DEFAULT_BACKLOG_FREQUENCY = 21 DEFAULT_UPDATE_FREQUENCY = 1 +DEFAULT_WATCHEDSTATE_FREQUENCY = 10 MIN_AUTOPOSTPROCESSER_FREQUENCY = 1 MIN_RECENTSEARCH_FREQUENCY = 10 MIN_BACKLOG_FREQUENCY = 7 MAX_BACKLOG_FREQUENCY = 42 MIN_UPDATE_FREQUENCY = 1 +MIN_WATCHEDSTATE_FREQUENCY = 10 +MAX_WATCHEDSTATE_FREQUENCY = 60 BACKLOG_DAYS = 7 SEARCH_UNAIRED = False @@ -257,6 +265,7 @@ NZBGET_CATEGORY = None NZBGET_HOST = None NZBGET_USE_HTTPS = False NZBGET_PRIORITY = 100 +NZBGET_SCRIPT_VERSION = None SAB_USERNAME = None SAB_PASSWORD = None @@ -276,8 +285,11 @@ TORRENT_VERIFY_CERT = False USE_EMBY = False EMBY_UPDATE_LIBRARY = False +EMBY_PARENT_MAPS = None EMBY_HOST = None EMBY_APIKEY = None +EMBY_WATCHEDSTATE_SCHEDULED = False +EMBY_WATCHEDSTATE_FREQUENCY = None USE_KODI = False KODI_ALWAYS_ON = True @@ -287,6 +299,7 @@ KODI_NOTIFY_ONSUBTITLEDOWNLOAD = False KODI_UPDATE_LIBRARY = False KODI_UPDATE_FULL = False KODI_UPDATE_ONLYFIRST = False +KODI_PARENT_MAPS = None KODI_HOST = '' KODI_USERNAME = None KODI_PASSWORD = None @@ -296,10 +309,13 @@ PLEX_NOTIFY_ONSNATCH = False PLEX_NOTIFY_ONDOWNLOAD = False PLEX_NOTIFY_ONSUBTITLEDOWNLOAD = False PLEX_UPDATE_LIBRARY = False +PLEX_PARENT_MAPS = None PLEX_SERVER_HOST = None PLEX_HOST = None PLEX_USERNAME = None PLEX_PASSWORD = None +PLEX_WATCHEDSTATE_SCHEDULED = False +PLEX_WATCHEDSTATE_FREQUENCY = None USE_XBMC = False XBMC_ALWAYS_ON = True @@ -565,8 +581,10 @@ def initialize(console_logging=True): # global traktCheckerScheduler global recentSearchScheduler, backlogSearchScheduler, showUpdateScheduler, \ versionCheckScheduler, showQueueScheduler, searchQueueScheduler, \ - properFinderScheduler, autoPostProcesserScheduler, subtitlesFinderScheduler, background_mapping_task, \ - provider_ping_thread_pool + properFinderScheduler, autoPostProcesserScheduler, subtitlesFinderScheduler, \ + background_mapping_task, provider_ping_thread_pool, \ + embyWatchedStateScheduler, plexWatchedStateScheduler, watchedStateQueueScheduler, \ + MIN_WATCHEDSTATE_FREQUENCY, MAX_WATCHEDSTATE_FREQUENCY, DEFAULT_WATCHEDSTATE_FREQUENCY # Add Show Search global RESULTS_SORTBY # Add Show Defaults @@ -600,7 +618,8 @@ def initialize(console_logging=True): ALLOW_HIGH_PRIORITY, SEARCH_UNAIRED, UNAIRED_RECENT_SEARCH_ONLY # Search Settings/NZB search global USE_NZBS, NZB_METHOD, NZB_DIR, SAB_HOST, SAB_USERNAME, SAB_PASSWORD, SAB_APIKEY, SAB_CATEGORY, \ - NZBGET_USE_HTTPS, NZBGET_HOST, NZBGET_USERNAME, NZBGET_PASSWORD, NZBGET_CATEGORY, NZBGET_PRIORITY + NZBGET_USE_HTTPS, NZBGET_HOST, NZBGET_USERNAME, NZBGET_PASSWORD, NZBGET_CATEGORY, NZBGET_PRIORITY, \ + NZBGET_SCRIPT_VERSION # Search Settings/Torrent search global USE_TORRENTS, TORRENT_METHOD, TORRENT_DIR, TORRENT_HOST, TORRENT_USERNAME, TORRENT_PASSWORD, \ TORRENT_LABEL, TORRENT_PATH, TORRENT_SEED_TIME, TORRENT_PAUSED, TORRENT_HIGH_BANDWIDTH, TORRENT_VERIFY_CERT @@ -623,14 +642,16 @@ def initialize(console_logging=True): global metadata_provider_dict, METADATA_KODI, METADATA_MEDE8ER, METADATA_XBMC, METADATA_MEDIABROWSER, \ METADATA_PS3, METADATA_TIVO, METADATA_WDTV, METADATA_XBMC_12PLUS # Notification Settings/HT and NAS - global USE_EMBY, EMBY_UPDATE_LIBRARY, EMBY_HOST, EMBY_APIKEY, \ + global USE_EMBY, EMBY_UPDATE_LIBRARY, EMBY_PARENT_MAPS, EMBY_HOST, EMBY_APIKEY, \ + EMBY_WATCHEDSTATE_SCHEDULED, EMBY_WATCHEDSTATE_FREQUENCY, \ USE_KODI, KODI_ALWAYS_ON, KODI_UPDATE_LIBRARY, KODI_UPDATE_FULL, KODI_UPDATE_ONLYFIRST, \ - KODI_HOST, KODI_USERNAME, KODI_PASSWORD, KODI_NOTIFY_ONSNATCH, \ + KODI_PARENT_MAPS, KODI_HOST, KODI_USERNAME, KODI_PASSWORD, KODI_NOTIFY_ONSNATCH, \ KODI_NOTIFY_ONDOWNLOAD, KODI_NOTIFY_ONSUBTITLEDOWNLOAD, \ USE_XBMC, XBMC_ALWAYS_ON, XBMC_NOTIFY_ONSNATCH, XBMC_NOTIFY_ONDOWNLOAD, XBMC_NOTIFY_ONSUBTITLEDOWNLOAD, \ XBMC_UPDATE_LIBRARY, XBMC_UPDATE_FULL, XBMC_UPDATE_ONLYFIRST, XBMC_HOST, XBMC_USERNAME, XBMC_PASSWORD, \ - USE_PLEX, PLEX_USERNAME, PLEX_PASSWORD, PLEX_UPDATE_LIBRARY, PLEX_SERVER_HOST, \ + USE_PLEX, PLEX_USERNAME, PLEX_PASSWORD, PLEX_UPDATE_LIBRARY, PLEX_PARENT_MAPS, PLEX_SERVER_HOST, \ PLEX_NOTIFY_ONSNATCH, PLEX_NOTIFY_ONDOWNLOAD, PLEX_NOTIFY_ONSUBTITLEDOWNLOAD, PLEX_HOST, \ + PLEX_WATCHEDSTATE_SCHEDULED, PLEX_WATCHEDSTATE_FREQUENCY, \ USE_NMJ, NMJ_HOST, NMJ_DATABASE, NMJ_MOUNT, \ USE_NMJv2, NMJv2_HOST, NMJv2_DATABASE, NMJv2_DBLOC, \ USE_SYNOINDEX, \ @@ -678,7 +699,7 @@ def initialize(console_logging=True): 'Growl', 'Prowl', 'Twitter', 'Slack', 'Discordapp', 'Boxcar2', 'NMJ', 'NMJv2', 'Synology', 'SynologyNotifier', 'pyTivo', 'NMA', 'Pushalot', 'Pushbullet', 'Subtitles'): - CheckSection(CFG, stanza) + check_section(CFG, stanza) update_config = False @@ -908,6 +929,15 @@ def initialize(console_logging=True): NZBGET_USE_HTTPS = bool(check_setting_int(CFG, 'NZBget', 'nzbget_use_https', 0)) NZBGET_PRIORITY = check_setting_int(CFG, 'NZBget', 'nzbget_priority', 100) + try: + ng_script_file = ek.ek(os.path.join, ek.ek(os.path.dirname, ek.ek(os.path.dirname, __file__)), + 'autoProcessTV', 'SickGear-NG', 'SickGear-NG.py') + with open(ng_script_file, 'r') as ng: + text = ng.read() + NZBGET_SCRIPT_VERSION = re.search(r'__version__ =.*\'([0-9.]+)\'.*$', text, flags=re.M).group(1) + except (StandardError, Exception): + NZBGET_SCRIPT_VERSION = None + TORRENT_USERNAME = check_setting_str(CFG, 'TORRENT', 'torrent_username', '') TORRENT_PASSWORD = check_setting_str(CFG, 'TORRENT', 'torrent_password', '') TORRENT_HOST = check_setting_str(CFG, 'TORRENT', 'torrent_host', '') @@ -920,8 +950,13 @@ def initialize(console_logging=True): USE_EMBY = bool(check_setting_int(CFG, 'Emby', 'use_emby', 0)) EMBY_UPDATE_LIBRARY = bool(check_setting_int(CFG, 'Emby', 'emby_update_library', 0)) + EMBY_PARENT_MAPS = check_setting_str(CFG, 'Emby', 'emby_parent_maps', '') EMBY_HOST = check_setting_str(CFG, 'Emby', 'emby_host', '') EMBY_APIKEY = check_setting_str(CFG, 'Emby', 'emby_apikey', '') + EMBY_WATCHEDSTATE_SCHEDULED = bool(check_setting_int(CFG, 'Emby', 'emby_watchedstate_scheduled', 0)) + EMBY_WATCHEDSTATE_FREQUENCY = minimax(check_setting_int( + CFG, 'Emby', 'emby_watchedstate_frequency', DEFAULT_WATCHEDSTATE_FREQUENCY), + DEFAULT_WATCHEDSTATE_FREQUENCY, MIN_WATCHEDSTATE_FREQUENCY, MAX_WATCHEDSTATE_FREQUENCY) USE_KODI = bool(check_setting_int(CFG, 'Kodi', 'use_kodi', 0)) KODI_ALWAYS_ON = bool(check_setting_int(CFG, 'Kodi', 'kodi_always_on', 1)) @@ -931,6 +966,7 @@ def initialize(console_logging=True): KODI_UPDATE_LIBRARY = bool(check_setting_int(CFG, 'Kodi', 'kodi_update_library', 0)) KODI_UPDATE_FULL = bool(check_setting_int(CFG, 'Kodi', 'kodi_update_full', 0)) KODI_UPDATE_ONLYFIRST = bool(check_setting_int(CFG, 'Kodi', 'kodi_update_onlyfirst', 0)) + KODI_PARENT_MAPS = check_setting_str(CFG, 'Kodi', 'kodi_parent_maps', '') KODI_HOST = check_setting_str(CFG, 'Kodi', 'kodi_host', '') KODI_USERNAME = check_setting_str(CFG, 'Kodi', 'kodi_username', '') KODI_PASSWORD = check_setting_str(CFG, 'Kodi', 'kodi_password', '') @@ -952,10 +988,15 @@ def initialize(console_logging=True): PLEX_NOTIFY_ONDOWNLOAD = bool(check_setting_int(CFG, 'Plex', 'plex_notify_ondownload', 0)) PLEX_NOTIFY_ONSUBTITLEDOWNLOAD = bool(check_setting_int(CFG, 'Plex', 'plex_notify_onsubtitledownload', 0)) PLEX_UPDATE_LIBRARY = bool(check_setting_int(CFG, 'Plex', 'plex_update_library', 0)) + PLEX_PARENT_MAPS = check_setting_str(CFG, 'Plex', 'plex_parent_maps', '') PLEX_SERVER_HOST = check_setting_str(CFG, 'Plex', 'plex_server_host', '') PLEX_HOST = check_setting_str(CFG, 'Plex', 'plex_host', '') PLEX_USERNAME = check_setting_str(CFG, 'Plex', 'plex_username', '') PLEX_PASSWORD = check_setting_str(CFG, 'Plex', 'plex_password', '') + PLEX_WATCHEDSTATE_SCHEDULED = bool(check_setting_int(CFG, 'Plex', 'plex_watchedstate_scheduled', 0)) + PLEX_WATCHEDSTATE_FREQUENCY = minimax(check_setting_int( + CFG, 'Plex', 'plex_watchedstate_frequency', DEFAULT_WATCHEDSTATE_FREQUENCY), + DEFAULT_WATCHEDSTATE_FREQUENCY, MIN_WATCHEDSTATE_FREQUENCY, MAX_WATCHEDSTATE_FREQUENCY) USE_GROWL = bool(check_setting_int(CFG, 'Growl', 'use_growl', 0)) GROWL_NOTIFY_ONSNATCH = bool(check_setting_int(CFG, 'Growl', 'growl_notify_onsnatch', 0)) @@ -1038,7 +1079,6 @@ def initialize(console_logging=True): TRAKT_ACCOUNTS = TraktAPI.read_config_string(check_setting_str(CFG, 'Trakt', 'trakt_accounts', '')) TRAKT_MRU = check_setting_str(CFG, 'Trakt', 'trakt_mru', '') - CheckSection(CFG, 'pyTivo') USE_PYTIVO = bool(check_setting_int(CFG, 'pyTivo', 'use_pytivo', 0)) PYTIVO_HOST = check_setting_str(CFG, 'pyTivo', 'pytivo_host', '') PYTIVO_SHARE_NAME = check_setting_str(CFG, 'pyTivo', 'pytivo_share_name', '') @@ -1341,7 +1381,8 @@ def initialize(console_logging=True): cycleTime=datetime.timedelta(seconds=3), threadName='SEARCHQUEUE') - update_interval = datetime.timedelta(minutes=(RECENTSEARCH_FREQUENCY, 1)[4489 == RECENTSEARCH_FREQUENCY]) + # enter 4490 (was 4489) for experimental internal provider frequencies + update_interval = datetime.timedelta(minutes=(RECENTSEARCH_FREQUENCY, 1)[4499 == RECENTSEARCH_FREQUENCY]) recentSearchScheduler = scheduler.Scheduler( search_recent.RecentSearcher(), cycleTime=update_interval, @@ -1407,6 +1448,23 @@ def initialize(console_logging=True): background_mapping_task = threading.Thread(name='LOAD-MAPPINGS', target=indexermapper.load_mapped_ids) + watchedStateQueueScheduler = scheduler.Scheduler( + watchedstate_queue.WatchedStateQueue(), + cycleTime=datetime.timedelta(seconds=3), + threadName='WATCHEDSTATEQUEUE') + + embyWatchedStateScheduler = scheduler.Scheduler( + EmbyWatchedStateUpdater(), + cycleTime=datetime.timedelta(minutes=EMBY_WATCHEDSTATE_FREQUENCY), + run_delay=datetime.timedelta(minutes=5), + threadName='EMBYWATCHEDSTATE') + + plexWatchedStateScheduler = scheduler.Scheduler( + PlexWatchedStateUpdater(), + cycleTime=datetime.timedelta(minutes=PLEX_WATCHEDSTATE_FREQUENCY), + run_delay=datetime.timedelta(minutes=5), + threadName='PLEXWATCHEDSTATE') + __INITIALIZED__ = True return True @@ -1416,7 +1474,8 @@ def enabled_schedulers(is_init=False): for s in ([], [events])[is_init] + \ [recentSearchScheduler, backlogSearchScheduler, showUpdateScheduler, versionCheckScheduler, showQueueScheduler, searchQueueScheduler, properFinderScheduler, - autoPostProcesserScheduler, subtitlesFinderScheduler] + \ + autoPostProcesserScheduler, subtitlesFinderScheduler, + embyWatchedStateScheduler, plexWatchedStateScheduler, watchedStateQueueScheduler] + \ ([events], [])[is_init]: yield s @@ -1724,8 +1783,11 @@ def save_config(): new_config['Emby'] = {} new_config['Emby']['use_emby'] = int(USE_EMBY) new_config['Emby']['emby_update_library'] = int(EMBY_UPDATE_LIBRARY) + new_config['Emby']['emby_parent_maps'] = EMBY_PARENT_MAPS new_config['Emby']['emby_host'] = EMBY_HOST new_config['Emby']['emby_apikey'] = EMBY_APIKEY + new_config['Emby']['emby_watchedstate_scheduled'] = int(EMBY_WATCHEDSTATE_SCHEDULED) + new_config['Emby']['emby_watchedstate_frequency'] = int(EMBY_WATCHEDSTATE_FREQUENCY) new_config['Kodi'] = {} new_config['Kodi']['use_kodi'] = int(USE_KODI) @@ -1733,6 +1795,7 @@ def save_config(): new_config['Kodi']['kodi_update_library'] = int(KODI_UPDATE_LIBRARY) new_config['Kodi']['kodi_update_full'] = int(KODI_UPDATE_FULL) new_config['Kodi']['kodi_update_onlyfirst'] = int(KODI_UPDATE_ONLYFIRST) + new_config['Kodi']['kodi_parent_maps'] = KODI_PARENT_MAPS new_config['Kodi']['kodi_host'] = KODI_HOST new_config['Kodi']['kodi_username'] = KODI_USERNAME new_config['Kodi']['kodi_password'] = helpers.encrypt(KODI_PASSWORD, ENCRYPTION_VERSION) @@ -1745,11 +1808,14 @@ def save_config(): new_config['Plex']['plex_username'] = PLEX_USERNAME new_config['Plex']['plex_password'] = helpers.encrypt(PLEX_PASSWORD, ENCRYPTION_VERSION) new_config['Plex']['plex_update_library'] = int(PLEX_UPDATE_LIBRARY) + new_config['Plex']['plex_parent_maps'] = PLEX_PARENT_MAPS new_config['Plex']['plex_server_host'] = PLEX_SERVER_HOST new_config['Plex']['plex_notify_onsnatch'] = int(PLEX_NOTIFY_ONSNATCH) new_config['Plex']['plex_notify_ondownload'] = int(PLEX_NOTIFY_ONDOWNLOAD) new_config['Plex']['plex_notify_onsubtitledownload'] = int(PLEX_NOTIFY_ONSUBTITLEDOWNLOAD) new_config['Plex']['plex_host'] = PLEX_HOST + new_config['Plex']['plex_watchedstate_scheduled'] = int(PLEX_WATCHEDSTATE_SCHEDULED) + new_config['Plex']['plex_watchedstate_frequency'] = int(PLEX_WATCHEDSTATE_FREQUENCY) new_config['XBMC'] = {} new_config['XBMC']['use_xbmc'] = int(USE_XBMC) diff --git a/sickbeard/auto_post_processer.py b/sickbeard/auto_post_processer.py index 90bec25..541ca69 100644 --- a/sickbeard/auto_post_processer.py +++ b/sickbeard/auto_post_processer.py @@ -23,21 +23,22 @@ from sickbeard import logger, processTV from sickbeard import encodingKludge as ek -class PostProcesser(): +class PostProcesser: def __init__(self): self.amActive = False @staticmethod - def check_paused(): - if sickbeard.PROCESS_AUTOMATICALLY: - return False - return True + def is_enabled(): + return sickbeard.PROCESS_AUTOMATICALLY def run(self): - if not sickbeard.PROCESS_AUTOMATICALLY: - return + if self.is_enabled(): + self.amActive = True + self._main() + self.amActive = False - self.amActive = True + @staticmethod + def _main(): if not ek.ek(os.path.isdir, sickbeard.TV_DOWNLOAD_DIR): logger.log(u"Automatic post-processing attempted but dir %s doesn't exist" % sickbeard.TV_DOWNLOAD_DIR, @@ -50,5 +51,3 @@ class PostProcesser(): return processTV.processDir(sickbeard.TV_DOWNLOAD_DIR, is_basedir=True) - - self.amActive = False diff --git a/sickbeard/classes.py b/sickbeard/classes.py index 0102b76..aef64b9 100644 --- a/sickbeard/classes.py +++ b/sickbeard/classes.py @@ -17,6 +17,7 @@ # along with SickGear. If not, see . import re import datetime +import os import sickbeard from sickbeard.common import Quality @@ -379,3 +380,48 @@ class ImageUrlList(list): if self._is_cache_item(x) and url == x[0]: super(ImageUrlList, self).remove(x) break + + +if 'nt' == os.name: + import ctypes + + class WinEnv: + def __init__(self): + pass + + @staticmethod + def get_environment_variable(name): + name = unicode(name) # ensures string argument is unicode + n = ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0) + result = None + if n: + buf = ctypes.create_unicode_buffer(u'\0'*n) + ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n) + result = buf.value + return result + + def __getitem__(self, key): + return self.get_environment_variable(key) + + def get(self, key, default=None): + r = self.get_environment_variable(key) + return r if r is not None else default + + sickbeard.ENV = WinEnv() +else: + class LinuxEnv(object): + def __init__(self, environ): + self.environ = environ + + def __getitem__(self, key): + v = self.environ.get(key) + try: + return v.decode(SYS_ENCODING) if isinstance(v, str) else v + except (UnicodeDecodeError, UnicodeEncodeError): + return v + + def get(self, key, default=None): + v = self[key] + return v if v is not None else default + + sickbeard.ENV = LinuxEnv(os.environ) diff --git a/sickbeard/clients/kodi/repository.sickgear/icon.png b/sickbeard/clients/kodi/repository.sickgear/icon.png new file mode 100644 index 0000000..5119217 Binary files /dev/null and b/sickbeard/clients/kodi/repository.sickgear/icon.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/_devenv.py b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/_devenv.py new file mode 100644 index 0000000..1312da3 --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/_devenv.py @@ -0,0 +1,22 @@ +# /tests/_devenv.py +# +# To trigger dev env +# +# import _devenv as devenv +# + +__remotedebug__ = True + +if __remotedebug__: + import sys + sys.path.append('C:\Program Files\JetBrains\PyCharm 2017.2.1\debug-eggs\pycharm-debug.egg') + import pydevd + + + def setup_devenv(state): + pydevd.settrace('localhost', port=(65001, 65000)[bool(state)], stdoutToServer=True, stderrToServer=True, + suspend=False) + + +def stop(): + pydevd.stoptrace() diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/addon.xml b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/addon.xml new file mode 100644 index 0000000..03de50a --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/addon.xml @@ -0,0 +1,35 @@ + + + + + + + + + + executable + + + SickGear Watched State Updater + This Add-on notifies SickGear when an episode watched state is changed in Kodi + all + en + + + + https://github.com/sickgear/sickgear + + true + https://github.com/sickgear/sickgear + + icon.png + + [B]1.0.0[/B] (2017-10-04) +- Initial release +[B]1.0.2[/B] (2017-11-15) +- Devel release for an SG API change +[B]1.0.3[/B] (2018-02-28) +- Add episodeid to payload + + + diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/changelog.txt b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/changelog.txt new file mode 100644 index 0000000..71e2443 --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/changelog.txt @@ -0,0 +1,2 @@ +[B]1.0.0[/B] (2017-10-04) +- Initial release diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/fanart.jpg b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/fanart.jpg new file mode 100644 index 0000000..ecc2e15 Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/fanart.jpg differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/icon.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/icon.png new file mode 100644 index 0000000..1039156 Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/icon.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black-sm.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black-sm.png new file mode 100644 index 0000000..fcdeae9 Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black-sm.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black.png new file mode 100644 index 0000000..7eaa3a1 Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-black.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green-sm.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green-sm.png new file mode 100644 index 0000000..87992ad Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green-sm.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green.png new file mode 100644 index 0000000..f8e09db Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-green.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red-sm.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red-sm.png new file mode 100644 index 0000000..3ead34d Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red-sm.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red.png b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red.png new file mode 100644 index 0000000..a5c5c48 Binary files /dev/null and b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/icon-red.png differ diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/language/English/strings.xml b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/language/English/strings.xml new file mode 100644 index 0000000..0418502 --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/language/English/strings.xml @@ -0,0 +1,18 @@ + + + General + Action Notifications + Error Notifications + Verbose Logs + + Servers + SickGear IP + SickGear Port + Kodi IP + Kodi JSON RPC Port + + The following required Kodi settings should already be enabled: + At "System / Service(s) settings / Control (aka Remote control)" + * Allow remote control from/by applications/programs on this system + * Allow remote control from/by applications/programs on other systems + diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/settings.xml b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/settings.xml new file mode 100644 index 0000000..ab52330 --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/resources/settings.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/service.py b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/service.py new file mode 100644 index 0000000..534fb14 --- /dev/null +++ b/sickbeard/clients/kodi/service.sickgear.watchedstate.updater/service.py @@ -0,0 +1,361 @@ +# coding=utf-8 +# +# This file is part of SickGear. +# +# SickGear is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# SickGear is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with SickGear. If not, see . + +try: + import json as json +except (StandardError, Exception): + import simplejson as json +from os import path, sep +import datetime +import socket +import time +import traceback +import urllib +import urllib2 +import xbmc +import xbmcaddon +import xbmcgui +import xbmcvfs + + +class SickGearWatchedStateUpdater: + + def __init__(self): + self.wait_onstartup = 4000 + + icon_size = '%s' + try: + if 1350 > xbmcgui.Window.getWidth(xbmcgui.Window()): + icon_size += '-sm' + except (StandardError, Exception): + pass + icon = 'special://home/addons/service.sickgear.watchedstate.updater/resources/icon-%s.png' % icon_size + + self.addon = xbmcaddon.Addon() + self.red_logo = icon % 'red' + self.green_logo = icon % 'green' + self.black_logo = icon % 'black' + self.addon_name = self.addon.getAddonInfo('name') + self.kodi_ip = self.addon.getSetting('kodi_ip') + self.kodi_port = int(self.addon.getSetting('kodi_port')) + + self.kodi_events = None + self.sock_kodi = None + + def run(self): + """ + Main start + + :return: + :rtype: + """ + + if not self.enable_kodi_allow_remote(): + return + + self.sock_kodi = socket.socket() + self.sock_kodi.setblocking(True) + xbmc.sleep(self.wait_onstartup) + try: + self.sock_kodi.connect((self.kodi_ip, self.kodi_port)) + except (StandardError, Exception) as e: + return self.report_contact_fail(e) + + self.log('Started') + self.notify('Started in background') + + self.kodi_events = xbmc.Monitor() + + sock_buffer, depth, methods, method = '', 0, {'VideoLibrary.OnUpdate': self.video_library_on_update}, None + + # socks listener parsing Kodi json output into action to perform + while not self.kodi_events.abortRequested(): + chunk = self.sock_kodi.recv(1) + sock_buffer += chunk + if chunk in '{}': + if '{' == chunk: + depth += 1 + else: + depth -= 1 + if not depth: + json_msg = json.loads(sock_buffer) + try: + method = json_msg.get('method') + method_handler = methods[method] + method_handler(json_msg) + except KeyError: + if 'System.OnQuit' == method: + break + if __dev__: + self.log('pass on event: %s' % json_msg.get('method')) + + sock_buffer = '' + + self.sock_kodi.close() + del self.kodi_events + self.log('Stopped') + + def is_enabled(self, name): + """ + Return state of an Add-on setting as Boolean + + :param name: Name of Addon setting + :type name: String + :return: Success as True if addon setting is enabled, else False + :rtype: Bool + """ + return 'true' == self.addon.getSetting(name) + + def log(self, msg, error=False): + """ + Add a message to the Kodi logging system (provided setting allows it) + + :param msg: Text to add to log file + :type msg: String + :param error: Specify whether text indicates an error or action + :type error: Boolean + :return: + :rtype: + """ + if self.is_enabled('verbose_log'): + xbmc.log('[%s]:: %s' % (self.addon_name, msg), (xbmc.LOGNOTICE, xbmc.LOGERROR)[error]) + + def notify(self, msg, period=4, error=None): + """ + Invoke the Kodi onscreen notification panel with a message (provided setting allows it) + + :param msg: Text to display in panel + :type msg: String + :param period: Wait seconds before closing dialog + :type period: Integer + :param error: Specify whether text indicates an error or action + :type error: Boolean + :return: + :rtype: + """ + if not error and self.is_enabled('action_notification') or (error and self.is_enabled('error_notification')): + xbmc.executebuiltin('Notification(%s, "%s", %s, %s)' % ( + self.addon_name, msg, 1000 * period, + ((self.green_logo, self.red_logo)[any([error])], self.black_logo)[None is error])) + + @staticmethod + def ex(e): + return '\n'.join(['\nEXCEPTION Raised: --> Python callback/script returned the following error <--', + 'Error type: ', + 'Error content: {1!r}', + '{2}', + '--> End of Python script error report <--\n' + ]).format(type(e).__name__, e.args, traceback.format_exc()) + + def report_contact_fail(self, e): + msg = 'Failed to contact Kodi at %s:%s' % (self.kodi_ip, self.kodi_port) + self.log('%s %s' % (msg, self.ex(e)), error=True) + self.notify(msg, period=20, error=True) + + def kodi_request(self, params): + params.update(dict(jsonrpc='2.0', id='SickGear')) + try: + response = xbmc.executeJSONRPC(json.dumps(params)) + except (StandardError, Exception) as e: + return self.report_contact_fail(e) + try: + return json.loads(response) + except UnicodeDecodeError: + return json.loads(response.decode('utf-8', 'ignore')) + + def video_library_on_update(self, json_msg): + """ + Actions to perform for: Kodi Notifications / VideoLibrary/ VideoLibrary.OnUpdate + invoked in Kodi when: A video item has been updated + source: http://kodi.wiki/view/JSON-RPC_API/v8#VideoLibrary.OnUpdate + + :param json_msg: A JSON parsed from socks + :type json_msg: String + :return: + :rtype: + """ + try: + # note: this is called multiple times when a season is marked as un-/watched + if 'episode' == json_msg['params']['data']['item']['type']: + media_id = json_msg['params']['data']['item']['id'] + play_count = json_msg['params']['data']['playcount'] + + json_resp = self.kodi_request(dict( + method='Profiles.GetCurrentProfile')) + current_profile = json_resp['result']['label'] + + json_resp = self.kodi_request(dict( + method='VideoLibrary.GetEpisodeDetails', + params=dict(episodeid=media_id, properties=['file']))) + path_file = json_resp['result']['episodedetails']['file'].encode('utf-8') + + self.update_sickgear(media_id, path_file, play_count, current_profile) + except (StandardError, Exception): + pass + + def update_sickgear(self, media_id, path_file, play_count, profile): + + self.notify('Update sent to SickGear') + + url = 'http://%s:%s/update_watched_state_kodi/' % ( + self.addon.getSetting('sickgear_ip'), self.addon.getSetting('sickgear_port')) + self.log('Notify state to %s with path_file=%s' % (url, path_file)) + + msg_bad = 'Failed to contact SickGear on port %s at %s' % ( + self.addon.getSetting('sickgear_port'), self.addon.getSetting('sickgear_ip')) + + payload_json = self.payload_prep(dict(media_id=media_id, path_file=path_file, played=play_count, label=profile)) + if payload_json: + payload = urllib.urlencode(dict(payload=payload_json)) + try: + rq = urllib2.Request(url, data=payload) + r = urllib2.urlopen(rq) + response = json.load(r) + r.close() + if 'OK' == r.msg: + self.payload_prep(response) + if not all(response.values()): + msg = 'Success, watched state updated' + else: + msg = 'Success, %s/%s watched stated updated' % ( + len([v for v in response.values() if v]), len(response.values())) + self.log(msg) + self.notify(msg, error=False) + else: + msg_bad = 'Failed to update watched state' + self.log(msg_bad) + self.notify(msg_bad, error=True) + except (urllib2.URLError, IOError) as e: + self.log(u'Couldn\'t contact SickGear %s' % self.ex(e), error=True) + self.notify(msg_bad, error=True, period=15) + except (StandardError, Exception) as e: + self.log(u'Couldn\'t contact SickGear %s' % self.ex(e), error=True) + self.notify(msg_bad, error=True, period=15) + + @staticmethod + def payload_prep(payload): + + name = 'sickgear_buffer.txt' + # try to locate /temp at parent location + path_temp = path.join(path.dirname(path.dirname(path.realpath(__file__))), 'temp') + path_data = path.join(path_temp, name) + + data_pool = {} + if xbmcvfs.exists(path_data): + fh = None + try: + fh = xbmcvfs.File(path_data) + data_pool = json.load(fh) + except (StandardError, Exception): + pass + fh and fh.close() + + temp_ok = True + if not any([data_pool]): + temp_ok = xbmcvfs.exists(path_temp) or xbmcvfs.exists(path.join(path_temp, sep)) + if not temp_ok: + temp_ok = xbmcvfs.mkdirs(path_temp) + + response_data = False + for k, v in payload.items(): + if response_data or k in data_pool: + response_data = True + if not v: + # whether no fail response or bad input, remove this from data + data_pool.pop(k) + elif isinstance(v, basestring): + # error so retry next time + continue + if not response_data: + ts_now = time.mktime(datetime.datetime.now().timetuple()) + timeout = 100 + while ts_now in data_pool and timeout: + ts_now = time.mktime(datetime.datetime.now().timetuple()) + timeout -= 1 + + max_payload = 50-1 + for k in list(data_pool.keys())[max_payload:]: + data_pool.pop(k) + payload.update(dict(date_watched=ts_now)) + data_pool.update({ts_now: payload}) + + output = json.dumps(data_pool) + if temp_ok: + fh = None + try: + fh = xbmcvfs.File(path_data, 'w') + fh.write(output) + except (StandardError, Exception): + pass + fh and fh.close() + + return output + + def enable_kodi_allow_remote(self): + try: + # setting esenabled: allow remote control by programs on this system + # setting esallinterfaces: allow remote control by programs on other systems + settings = [dict(esenabled=True), dict(esallinterfaces=True)] + for setting in settings: + if not self.kodi_request(dict( + method='Settings.SetSettingValue', + params=dict(setting='services.%s' % setting.keys()[0], value=setting.values()[0]) + )).get('result', {}): + settings[setting] = self.kodi_request(dict( + method='Settings.GetSettingValue', + params=dict(setting='services.%s' % setting.keys()[0]) + )).get('result', {}).get('value') + except (StandardError, Exception): + return + + setting_states = [setting.values()[0] for setting in settings] + if not all(setting_states): + if not (any(setting_states)): + msg = 'Please enable *all* Kodi settings to allow remote control by programs...' + else: + msg = 'Please enable Kodi setting to allow remote control by programs on other systems' + msg = 'Failed startup. %s in system service/remote control' % msg + self.log(msg, error=True) + self.notify(msg, period=20, error=True) + return + return True + + +__dev__ = True +if __dev__: + try: + # noinspection PyProtectedMember + import _devenv as devenv + except ImportError: + __dev__ = False + + +if 1 < len(sys.argv): + if __dev__: + devenv.setup_devenv(False) + if sys.argv[2].endswith('send_all'): + print('>>>>>> TESTTESTTEST') + +elif __name__ == '__main__': + if __dev__: + devenv.setup_devenv(True) + WSU = SickGearWatchedStateUpdater() + WSU.run() + del WSU + +if __dev__: + devenv.stop() diff --git a/sickbeard/common.py b/sickbeard/common.py index 88c6831..382d133 100644 --- a/sickbeard/common.py +++ b/sickbeard/common.py @@ -41,19 +41,6 @@ cpu_presets = {'DISABLED': 0, 'LOW': 0.01, 'NORMAL': 0.05, 'HIGH': 0.1} MULTI_EP_RESULT = -1 SEASON_RESULT = -2 -# Notification Types -NOTIFY_SNATCH = 1 -NOTIFY_DOWNLOAD = 2 -NOTIFY_SUBTITLE_DOWNLOAD = 3 -NOTIFY_GIT_UPDATE = 4 -NOTIFY_GIT_UPDATE_TEXT = 5 - -notifyStrings = {NOTIFY_SNATCH: 'Started Download', - NOTIFY_DOWNLOAD: 'Download Finished', - NOTIFY_SUBTITLE_DOWNLOAD: 'Subtitle Download Finished', - NOTIFY_GIT_UPDATE: 'SickGear Updated', - NOTIFY_GIT_UPDATE_TEXT: 'SickGear Updated To Commit#: '} - # Episode statuses UNKNOWN = -1 # should never happen UNAIRED = 1 # episodes that haven't aired yet diff --git a/sickbeard/config.py b/sickbeard/config.py index 4e7573f..b9c4a6b 100644 --- a/sickbeard/config.py +++ b/sickbeard/config.py @@ -49,7 +49,7 @@ naming_sep_type = (' - ', ' ') naming_sep_type_text = (' - ', 'space') -def change_HTTPS_CERT(https_cert): +def change_https_cert(https_cert): if https_cert == '': sickbeard.HTTPS_CERT = '' return True @@ -64,7 +64,7 @@ def change_HTTPS_CERT(https_cert): return True -def change_HTTPS_KEY(https_key): +def change_https_key(https_key): if https_key == '': sickbeard.HTTPS_KEY = '' return True @@ -79,7 +79,7 @@ def change_HTTPS_KEY(https_key): return True -def change_LOG_DIR(log_dir, web_log): +def change_log_dir(log_dir, web_log): log_dir_changed = False abs_log_dir = os.path.normpath(os.path.join(sickbeard.DATA_DIR, log_dir)) web_log_value = checkbox_to_value(web_log) @@ -102,7 +102,7 @@ def change_LOG_DIR(log_dir, web_log): return True -def change_NZB_DIR(nzb_dir): +def change_nzb_dir(nzb_dir): if nzb_dir == '': sickbeard.NZB_DIR = '' return True @@ -117,7 +117,7 @@ def change_NZB_DIR(nzb_dir): return True -def change_TORRENT_DIR(torrent_dir): +def change_torrent_dir(torrent_dir): if torrent_dir == '': sickbeard.TORRENT_DIR = '' return True @@ -132,7 +132,7 @@ def change_TORRENT_DIR(torrent_dir): return True -def change_TV_DOWNLOAD_DIR(tv_download_dir): +def change_tv_download_dir(tv_download_dir): if tv_download_dir == '': sickbeard.TV_DOWNLOAD_DIR = '' return True @@ -147,16 +147,17 @@ def change_TV_DOWNLOAD_DIR(tv_download_dir): return True -def change_AUTOPOSTPROCESSER_FREQUENCY(freq): +def schedule_autopostprocesser(freq): sickbeard.AUTOPOSTPROCESSER_FREQUENCY = to_int(freq, default=sickbeard.DEFAULT_AUTOPOSTPROCESSER_FREQUENCY) if sickbeard.AUTOPOSTPROCESSER_FREQUENCY < sickbeard.MIN_AUTOPOSTPROCESSER_FREQUENCY: sickbeard.AUTOPOSTPROCESSER_FREQUENCY = sickbeard.MIN_AUTOPOSTPROCESSER_FREQUENCY sickbeard.autoPostProcesserScheduler.cycleTime = datetime.timedelta(minutes=sickbeard.AUTOPOSTPROCESSER_FREQUENCY) + sickbeard.autoPostProcesserScheduler.set_paused_state() -def change_RECENTSEARCH_FREQUENCY(freq): +def schedule_recentsearch(freq): sickbeard.RECENTSEARCH_FREQUENCY = to_int(freq, default=sickbeard.DEFAULT_RECENTSEARCH_FREQUENCY) if sickbeard.RECENTSEARCH_FREQUENCY < sickbeard.MIN_RECENTSEARCH_FREQUENCY: @@ -165,13 +166,14 @@ def change_RECENTSEARCH_FREQUENCY(freq): sickbeard.recentSearchScheduler.cycleTime = datetime.timedelta(minutes=sickbeard.RECENTSEARCH_FREQUENCY) -def change_BACKLOG_FREQUENCY(freq): - sickbeard.BACKLOG_FREQUENCY = minimax(freq, sickbeard.DEFAULT_BACKLOG_FREQUENCY, sickbeard.MIN_BACKLOG_FREQUENCY, sickbeard.MAX_BACKLOG_FREQUENCY) +def schedule_backlog(freq): + sickbeard.BACKLOG_FREQUENCY = minimax(freq, sickbeard.DEFAULT_BACKLOG_FREQUENCY, + sickbeard.MIN_BACKLOG_FREQUENCY, sickbeard.MAX_BACKLOG_FREQUENCY) sickbeard.backlogSearchScheduler.action.cycleTime = sickbeard.BACKLOG_FREQUENCY -def change_UPDATE_FREQUENCY(freq): +def schedule_update(freq): sickbeard.UPDATE_FREQUENCY = to_int(freq, default=sickbeard.DEFAULT_UPDATE_FREQUENCY) if sickbeard.UPDATE_FREQUENCY < sickbeard.MIN_UPDATE_FREQUENCY: @@ -180,27 +182,25 @@ def change_UPDATE_FREQUENCY(freq): sickbeard.versionCheckScheduler.cycleTime = datetime.timedelta(hours=sickbeard.UPDATE_FREQUENCY) -def change_VERSION_NOTIFY(version_notify): - oldSetting = sickbeard.VERSION_NOTIFY +def schedule_version_notify(version_notify): + old_setting = sickbeard.VERSION_NOTIFY sickbeard.VERSION_NOTIFY = version_notify if not version_notify: sickbeard.NEWEST_VERSION_STRING = None - if not oldSetting and version_notify: + if not old_setting and version_notify: sickbeard.versionCheckScheduler.action.run() -def change_DOWNLOAD_PROPERS(download_propers): - if sickbeard.DOWNLOAD_PROPERS == download_propers: - return - - sickbeard.DOWNLOAD_PROPERS = download_propers - sickbeard.properFinderScheduler.check_paused() +def schedule_download_propers(download_propers): + if sickbeard.DOWNLOAD_PROPERS != download_propers: + sickbeard.DOWNLOAD_PROPERS = download_propers + sickbeard.properFinderScheduler.set_paused_state() -def change_USE_TRAKT(use_trakt): +def schedule_trakt(use_trakt): if sickbeard.USE_TRAKT == use_trakt: return @@ -216,22 +216,40 @@ def change_USE_TRAKT(use_trakt): # pass -def change_USE_SUBTITLES(use_subtitles): - if sickbeard.USE_SUBTITLES == use_subtitles: - return +def schedule_subtitles(use_subtitles): + if sickbeard.USE_SUBTITLES != use_subtitles: + sickbeard.USE_SUBTITLES = use_subtitles + sickbeard.subtitlesFinderScheduler.set_paused_state() + + +def schedule_emby_watched(emby_watched_interval): + emby_watched_freq = minimax(emby_watched_interval, sickbeard.DEFAULT_WATCHEDSTATE_FREQUENCY, + 0, sickbeard.MAX_WATCHEDSTATE_FREQUENCY) + if emby_watched_freq and emby_watched_freq != sickbeard.EMBY_WATCHEDSTATE_FREQUENCY: + sickbeard.EMBY_WATCHEDSTATE_FREQUENCY = emby_watched_freq + sickbeard.embyWatchedStateScheduler.cycleTime = datetime.timedelta(minutes=emby_watched_freq) - sickbeard.USE_SUBTITLES = use_subtitles - sickbeard.subtitlesFinderScheduler.check_paused() + sickbeard.EMBY_WATCHEDSTATE_SCHEDULED = bool(emby_watched_freq) + sickbeard.embyWatchedStateScheduler.set_paused_state() -def CheckSection(CFG, sec): +def schedule_plex_watched(plex_watched_interval): + plex_watched_freq = minimax(plex_watched_interval, sickbeard.DEFAULT_WATCHEDSTATE_FREQUENCY, + 0, sickbeard.MAX_WATCHEDSTATE_FREQUENCY) + if plex_watched_freq and plex_watched_freq != sickbeard.PLEX_WATCHEDSTATE_FREQUENCY: + sickbeard.PLEX_WATCHEDSTATE_FREQUENCY = plex_watched_freq + sickbeard.plexWatchedStateScheduler.cycleTime = datetime.timedelta(minutes=plex_watched_freq) + + sickbeard.PLEX_WATCHEDSTATE_SCHEDULED = bool(plex_watched_freq) + sickbeard.plexWatchedStateScheduler.set_paused_state() + + +def check_section(cfg, section): """ Check if INI section exists, if not create it """ - try: - CFG[sec] - return True - except: - CFG[sec] = {} + if section not in cfg: + cfg[section] = {} return False + return True def checkbox_to_value(option, value_on=1, value_off=0): @@ -284,7 +302,7 @@ def clean_host(host, default_port=None): def clean_hosts(hosts, default_port=None): cleaned_hosts = [] - for cur_host in [x.strip() for x in hosts.split(',')]: + for cur_host in [host.strip() for host in hosts.split(',')]: if cur_host: cleaned_host = clean_host(cur_host, default_port) if cleaned_host: @@ -324,12 +342,25 @@ def clean_url(url, add_slash=True): return cleaned_url +def kv_csv(data, default=''): + """ + Returns a cleansed CSV string of key value pairs + Elements must have one '=' in order to be returned + Elements are stripped of leading/trailing whitespace but may contain whitespace (e.g. "tv shows") + """ + if not isinstance(data, basestring): + return default + + return ','.join(['='.join(i.strip() for i in i.split('=')) for i in data.split(',') + if 1 == len(re.findall('=', i)) and all(i.replace(' ', '').split('='))]) + + def to_int(val, default=0): """ Return int value of val or default on error """ try: val = int(val) - except: + except(StandardError, Exception): val = default return val @@ -351,11 +382,11 @@ def minimax(val, default, low, high): def check_setting_int(config, cfg_name, item_name, def_val): try: my_val = int(config[cfg_name][item_name]) - except: + except(StandardError, Exception): my_val = def_val try: config[cfg_name][item_name] = my_val - except: + except(StandardError, Exception): config[cfg_name] = {} config[cfg_name][item_name] = my_val logger.log('%s -> %s' % (item_name, my_val), logger.DEBUG) @@ -365,11 +396,11 @@ def check_setting_int(config, cfg_name, item_name, def_val): def check_setting_float(config, cfg_name, item_name, def_val): try: my_val = float(config[cfg_name][item_name]) - except: + except(StandardError, Exception): my_val = def_val try: config[cfg_name][item_name] = my_val - except: + except(StandardError, Exception): config[cfg_name] = {} config[cfg_name][item_name] = my_val @@ -391,11 +422,11 @@ def check_setting_str(config, cfg_name, item_name, def_val, log=True): try: my_val = helpers.decrypt(config[cfg_name][item_name], encryption_version) - except: + except(StandardError, Exception): my_val = def_val try: config[cfg_name][item_name] = helpers.encrypt(my_val, encryption_version) - except: + except(StandardError, Exception): config[cfg_name] = {} config[cfg_name][item_name] = helpers.encrypt(my_val, encryption_version) @@ -407,7 +438,7 @@ def check_setting_str(config, cfg_name, item_name, def_val, log=True): return (my_val, def_val)['None' == my_val] -class ConfigMigrator(): +class ConfigMigrator: def __init__(self, config_obj): """ Initializes a config migrator that can take the config from the version indicated in the config @@ -491,8 +522,8 @@ class ConfigMigrator(): sickbeard.NAMING_MULTI_EP = int(check_setting_int(self.config_obj, 'General', 'naming_multi_ep_type', 1)) # see if any of their shows used season folders - myDB = db.DBConnection() - season_folder_shows = myDB.select('SELECT * FROM tv_shows WHERE flatten_folders = 0') + my_db = db.DBConnection() + season_folder_shows = my_db.select('SELECT * FROM tv_shows WHERE flatten_folders = 0') # if any shows had season folders on then prepend season folder to the pattern if season_folder_shows: @@ -518,7 +549,7 @@ class ConfigMigrator(): logger.log(u'No shows were using season folders before so I am disabling flattening on all shows') # don't flatten any shows at all - myDB.action('UPDATE tv_shows SET flatten_folders = 0') + my_db.action('UPDATE tv_shows SET flatten_folders = 0') sickbeard.NAMING_FORCE_FOLDERS = naming.check_force_season_folders() @@ -534,11 +565,11 @@ class ConfigMigrator(): use_ep_name = bool(check_setting_int(self.config_obj, 'General', 'naming_ep_name', 1)) # make the presets into templates - naming_ep_type = ('%Sx%0E', + naming_ep_tmpl = ('%Sx%0E', 's%0Se%0E', 'S%0SE%0E', '%0Sx%0E') - naming_sep_type = (' - ', ' ') + naming_sep_tmpl = (' - ', ' ') # set up our data to use if use_periods: @@ -555,29 +586,29 @@ class ConfigMigrator(): if abd: ep_string = abd_string else: - ep_string = naming_ep_type[ep_type] + ep_string = naming_ep_tmpl[ep_type] - finalName = '' + final_name = '' # start with the show name if use_show_name: - finalName += show_name + naming_sep_type[sep_type] + final_name += show_name + naming_sep_tmpl[sep_type] # add the season/ep stuff - finalName += ep_string + final_name += ep_string # add the episode name if use_ep_name: - finalName += naming_sep_type[sep_type] + ep_name + final_name += naming_sep_tmpl[sep_type] + ep_name # add the quality if use_quality: - finalName += naming_sep_type[sep_type] + ep_quality + final_name += naming_sep_tmpl[sep_type] + ep_quality if use_periods: - finalName = re.sub('\s+', '.', finalName) + final_name = re.sub('\s+', '.', final_name) - return finalName + return final_name # Migration v2: Dummy migration to sync backup number with config version number def _migrate_v2(self): @@ -589,7 +620,8 @@ class ConfigMigrator(): Reads in the old naming settings from your config and generates a new config template from them. """ # get the old settings from the file and store them in the new variable names - for prov in [curProvider for curProvider in sickbeard.providers.sortedProviderList() if curProvider.name == 'omgwtfnzbs']: + for prov in [curProvider for curProvider in sickbeard.providers.sortedProviderList() + if 'omgwtfnzbs' == curProvider.name]: prov.username = check_setting_str(self.config_obj, 'omgwtfnzbs', 'omgwtfnzbs_uid', '') prov.api_key = check_setting_str(self.config_obj, 'omgwtfnzbs', 'omgwtfnzbs_key', '') @@ -662,7 +694,7 @@ class ConfigMigrator(): use_banner = bool(check_setting_int(self.config_obj, 'General', 'use_banner', 0)) - def _migrate_metadata(metadata, metadata_name, use_banner): + def _migrate_metadata(metadata, metadata_name, banner): cur_metadata = metadata.split('|') # if target has the old number of values, do upgrade if len(cur_metadata) == 6: @@ -673,9 +705,9 @@ class ConfigMigrator(): cur_metadata.append('0') # swap show fanart, show poster cur_metadata[3], cur_metadata[2] = cur_metadata[2], cur_metadata[3] - # if user was using use_banner to override the poster, + # if user was using banner to override the poster, # instead enable the banner option and deactivate poster - if metadata_name == 'XBMC' and use_banner: + if 'XBMC' == metadata_name and banner: cur_metadata[4], cur_metadata[3] = cur_metadata[3], '0' # write new format metadata = '|'.join(cur_metadata) @@ -723,7 +755,8 @@ class ConfigMigrator(): check_setting_int(self.config_obj, 'GUI', 'coming_eps_display_paused', 0)) sickbeard.EPISODE_VIEW_MISSED_RANGE = check_setting_int(self.config_obj, 'GUI', 'coming_eps_missed_range', 7) - def _migrate_v8(self): + @staticmethod + def _migrate_v8(): # removing settings from gui and making it a hidden debug option sickbeard.RECENTSEARCH_STARTUP = False @@ -731,7 +764,8 @@ class ConfigMigrator(): sickbeard.PUSHBULLET_ACCESS_TOKEN = check_setting_str(self.config_obj, 'Pushbullet', 'pushbullet_api', '') sickbeard.PUSHBULLET_DEVICE_IDEN = check_setting_str(self.config_obj, 'Pushbullet', 'pushbullet_device', '') - def _migrate_v10(self): + @staticmethod + def _migrate_v10(): # reset backlog frequency to default sickbeard.BACKLOG_FREQUENCY = sickbeard.DEFAULT_BACKLOG_FREQUENCY @@ -741,9 +775,11 @@ class ConfigMigrator(): else: sickbeard.SHOWLIST_TAGVIEW = 'default' - def _migrate_v12(self): + @staticmethod + def _migrate_v12(): # add words to ignore list and insert spaces to improve the ui config readability - words_to_add = ['hevc', 'reenc', 'x265', 'danish', 'deutsch', 'flemish', 'italian', 'nordic', 'norwegian', 'portuguese', 'spanish', 'turkish'] + words_to_add = ['hevc', 'reenc', 'x265', 'danish', 'deutsch', 'flemish', 'italian', + 'nordic', 'norwegian', 'portuguese', 'spanish', 'turkish'] config_words = sickbeard.IGNORE_WORDS.split(',') new_list = [] for new_word in words_to_add: @@ -759,7 +795,8 @@ class ConfigMigrator(): sickbeard.IGNORE_WORDS = ', '.join(sorted(new_list)) - def _migrate_v13(self): + @staticmethod + def _migrate_v13(): # change dereferrer.org urls to blank, but leave any other url untouched if sickbeard.ANON_REDIRECT == 'http://dereferer.org/?': sickbeard.ANON_REDIRECT = '' diff --git a/sickbeard/databases/mainDB.py b/sickbeard/databases/mainDB.py index b49da75..28a44da 100644 --- a/sickbeard/databases/mainDB.py +++ b/sickbeard/databases/mainDB.py @@ -27,7 +27,7 @@ from sickbeard import encodingKludge as ek from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException MIN_DB_VERSION = 9 # oldest db version we support migrating from -MAX_DB_VERSION = 20008 +MAX_DB_VERSION = 20009 TEST_BASE_VERSION = None # the base production db version, only needed for TEST db versions (>=100000) @@ -44,12 +44,13 @@ class MainSanityCheck(db.DBSanityCheck): def fix_duplicate_shows(self, column='indexer_id'): sql_results = self.connection.select( - 'SELECT show_id, ' + column + ', COUNT(' + column + ') as count FROM tv_shows GROUP BY ' + column + ' HAVING count > 1') + 'SELECT show_id, %(col)s, COUNT(%(col)s) as count FROM tv_shows GROUP BY %(col)s HAVING count > 1' + % {'col': column}) for cur_duplicate in sql_results: - logger.log(u'Duplicate show detected! %s: %s count: %s' % (column, cur_duplicate[column], - cur_duplicate['count']), logger.DEBUG) + logger.log(u'Duplicate show detected! %s: %s count: %s' % ( + column, cur_duplicate[column], cur_duplicate['count']), logger.DEBUG) cur_dupe_results = self.connection.select( 'SELECT show_id, ' + column + ' FROM tv_shows WHERE ' + column + ' = ? LIMIT ?', @@ -58,9 +59,8 @@ class MainSanityCheck(db.DBSanityCheck): cl = [] for cur_dupe_id in cur_dupe_results: - logger.log( - u'Deleting duplicate show with %s: %s show_id: %s' % (column, cur_dupe_id[column], - cur_dupe_id['show_id'])) + logger.log(u'Deleting duplicate show with %s: %s show_id: %s' % ( + column, cur_dupe_id[column], cur_dupe_id['show_id'])) cl.append(['DELETE FROM tv_shows WHERE show_id = ?', [cur_dupe_id['show_id']]]) if 0 < len(cl): @@ -72,7 +72,10 @@ class MainSanityCheck(db.DBSanityCheck): def fix_duplicate_episodes(self): sql_results = self.connection.select( - 'SELECT showid, season, episode, COUNT(showid) as count FROM tv_episodes GROUP BY showid, season, episode HAVING count > 1') + 'SELECT showid, season, episode, COUNT(showid) as count' + ' FROM tv_episodes' + ' GROUP BY showid, season, episode' + ' HAVING count > 1') for cur_duplicate in sql_results: @@ -81,7 +84,10 @@ class MainSanityCheck(db.DBSanityCheck): cur_duplicate['count']), logger.DEBUG) cur_dupe_results = self.connection.select( - 'SELECT episode_id FROM tv_episodes WHERE showid = ? AND season = ? and episode = ? ORDER BY episode_id DESC LIMIT ?', + 'SELECT episode_id' + ' FROM tv_episodes' + ' WHERE showid = ? AND season = ? and episode = ?' + ' ORDER BY episode_id DESC LIMIT ?', [cur_duplicate['showid'], cur_duplicate['season'], cur_duplicate['episode'], int(cur_duplicate['count']) - 1] ) @@ -100,12 +106,15 @@ class MainSanityCheck(db.DBSanityCheck): def fix_orphan_episodes(self): sql_results = self.connection.select( - 'SELECT episode_id, showid, tv_shows.indexer_id FROM tv_episodes LEFT JOIN tv_shows ON tv_episodes.showid=tv_shows.indexer_id WHERE tv_shows.indexer_id is NULL') + 'SELECT episode_id, showid, tv_shows.indexer_id' + ' FROM tv_episodes' + ' LEFT JOIN tv_shows ON tv_episodes.showid=tv_shows.indexer_id' + ' WHERE tv_shows.indexer_id is NULL') cl = [] for cur_orphan in sql_results: - logger.log(u'Orphan episode detected! episode_id: %s showid: %s' % (cur_orphan['episode_id'], - cur_orphan['showid']), logger.DEBUG) + logger.log(u'Orphan episode detected! episode_id: %s showid: %s' % ( + cur_orphan['episode_id'], cur_orphan['showid']), logger.DEBUG) logger.log(u'Deleting orphan episode with episode_id: %s' % cur_orphan['episode_id']) cl.append(['DELETE FROM tv_episodes WHERE episode_id = ?', [cur_orphan['episode_id']]]) @@ -150,15 +159,15 @@ class MainSanityCheck(db.DBSanityCheck): sql_results = self.connection.select( 'SELECT episode_id, showid FROM tv_episodes WHERE status = ? or ( airdate > ? AND status in (?,?) ) or ' - '( airdate <= 1 AND status = ? )', ['', cur_date.toordinal(), common.SKIPPED, common.WANTED, common.WANTED]) + '(airdate <= 1 AND status = ? )', ['', cur_date.toordinal(), common.SKIPPED, common.WANTED, common.WANTED]) cl = [] for cur_unaired in sql_results: - logger.log(u'UNAIRED episode detected! episode_id: %s showid: %s' % (cur_unaired['episode_id'], - cur_unaired['showid']), logger.DEBUG) + logger.log(u'UNAIRED episode detected! episode_id: %s showid: %s' % ( + cur_unaired['episode_id'], cur_unaired['showid']), logger.DEBUG) logger.log(u'Fixing unaired episode status with episode_id: %s' % cur_unaired['episode_id']) cl.append(['UPDATE tv_episodes SET status = ? WHERE episode_id = ?', - [common.UNAIRED, cur_unaired['episode_id']]]) + [common.UNAIRED, cur_unaired['episode_id']]]) if 0 < len(cl): self.connection.mass_action(cl) @@ -176,42 +185,90 @@ class MainSanityCheck(db.DBSanityCheck): self.connection.action('UPDATE scene_exceptions SET season = -1 WHERE season = "null"') def fix_orphan_not_found_show(self): - sql_result = self.connection.action('DELETE FROM tv_shows_not_found WHERE NOT EXISTS (SELECT NULL FROM ' - 'tv_shows WHERE tv_shows_not_found.indexer == tv_shows.indexer AND ' - 'tv_shows_not_found.indexer_id == tv_shows.indexer_id)') + sql_result = self.connection.action( + 'DELETE FROM tv_shows_not_found' + ' WHERE NOT EXISTS (SELECT NULL FROM tv_shows WHERE tv_shows_not_found.indexer == tv_shows.indexer AND' + ' tv_shows_not_found.indexer_id == tv_shows.indexer_id)') if sql_result.rowcount: logger.log('Fixed orphaned not found shows') -# ====================== -# = Main DB Migrations = -# ====================== -# Add new migrations at the bottom of the list; subclass the previous migration. -# 0 -> 20003 + class InitialSchema(db.SchemaUpgrade): + # ====================== + # = Main DB Migrations = + # ====================== + # Add new migrations at the bottom of the list; subclass the previous migration. + # 0 -> 20007 def execute(self): db.backup_database('sickbeard.db', self.checkDBVersion()) if not self.hasTable('tv_shows') and not self.hasTable('db_version'): queries = [ - # original sick beard tables - 'CREATE TABLE db_version (db_version INTEGER);', - 'CREATE TABLE history (action NUMERIC, date NUMERIC, showid NUMERIC, season NUMERIC, episode NUMERIC, quality NUMERIC, resource TEXT, provider TEXT, version NUMERIC)', - 'CREATE TABLE info (last_backlog NUMERIC, last_indexer NUMERIC, last_proper_search NUMERIC)', - 'CREATE TABLE tv_episodes (episode_id INTEGER PRIMARY KEY, showid NUMERIC, indexerid NUMERIC, indexer NUMERIC, name TEXT, season NUMERIC, episode NUMERIC, description TEXT, airdate NUMERIC, hasnfo NUMERIC, hastbn NUMERIC, status NUMERIC, location TEXT, file_size NUMERIC, release_name TEXT, subtitles TEXT, subtitles_searchcount NUMERIC, subtitles_lastsearch TIMESTAMP, is_proper NUMERIC, scene_season NUMERIC, scene_episode NUMERIC, absolute_number NUMERIC, scene_absolute_number NUMERIC, version NUMERIC, release_group TEXT, trakt_watched NUMERIC)', - 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, indexer_id NUMERIC, indexer NUMERIC, show_name TEXT, location TEXT, network TEXT, genre TEXT, classification TEXT, runtime NUMERIC, quality NUMERIC, airs TEXT, status TEXT, flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC, air_by_date NUMERIC, lang TEXT, subtitles NUMERIC, notify_list TEXT, imdb_id TEXT, last_update_indexer NUMERIC, dvdorder NUMERIC, archive_firstmatch NUMERIC, rls_require_words TEXT, rls_ignore_words TEXT, sports NUMERIC, anime NUMERIC, scene NUMERIC, overview TEXT, tag TEXT)', - 'CREATE INDEX idx_showid ON tv_episodes (showid)', - 'CREATE INDEX idx_tv_episodes_showid_airdate ON tv_episodes (showid,airdate)', + # blacklist 'CREATE TABLE blacklist (show_id INTEGER, range TEXT, keyword TEXT)', - 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER, mindexer NUMERIC, PRIMARY KEY (indexer_id, indexer))', - 'CREATE TABLE imdb_info (indexer_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC, akas TEXT, runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT, rating TEXT, votes INTEGER, last_update NUMERIC)', - 'CREATE TABLE scene_numbering (indexer TEXT, indexer_id INTEGER, season INTEGER, episode INTEGER, scene_season INTEGER, scene_episode INTEGER, absolute_number NUMERIC, scene_absolute_number NUMERIC, PRIMARY KEY (indexer_id, season, episode))', + # db_version + 'CREATE TABLE db_version (db_version INTEGER)', + 'INSERT INTO db_version (db_version) VALUES (20008)', + # flags + 'CREATE TABLE flags (flag PRIMARY KEY NOT NULL)', + # history + 'CREATE TABLE history (action NUMERIC, date NUMERIC, showid NUMERIC, season NUMERIC, episode NUMERIC,' + ' quality NUMERIC, resource TEXT, provider TEXT, version NUMERIC)', + # imdb_info + 'CREATE TABLE imdb_info (indexer_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC,' + ' akas TEXT, runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT,' + ' rating TEXT, votes INTEGER, last_update NUMERIC)', + # indexer_mapping + 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER NOT NULL,' + ' mindexer NUMERIC, date NUMERIC NOT NULL DEFAULT 0, status INTEGER NOT NULL DEFAULT 0,' + ' PRIMARY KEY (indexer_id, indexer, mindexer))', + 'CREATE INDEX idx_mapping ON indexer_mapping (indexer_id, indexer)', + # info + 'CREATE TABLE info (last_backlog NUMERIC, last_indexer NUMERIC, last_proper_search NUMERIC,' + ' last_run_backlog NUMERIC NOT NULL DEFAULT 1)', + # scene_exceptions + 'CREATE TABLE scene_exceptions (exception_id INTEGER PRIMARY KEY, indexer_id INTEGER KEY,' + ' show_name TEXT, season NUMERIC, custom NUMERIC)', + # scene_exceptions_refresh + 'CREATE TABLE scene_exceptions_refresh (list TEXT PRIMARY KEY, last_refreshed INTEGER)', + # scene_numbering + 'CREATE TABLE scene_numbering (indexer TEXT, indexer_id INTEGER, season INTEGER, episode INTEGER,' + ' scene_season INTEGER, scene_episode INTEGER, absolute_number NUMERIC, scene_absolute_number NUMERIC,' + ' PRIMARY KEY (indexer_id, season, episode))', + # tv_episodes + 'CREATE TABLE tv_episodes (episode_id INTEGER PRIMARY KEY, showid NUMERIC, indexerid NUMERIC,' + ' indexer NUMERIC, name TEXT, season NUMERIC, episode NUMERIC, description TEXT, airdate NUMERIC,' + ' hasnfo NUMERIC, hastbn NUMERIC, status NUMERIC, location TEXT, file_size NUMERIC, release_name TEXT,' + ' subtitles TEXT, subtitles_searchcount NUMERIC, subtitles_lastsearch TIMESTAMP, is_proper NUMERIC,' + ' scene_season NUMERIC, scene_episode NUMERIC, absolute_number NUMERIC, scene_absolute_number NUMERIC,' + ' version NUMERIC, release_group TEXT, trakt_watched NUMERIC)', + 'CREATE INDEX idx_showid ON tv_episodes (showid)', + 'CREATE INDEX idx_tv_episodes_showid_airdate ON tv_episodes (showid, airdate)', + 'CREATE INDEX idx_sta_epi_air ON tv_episodes (status, episode, airdate)', + 'CREATE INDEX idx_sta_epi_sta_air ON tv_episodes (season, episode, status, airdate)', + 'CREATE INDEX idx_status ON tv_episodes (status, season, episode, airdate)', + # tv_episodes_watched + 'CREATE TABLE tv_episodes_watched (tvep_id NUMERIC NOT NULL, clientep_id TEXT, label TEXT,' + ' played NUMERIC DEFAULT 0 NOT NULL, date_watched NUMERIC NOT NULL, date_added NUMERIC,' + ' status NUMERIC, location TEXT, file_size NUMERIC, hide INT default 0 not null)', + # tv_shows + 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, indexer_id NUMERIC, indexer NUMERIC,' + ' show_name TEXT, location TEXT, network TEXT, genre TEXT, classification TEXT, runtime NUMERIC,' + ' quality NUMERIC, airs TEXT, status TEXT, flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC,' + ' air_by_date NUMERIC, lang TEXT, subtitles NUMERIC, notify_list TEXT, imdb_id TEXT,' + ' last_update_indexer NUMERIC, dvdorder NUMERIC, archive_firstmatch NUMERIC, rls_require_words TEXT,' + ' rls_ignore_words TEXT, sports NUMERIC, anime NUMERIC, scene NUMERIC, overview TEXT, tag TEXT)', + 'CREATE UNIQUE INDEX idx_indexer_id ON tv_shows (indexer_id)', + # tv_shows_not_found + 'CREATE TABLE tv_shows_not_found (indexer NUMERIC NOT NULL, indexer_id NUMERIC NOT NULL,' + ' fail_count NUMERIC NOT NULL DEFAULT 0, last_check NUMERIC NOT NULL, last_success NUMERIC,' + ' PRIMARY KEY (indexer_id, indexer))', + # webdl_types + 'CREATE TABLE webdl_types (dname TEXT NOT NULL, regex TEXT NOT NULL)', + # whitelist 'CREATE TABLE whitelist (show_id INTEGER, range TEXT, keyword TEXT)', + # xem_refresh 'CREATE TABLE xem_refresh (indexer TEXT, indexer_id INTEGER PRIMARY KEY, last_refreshed INTEGER)', - 'CREATE UNIQUE INDEX idx_indexer_id ON tv_shows (indexer_id)', - 'CREATE INDEX idx_sta_epi_air ON tv_episodes (status,episode, airdate)', - 'CREATE INDEX idx_sta_epi_sta_air ON tv_episodes (season,episode, status, airdate)', - 'CREATE INDEX idx_status ON tv_episodes (status,season,episode,airdate)', - 'INSERT INTO db_version (db_version) VALUES (20003)' ] for query in queries: self.connection.action(query) @@ -220,20 +277,22 @@ class InitialSchema(db.SchemaUpgrade): cur_db_version = self.checkDBVersion() if cur_db_version < MIN_DB_VERSION: - logger.log_error_and_exit(u'Your database version (' - + str(cur_db_version) - + ') is too old to migrate from what this version of SickGear supports (' - + str(MIN_DB_VERSION) + ').' + "\n" - + 'Upgrade using a previous version (tag) build 496 to build 501 of SickGear first or remove database file to begin fresh.' - ) + logger.log_error_and_exit( + u'Your database version (' + str(cur_db_version) + + ') is too old to migrate from what this version of SickGear supports (' + + str(MIN_DB_VERSION) + ').' + "\n" + + 'Upgrade using a previous version (tag) build 496 to build 501 of SickGear' + ' first or remove database file to begin fresh.' + ) if cur_db_version > MAX_DB_VERSION: - logger.log_error_and_exit(u'Your database version (' - + str(cur_db_version) - + ') has been incremented past what this version of SickGear supports (' - + str(MAX_DB_VERSION) + ').' + "\n" - + 'If you have used other forks of SickGear, your database may be unusable due to their modifications.' - ) + logger.log_error_and_exit( + u'Your database version (' + str(cur_db_version) + + ') has been incremented past what this version of SickGear supports (' + + str(MAX_DB_VERSION) + ').\n' + + 'If you have used other forks of SickGear,' + ' your database may be unusable due to their modifications.' + ) return self.checkDBVersion() @@ -270,7 +329,9 @@ class AddSizeAndSceneNameFields(db.SchemaUpgrade): for cur_result in history_results: # find the associated download, if there isn't one then ignore it download_results = self.connection.select( - 'SELECT resource FROM history WHERE provider = -1 AND showid = ? AND season = ? AND episode = ? AND date > ?', + 'SELECT resource' + ' FROM history' + ' WHERE provider = -1 AND showid = ? AND season = ? AND episode = ? AND date > ?', [cur_result['showid'], cur_result['season'], cur_result['episode'], cur_result['date']]) if not download_results: logger.log(u'Found a snatch in the history for ' + cur_result[ @@ -286,7 +347,9 @@ class AddSizeAndSceneNameFields(db.SchemaUpgrade): # find the associated episode on disk ep_results = self.connection.select( - 'SELECT episode_id, status FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ? AND location != ""', + 'SELECT episode_id, status' + ' FROM tv_episodes' + ' WHERE showid = ? AND season = ? AND episode = ? AND location != ""', [cur_result['showid'], cur_result['season'], cur_result['episode']]) if not ep_results: logger.log( @@ -358,8 +421,14 @@ class RenameSeasonFolders(db.SchemaUpgrade): # rename the column self.connection.action('ALTER TABLE tv_shows RENAME TO tmp_tv_shows') self.connection.action( - 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, location TEXT, show_name TEXT, tvdb_id NUMERIC, network TEXT, genre TEXT, runtime NUMERIC, quality NUMERIC, airs TEXT, status TEXT, flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC, tvr_id NUMERIC, tvr_name TEXT, air_by_date NUMERIC, lang TEXT)') - sql = 'INSERT INTO tv_shows(show_id, location, show_name, tvdb_id, network, genre, runtime, quality, airs, status, flatten_folders, paused, startyear, tvr_id, tvr_name, air_by_date, lang) SELECT show_id, location, show_name, tvdb_id, network, genre, runtime, quality, airs, status, seasonfolders, paused, startyear, tvr_id, tvr_name, air_by_date, lang FROM tmp_tv_shows' + 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, location TEXT, show_name TEXT, tvdb_id NUMERIC,' + ' network TEXT, genre TEXT, runtime NUMERIC, quality NUMERIC, airs TEXT, status TEXT,' + ' flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC, tvr_id NUMERIC, tvr_name TEXT,' + ' air_by_date NUMERIC, lang TEXT)') + sql = 'INSERT INTO tv_shows(show_id, location, show_name, tvdb_id, network, genre, runtime,' \ + ' quality, airs, status, flatten_folders, paused, startyear, tvr_id, tvr_name, air_by_date, lang)' \ + ' SELECT show_id, location, show_name, tvdb_id, network, genre, runtime, quality, airs, status,' \ + ' seasonfolders, paused, startyear, tvr_id, tvr_name, air_by_date, lang FROM tmp_tv_shows' self.connection.action(sql) # flip the values to be opposite of what they were before @@ -419,13 +488,13 @@ class Add1080pAndRawHDQualities(db.SchemaUpgrade): return result def _update_composite_qualities(self, status): - ''' + """ Unpack, Update, Return new quality values Unpack the composite archive/initial values. Update either qualities if needed. Then return the new compsite quality value. - ''' + """ best = (status & (0xffff << 16)) >> 16 initial = status & 0xffff @@ -449,7 +518,8 @@ class Add1080pAndRawHDQualities(db.SchemaUpgrade): new_hd = common.Quality.combineQualities([common.Quality.HDTV, common.Quality.HDWEBDL, common.Quality.HDBLURAY], []) - # update ANY -- shift existing qualities and add new 1080p qualities, note that rawHD was not added to the ANY template + # update ANY -- shift existing qualities and add new 1080p qualities, + # note that rawHD was not added to the ANY template old_any = common.Quality.combineQualities( [common.Quality.SDTV, common.Quality.SDDVD, common.Quality.HDTV, common.Quality.HDWEBDL >> 2, common.Quality.HDBLURAY >> 3, common.Quality.UNKNOWN], []) @@ -472,7 +542,8 @@ class Add1080pAndRawHDQualities(db.SchemaUpgrade): cl.append(['UPDATE tv_shows SET quality = ? WHERE show_id = ?', [new_quality, cur_show['show_id']]]) self.connection.mass_action(cl) - # update status that are are within the old hdwebdl (1<<3 which is 8) and better -- exclude unknown (1<<15 which is 32768) + # update status that are are within the old hdwebdl + # (1<<3 which is 8) and better -- exclude unknown (1<<15 which is 32768) logger.log(u'[2/4] Updating the status for the episodes within each show...', logger.MESSAGE) cl = [] episodes = self.connection.select('SELECT * FROM tv_episodes WHERE status < 3276800 AND status >= 800') @@ -481,7 +552,8 @@ class Add1080pAndRawHDQualities(db.SchemaUpgrade): [self._update_status(cur_episode['status']), cur_episode['episode_id']]]) self.connection.mass_action(cl) - # make two seperate passes through the history since snatched and downloaded (action & quality) may not always coordinate together + # make two seperate passes through the history since snatched and downloaded (action & quality) + # may not always coordinate together # update previous history so it shows the correct action logger.log(u'[3/4] Updating history to reflect the correct action...', logger.MESSAGE) @@ -564,7 +636,9 @@ class AddIMDbInfo(db.SchemaUpgrade): db.backup_database('sickbeard.db', self.checkDBVersion()) db_backed_up = True self.connection.action( - 'CREATE TABLE imdb_info (tvdb_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC, akas TEXT, runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT, rating TEXT, votes INTEGER, last_update NUMERIC)') + 'CREATE TABLE imdb_info (tvdb_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC,' + ' akas TEXT, runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT,' + ' rating TEXT, votes INTEGER, last_update NUMERIC)') if not self.hasColumn('tv_shows', 'imdb_id'): logger.log(u'Adding IMDb column imdb_id to tv_shows') @@ -680,9 +754,18 @@ class ConvertTVShowsToIndexerScheme(db.SchemaUpgrade): self.connection.action('ALTER TABLE tv_shows RENAME TO tmp_tv_shows') self.connection.action( - 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, indexer_id NUMERIC, indexer NUMERIC, show_name TEXT, location TEXT, network TEXT, genre TEXT, classification TEXT, runtime NUMERIC, quality NUMERIC, airs TEXT, status TEXT, flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC, air_by_date NUMERIC, lang TEXT, subtitles NUMERIC, notify_list TEXT, imdb_id TEXT, last_update_indexer NUMERIC, dvdorder NUMERIC)') + 'CREATE TABLE tv_shows (show_id INTEGER PRIMARY KEY, indexer_id NUMERIC, indexer NUMERIC, show_name TEXT,' + ' location TEXT, network TEXT, genre TEXT, classification TEXT, runtime NUMERIC, quality NUMERIC,' + ' airs TEXT, status TEXT, flatten_folders NUMERIC, paused NUMERIC, startyear NUMERIC, air_by_date NUMERIC,' + ' lang TEXT, subtitles NUMERIC, notify_list TEXT, imdb_id TEXT,' + ' last_update_indexer NUMERIC, dvdorder NUMERIC)') self.connection.action( - 'INSERT INTO tv_shows(show_id, indexer_id, show_name, location, network, genre, runtime, quality, airs, status, flatten_folders, paused, startyear, air_by_date, lang, subtitles, notify_list, imdb_id, last_update_indexer, dvdorder) SELECT show_id, tvdb_id, show_name, location, network, genre, runtime, quality, airs, status, flatten_folders, paused, startyear, air_by_date, lang, subtitles, notify_list, imdb_id, last_update_tvdb, dvdorder FROM tmp_tv_shows') + 'INSERT INTO tv_shows(show_id, indexer_id, show_name, location, network, genre, runtime, quality, airs,' + ' status, flatten_folders, paused, startyear, air_by_date, lang, subtitles, notify_list, imdb_id,' + ' last_update_indexer, dvdorder)' + ' SELECT show_id, tvdb_id, show_name, location, network, genre, runtime,' + ' quality, airs, status, flatten_folders, paused, startyear, air_by_date, lang, subtitles, notify_list,' + ' imdb_id, last_update_tvdb, dvdorder FROM tmp_tv_shows') self.connection.action('DROP TABLE tmp_tv_shows') self.connection.action('CREATE UNIQUE INDEX idx_indexer_id ON tv_shows (indexer_id);') @@ -707,9 +790,16 @@ class ConvertTVEpisodesToIndexerScheme(db.SchemaUpgrade): self.connection.action('ALTER TABLE tv_episodes RENAME TO tmp_tv_episodes') self.connection.action( - 'CREATE TABLE tv_episodes (episode_id INTEGER PRIMARY KEY, showid NUMERIC, indexerid NUMERIC, indexer NUMERIC, name TEXT, season NUMERIC, episode NUMERIC, description TEXT, airdate NUMERIC, hasnfo NUMERIC, hastbn NUMERIC, status NUMERIC, location TEXT, file_size NUMERIC, release_name TEXT, subtitles TEXT, subtitles_searchcount NUMERIC, subtitles_lastsearch TIMESTAMP, is_proper NUMERIC)') + 'CREATE TABLE tv_episodes (episode_id INTEGER PRIMARY KEY, showid NUMERIC, indexerid NUMERIC,' + ' indexer NUMERIC, name TEXT, season NUMERIC, episode NUMERIC, description TEXT, airdate NUMERIC,' + ' hasnfo NUMERIC, hastbn NUMERIC, status NUMERIC, location TEXT, file_size NUMERIC, release_name TEXT,' + ' subtitles TEXT, subtitles_searchcount NUMERIC, subtitles_lastsearch TIMESTAMP, is_proper NUMERIC)') self.connection.action( - 'INSERT INTO tv_episodes(episode_id, showid, indexerid, name, season, episode, description, airdate, hasnfo, hastbn, status, location, file_size, release_name, subtitles, subtitles_searchcount, subtitles_lastsearch, is_proper) SELECT episode_id, showid, tvdbid, name, season, episode, description, airdate, hasnfo, hastbn, status, location, file_size, release_name, subtitles, subtitles_searchcount, subtitles_lastsearch, is_proper FROM tmp_tv_episodes') + 'INSERT INTO tv_episodes(episode_id, showid, indexerid, name, season, episode, description, airdate,' + ' hasnfo, hastbn, status, location, file_size, release_name, subtitles, subtitles_searchcount,' + ' subtitles_lastsearch, is_proper) SELECT episode_id, showid, tvdbid, name, season, episode, description,' + ' airdate, hasnfo, hastbn, status, location, file_size, release_name, subtitles, subtitles_searchcount,' + ' subtitles_lastsearch, is_proper FROM tmp_tv_episodes') self.connection.action('DROP TABLE tmp_tv_episodes') self.connection.action('CREATE INDEX idx_tv_episodes_showid_airdate ON tv_episodes(showid,airdate);') @@ -737,9 +827,13 @@ class ConvertIMDBInfoToIndexerScheme(db.SchemaUpgrade): self.connection.action('ALTER TABLE imdb_info RENAME TO tmp_imdb_info') self.connection.action( - 'CREATE TABLE imdb_info (indexer_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC, akas TEXT, runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT, rating TEXT, votes INTEGER, last_update NUMERIC)') + 'CREATE TABLE imdb_info (indexer_id INTEGER PRIMARY KEY, imdb_id TEXT, title TEXT, year NUMERIC, akas TEXT,' + ' runtimes NUMERIC, genres TEXT, countries TEXT, country_codes TEXT, certificates TEXT, rating TEXT,' + ' votes INTEGER, last_update NUMERIC)') self.connection.action( - 'INSERT INTO imdb_info(indexer_id, imdb_id, title, year, akas, runtimes, genres, countries, country_codes, certificates, rating, votes, last_update) SELECT tvdb_id, imdb_id, title, year, akas, runtimes, genres, countries, country_codes, certificates, rating, votes, last_update FROM tmp_imdb_info') + 'INSERT INTO imdb_info(indexer_id, imdb_id, title, year, akas, runtimes, genres, countries, country_codes,' + ' certificates, rating, votes, last_update) SELECT tvdb_id, imdb_id, title, year, akas, runtimes, genres,' + ' countries, country_codes, certificates, rating, votes, last_update FROM tmp_imdb_info') self.connection.action('DROP TABLE tmp_imdb_info') self.incDBVersion() @@ -761,7 +855,8 @@ class ConvertInfoToIndexerScheme(db.SchemaUpgrade): self.connection.action( 'CREATE TABLE info (last_backlog NUMERIC, last_indexer NUMERIC, last_proper_search NUMERIC)') self.connection.action( - 'INSERT INTO info(last_backlog, last_indexer, last_proper_search) SELECT last_backlog, last_tvdb, last_proper_search FROM tmp_info') + 'INSERT INTO info(last_backlog, last_indexer, last_proper_search)' + ' SELECT last_backlog, last_tvdb, last_proper_search FROM tmp_info') self.connection.action('DROP TABLE tmp_info') self.incDBVersion() @@ -791,7 +886,9 @@ class AddSceneNumbering(db.SchemaUpgrade): logger.log(u'Upgrading table scene_numbering ...', logger.MESSAGE) self.connection.action( - 'CREATE TABLE scene_numbering (indexer TEXT, indexer_id INTEGER, season INTEGER, episode INTEGER, scene_season INTEGER, scene_episode INTEGER, PRIMARY KEY (indexer_id,season,episode))') + 'CREATE TABLE scene_numbering (indexer TEXT, indexer_id INTEGER, season INTEGER, episode INTEGER,' + ' scene_season INTEGER, scene_episode INTEGER,' + ' PRIMARY KEY (indexer_id,season,episode))') self.incDBVersion() return self.checkDBVersion() @@ -981,7 +1078,8 @@ class AddIndexerMapping(db.SchemaUpgrade): logger.log(u'Adding table indexer_mapping') self.connection.action( - 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER, mindexer NUMERIC, PRIMARY KEY (indexer_id, indexer))') + 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER, mindexer NUMERIC,' + ' PRIMARY KEY (indexer_id, indexer))') self.incDBVersion() return self.checkDBVersion() @@ -1190,7 +1288,9 @@ class ChangeMapIndexer(db.SchemaUpgrade): logger.log(u'Changing table indexer_mapping') self.connection.action( - 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER NOT NULL, mindexer NUMERIC, date NUMERIC NOT NULL DEFAULT 0, status INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (indexer_id, indexer, mindexer))') + 'CREATE TABLE indexer_mapping (indexer_id INTEGER, indexer NUMERIC, mindexer_id INTEGER NOT NULL,' + ' mindexer NUMERIC, date NUMERIC NOT NULL DEFAULT 0, status INTEGER NOT NULL DEFAULT 0,' + ' PRIMARY KEY (indexer_id, indexer, mindexer))') self.connection.action('CREATE INDEX IF NOT EXISTS idx_mapping ON indexer_mapping (indexer_id, indexer)') @@ -1204,21 +1304,23 @@ class ChangeMapIndexer(db.SchemaUpgrade): self.connection.action('CREATE TABLE scene_exceptions_refresh (list TEXT PRIMARY KEY, last_refreshed INTEGER)') if self.hasTable('scene_exceptions'): self.connection.action('DROP TABLE scene_exceptions') - self.connection.action('CREATE TABLE scene_exceptions (exception_id INTEGER PRIMARY KEY, indexer_id INTEGER KEY, show_name TEXT, season NUMERIC, custom NUMERIC)') + self.connection.action('CREATE TABLE scene_exceptions (exception_id INTEGER PRIMARY KEY,' + ' indexer_id INTEGER KEY, show_name TEXT, season NUMERIC, custom NUMERIC)') try: cachedb = db.DBConnection(filename='cache.db') if cachedb.hasTable('scene_exceptions'): - sqlResults = cachedb.action('SELECT * FROM scene_exceptions') + sql_results = cachedb.action('SELECT * FROM scene_exceptions') cs = [] - for r in sqlResults: - cs.append(['INSERT OR REPLACE INTO scene_exceptions (exception_id, indexer_id, show_name, season, custom)' - ' VALUES (?,?,?,?,?)', [r['exception_id'], r['indexer_id'], r['show_name'], - r['season'], r['custom']]]) + for r in sql_results: + cs.append( + ['INSERT OR REPLACE INTO scene_exceptions (exception_id, indexer_id, show_name, season, custom)' + ' VALUES (?,?,?,?,?)', + [r['exception_id'], r['indexer_id'], r['show_name'], r['season'], r['custom']]]) - if len(cs) > 0: + if 0 < len(cs): self.connection.mass_action(cs) - except: + except (StandardError, Exception): pass keep_tables = {'scene_exceptions', 'scene_exceptions_refresh', 'info', 'indexer_mapping', 'blacklist', @@ -1242,7 +1344,10 @@ class AddShowNotFoundCounter(db.SchemaUpgrade): logger.log(u'Adding table tv_shows_not_found') db.backup_database('sickbeard.db', self.checkDBVersion()) - self.connection.action('CREATE TABLE tv_shows_not_found (indexer NUMERIC NOT NULL, indexer_id NUMERIC NOT NULL, fail_count NUMERIC NOT NULL DEFAULT 0, last_check NUMERIC NOT NULL, last_success NUMERIC, PRIMARY KEY (indexer_id, indexer))') + self.connection.action( + 'CREATE TABLE tv_shows_not_found (indexer NUMERIC NOT NULL, indexer_id NUMERIC NOT NULL,' + ' fail_count NUMERIC NOT NULL DEFAULT 0, last_check NUMERIC NOT NULL, last_success NUMERIC,' + ' PRIMARY KEY (indexer_id, indexer))') self.setDBVersion(20005) return self.checkDBVersion() @@ -1255,7 +1360,7 @@ class AddFlagTable(db.SchemaUpgrade): logger.log(u'Adding table flags') db.backup_database('sickbeard.db', self.checkDBVersion()) - self.connection.action('CREATE TABLE flags (flag PRIMARY KEY NOT NULL )') + self.connection.action('CREATE TABLE flags (flag PRIMARY KEY NOT NULL)') self.setDBVersion(20006) return self.checkDBVersion() @@ -1275,7 +1380,29 @@ class DBIncreaseTo20007(db.SchemaUpgrade): class AddWebdlTypesTable(db.SchemaUpgrade): def execute(self): db.backup_database('sickbeard.db', self.checkDBVersion()) - self.connection.action('CREATE TABLE webdl_types (dname TEXT NOT NULL , regex TEXT NOT NULL )') + self.connection.action('CREATE TABLE webdl_types (dname TEXT NOT NULL, regex TEXT NOT NULL)') self.setDBVersion(20008) return self.checkDBVersion() + + +# 20008 -> 20009 +class AddWatched(db.SchemaUpgrade): + def execute(self): + # remove old table from version 20007 + if self.hasTable('tv_episodes_watched') and not self.hasColumn('tv_episodes_watched', 'clientep_id'): + self.connection.action('DROP TABLE tv_episodes_watched') + self.connection.action('VACUUM') + + if not self.hasTable('tv_episodes_watched'): + logger.log(u'Adding table tv_episodes_watched') + + db.backup_database('sickbeard.db', self.checkDBVersion()) + self.connection.action( + 'CREATE TABLE tv_episodes_watched (tvep_id NUMERIC NOT NULL, clientep_id TEXT, label TEXT,' + ' played NUMERIC DEFAULT 0 NOT NULL, date_watched NUMERIC NOT NULL, date_added NUMERIC,' + ' status NUMERIC, location TEXT, file_size NUMERIC, hide INT default 0 not null)' + ) + + self.setDBVersion(20009) + return self.checkDBVersion() diff --git a/sickbeard/db.py b/sickbeard/db.py index fa439fa..622a8fc 100644 --- a/sickbeard/db.py +++ b/sickbeard/db.py @@ -47,26 +47,35 @@ def dbFilename(filename='sickbeard.db', suffix=None): return ek.ek(os.path.join, sickbeard.DATA_DIR, filename) -def mass_upsert_sql(tableName, valueDict, keyDict): - +def mass_upsert_sql(table_name, value_dict, key_dict, sanitise=True): """ use with cl.extend(mass_upsert_sql(tableName, valueDict, keyDict)) - :param tableName: table name - :param valueDict: dict of values to be set {'table_fieldname': value} - :param keyDict: dict of restrains for update {'table_fieldname': value} + :param table_name: table name + :param value_dict: dict of values to be set {'table_fieldname': value} + :param key_dict: dict of restrains for update {'table_fieldname': value} + :param sanitise: True to remove k, v pairs in keyDict from valueDict as they must not exist in both. + This option has a performance hit so it's best to remove key_dict keys from value_dict and set this False instead. + :type sanitise: Boolean :return: list of 2 sql command """ cl = [] - genParams = lambda myDict: [x + ' = ?' for x in myDict.keys()] + gen_params = (lambda my_dict: [x + ' = ?' for x in my_dict.keys()]) - cl.append(['UPDATE [%s] SET %s WHERE %s' % ( - tableName, ', '.join(genParams(valueDict)), ' AND '.join(genParams(keyDict))), valueDict.values() + keyDict.values()]) + # sanity: remove k, v pairs in keyDict from valueDict + if sanitise: + value_dict = dict(filter(lambda (k, _): k not in key_dict.keys(), value_dict.items())) + cl.append(['UPDATE [%s] SET %s WHERE %s' % + (table_name, ', '.join(gen_params(value_dict)), ' AND '.join(gen_params(key_dict))), + value_dict.values() + key_dict.values()]) - cl.append(['INSERT INTO [' + tableName + '] (' + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in valueDict.keys() + keyDict.keys()]) + ')' + - ' SELECT ' + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in valueDict.values() + keyDict.values()]) + ' WHERE changes() = 0']) + cl.append(['INSERT INTO [' + table_name + '] (' + + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in value_dict.keys() + key_dict.keys()]) + ')' + + ' SELECT ' + + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in value_dict.values() + key_dict.values()]) + + ' WHERE changes() = 0']) return cl @@ -261,12 +270,41 @@ class DBConnection(object): return False def add_flag(self, flag_name): - if not self.has_flag(flag_name): + has_flag = self.has_flag(flag_name) + if not has_flag: self.action('INSERT INTO flags (flag) VALUES (?)', [flag_name]) + return not has_flag def remove_flag(self, flag_name): - if self.has_flag(flag_name): + has_flag = self.has_flag(flag_name) + if has_flag: self.action('DELETE FROM flags WHERE flag = ?', [flag_name]) + return has_flag + + def toggle_flag(self, flag_name): + """ + Add or remove a flag + :param flag_name: Name of flag + :type flag_name: String + :return: True if this call added the flag, False if flag is removed + :rtype: Boolean + """ + if self.remove_flag(flag_name): + return False + self.add_flag(flag_name) + return True + + def set_flag(self, flag_name, state=True): + """ + Set state of flag + :param flag_name: Name of flag + :type flag_name: String + :param state: If true, create flag otherwise remove flag + :type state: Boolean + :return: Previous state of flag + :rtype: Boolean + """ + return (self.add_flag, self.remove_flag)[not bool(state)](flag_name) def close(self): """Close database connection""" @@ -515,6 +553,7 @@ def MigrationCode(myDB): 20005: sickbeard.mainDB.AddFlagTable, 20006: sickbeard.mainDB.DBIncreaseTo20007, 20007: sickbeard.mainDB.AddWebdlTypesTable, + 20008: sickbeard.mainDB.AddWatched, # 20002: sickbeard.mainDB.AddCoolSickGearFeature3, } @@ -532,6 +571,9 @@ def MigrationCode(myDB): else: while db_version < sickbeard.mainDB.MAX_DB_VERSION: + if None is schema[db_version]: # skip placeholders used when multi PRs are updating DB + db_version += 1 + continue try: update = schema[db_version](myDB) db_version = update.execute() diff --git a/sickbeard/helpers.py b/sickbeard/helpers.py index afcbcb8..ed9d795 100644 --- a/sickbeard/helpers.py +++ b/sickbeard/helpers.py @@ -1618,3 +1618,28 @@ def freespace(path=None): pass return result + + +def path_mapper(search, replace, subject): + """ + Substitute strings in a path + + :param search: Search text + :type search: String + :param replace: Replacement text + :type replace: String + :param subject: Path text to search + :type subject: String + :return: Subject with or without substitution, True if a change was made otherwise False + :rtype: Tuple + """ + delim = '/!~!/' + search = re.sub(r'[\\]', delim, search) + replace = re.sub(r'[\\]', delim, replace) + path = re.sub(r'[\\]', delim, subject) + result = re.sub('(?i)^%s' % search, replace, path) + + if re.search(delim, path): + result = os.path.normpath(re.sub(delim, '/', result)) + + return result, result != subject diff --git a/sickbeard/indexers/indexer_api.py b/sickbeard/indexers/indexer_api.py index b105751..8db5af1 100644 --- a/sickbeard/indexers/indexer_api.py +++ b/sickbeard/indexers/indexer_api.py @@ -126,6 +126,11 @@ class indexerApi(object): return dict((int(x['id']), x['name']) for x in indexerConfig.values() if not x['mapped_only']) @property + def search_indexers(self): + return dict((int(x['id']), x['name']) for x in indexerConfig.values() if not x['mapped_only'] and + x.get('active') and not x.get('defunct')) + + @property def all_indexers(self): """ return all indexers including mapped only indexers diff --git a/sickbeard/name_parser/regexes.py b/sickbeard/name_parser/regexes.py index 21cc9c8..acf8534 100644 --- a/sickbeard/name_parser/regexes.py +++ b/sickbeard/name_parser/regexes.py @@ -54,6 +54,21 @@ normal_regexes = [ ''' ), + ('non_standard_multi_ep', + # Show Name - S01E02&03 - My Ep Name + # Show Name - S01E02and03 - My Ep Name + ''' + ^((?P.+?)[. _-]+)? # Show_Name and separator + s(?P\d+)[. _-]* # S01 and optional separator + e(?P\d+) # E02 and separator + (([. _-]*and|&|to) # linking and/&/to + (?P(?!(2160|1080|720|480)[pi])\d+))+ # additional E03/etc + [. _-]*((?P.+?) # Source_Quality_Etc- + ((?[^- ]+))?)?$ # Group + ''' + ), + ('standard', # Show.Name.S01E02.Source.Quality.Etc-Group # Show Name - S01E02 - My Ep Name @@ -73,6 +88,22 @@ normal_regexes = [ ''' ), + ('fov_non_standard_multi_ep', + # Show Name - 1x02and03and04 - My Ep Name + ''' + ^((?P.+?)[\[. _-]+)? # Show_Name and separator + (?P\d+)x # 1x + (?P\d+) # 02 and separator + (([. _-]*and|&|to) # linking x/- char + (?P + (?!(2160|1080|720|480)[pi])(?!(?<=x)264) # ignore obviously wrong multi-eps + \d+))+ # additional x03/etc + [\]. _-]*((?P.+?) # Source_Quality_Etc- + ((?[^- ]+))?)?$ # Group + ''' + ), + ('fov', # Show_Name.1x02.Source_Quality_Etc-Group # Show Name - 1x02 - My Ep Name diff --git a/sickbeard/network_timezones.py b/sickbeard/network_timezones.py index a5076eb..0972b31 100644 --- a/sickbeard/network_timezones.py +++ b/sickbeard/network_timezones.py @@ -295,31 +295,35 @@ def load_network_dict(load=True): # get timezone of a network or return default timezone -def get_network_timezone(network): +def get_network_timezone(network, return_name=False): if network is None: return sb_timezone timezone = None + timezone_name = None try: if zoneinfo.ZONEFILENAME is not None: if not network_dict: load_network_dict() try: - timezone = tz.gettz(network_dupes.get(network) or network_dict.get(network.replace(' ', '').lower()), - zoneinfo_priority=True) - except: + timezone_name = network_dupes.get(network) or network_dict.get(network.replace(' ', '').lower()) + timezone = tz.gettz(timezone_name, zoneinfo_priority=True) + except (StandardError, Exception): pass if timezone is None: cc = re.search(r'\(([a-z]+)\)$', network, flags=re.I) try: - timezone = tz.gettz(country_timezones.get(cc.group(1).upper()), zoneinfo_priority=True) - except: + timezone_name = country_timezones.get(cc.group(1).upper()) + timezone = tz.gettz(timezone_name, zoneinfo_priority=True) + except (StandardError, Exception): pass - except: + except (StandardError, Exception): pass + if return_name: + return timezone if isinstance(timezone, datetime.tzinfo) else sb_timezone, timezone_name return timezone if isinstance(timezone, datetime.tzinfo) else sb_timezone diff --git a/sickbeard/notifiers/emby.py b/sickbeard/notifiers/emby.py index ff1e75b..28ed9c5 100644 --- a/sickbeard/notifiers/emby.py +++ b/sickbeard/notifiers/emby.py @@ -122,7 +122,7 @@ class EmbyNotifier(Notifier): else: new_keys += [key] - apikeys = (new_keys, [x.strip() for x in sickbeard.EMBY_APIKEY.split(',') if x.strip()] + new_keys)[has_old_key] + apikeys = has_old_key and [x.strip() for x in sickbeard.EMBY_APIKEY.split(',') if x.strip()] or [] + new_keys if len(hosts) != len(apikeys): message = ('Not enough Api keys for hosts', 'More Api keys than hosts')[len(apikeys) > len(hosts)] @@ -178,5 +178,10 @@ class EmbyNotifier(Notifier): def discover_server(self): return self._discover_server() + def check_config(self, hosts=None, apikeys=None): + + self._testing = True # ensure _choose() uses passed args + return self._check_config(hosts, apikeys) + notifier = EmbyNotifier diff --git a/sickbeard/processTV.py b/sickbeard/processTV.py index b6b23f9..4208e1c 100644 --- a/sickbeard/processTV.py +++ b/sickbeard/processTV.py @@ -58,10 +58,11 @@ except ImportError: class ProcessTVShow(object): """ Process a TV Show """ - def __init__(self, webhandler=None, is_basedir=True): + def __init__(self, webhandler=None, is_basedir=True, skip_failure_processing=False): self.files_passed = 0 self.files_failed = 0 self.fail_detected = False + self.skip_failure_processing = skip_failure_processing self._output = [] self.webhandler = webhandler self.is_basedir = is_basedir @@ -919,6 +920,10 @@ class ProcessTVShow(object): def _process_failed(self, dir_name, nzb_name, showObj=None): """ Process a download that did not complete correctly """ + if self.skip_failure_processing: + self._log_helper('Download was not added by SickGear, ignoring failure', logger.WARNING) + return + if sickbeard.USE_FAILED_DOWNLOADS: processor = None @@ -947,8 +952,9 @@ class ProcessTVShow(object): # backward compatibility prevents the case of this function name from being updated to PEP8 def processDir(dir_name, nzb_name=None, process_method=None, force=False, force_replace=None, - failed=False, type='auto', cleanup=False, webhandler=None, showObj=None, is_basedir=True): + failed=False, type='auto', cleanup=False, webhandler=None, showObj=None, is_basedir=True, + skip_failure_processing=False): # backward compatibility prevents the case of this function name from being updated to PEP8 - return ProcessTVShow(webhandler, is_basedir).process_dir( + return ProcessTVShow(webhandler, is_basedir, skip_failure_processing=skip_failure_processing).process_dir( dir_name, nzb_name, process_method, force, force_replace, failed, type, cleanup, showObj) diff --git a/sickbeard/providers/__init__.py b/sickbeard/providers/__init__.py index 6d580dd..d5ec1a0 100755 --- a/sickbeard/providers/__init__.py +++ b/sickbeard/providers/__init__.py @@ -29,7 +29,7 @@ from . import newznab, omgwtfnzbs from . import alpharatio, beyondhd, bithdtv, bitmetv, blutopia, btn, btscene, dh, ettv, \ fano, filelist, funfile, gftracker, grabtheinfo, hdbits, hdspace, hdtorrents, \ iptorrents, limetorrents, magnetdl, morethan, nebulance, ncore, nyaa, pisexy, potuk, pretome, privatehd, ptf, \ - rarbg, revtt, scenehd, scenetime, shazbat, skytorrents, speedcd, \ + rarbg, revtt, scenehd, scenetime, shazbat, showrss, skytorrents, speedcd, \ thepiratebay, torlock, torrentbytes, torrentday, torrenting, torrentleech, \ torrentz2, tvchaosuk, wop, zooqle # anime @@ -77,6 +77,7 @@ __all__ = ['omgwtfnzbs', 'scenehd', 'scenetime', 'shazbat', + 'showrss', 'skytorrents', 'speedcd', 'thepiratebay', diff --git a/sickbeard/providers/generic.py b/sickbeard/providers/generic.py index ef11a78..8c68689 100644 --- a/sickbeard/providers/generic.py +++ b/sickbeard/providers/generic.py @@ -100,7 +100,8 @@ class ProviderFailList(object): fail_hour = e.fail_time.time().hour date_time = datetime.datetime.combine(fail_date, datetime.time(hour=fail_hour)) if ProviderFailTypes.names[e.fail_type] not in fail_dict.get(date_time, {}): - default = {'date': str(fail_date), 'date_time': date_time, 'multirow': False} + default = {'date': str(fail_date), 'date_time': date_time, + 'timestamp': helpers.tryInt(sbdatetime.totimestamp(e.fail_time)), 'multirow': False} for et in ProviderFailTypes.names.itervalues(): default[et] = b_d.copy() fail_dict.setdefault(date_time, default)[ProviderFailTypes.names[e.fail_type]]['count'] = 1 @@ -502,8 +503,10 @@ class GenericProvider(object): kwargs['raise_exceptions'] = True kwargs['raise_status_code'] = True - for k, v in dict(headers=self.headers, hooks=dict(response=self.cb_response), session=self.session).items(): + for k, v in dict(headers=self.headers, hooks=dict(response=self.cb_response)).items(): kwargs.setdefault(k, v) + if 'nzbs.in' not in url: # this provider returns 503's 3 out of 4 requests with the persistent session system + kwargs.setdefault('session', self.session) post_data = kwargs.get('post_data') post_json = kwargs.get('post_json') diff --git a/sickbeard/providers/newznab.py b/sickbeard/providers/newznab.py index d1e18f1..facd5e8 100755 --- a/sickbeard/providers/newznab.py +++ b/sickbeard/providers/newznab.py @@ -450,7 +450,8 @@ class NewznabProvider(generic.NZBProvider): r_found = True while r_found: r_found = False - for pattern, repl in ((r'(?i)-Obfuscated$', ''), (r'(?i)-postbot$', ''), (r'(?i)[-.]English$', '')): + for pattern, repl in ((r'(?i)-Scrambled$', ''), (r'(?i)-BUYMORE$', ''), (r'(?i)-Obfuscated$', ''), + (r'(?i)-postbot$', ''), (r'(?i)[-.]English$', '')): if re.search(pattern, title): r_found = True title = re.sub(pattern, repl, title) diff --git a/sickbeard/providers/showrss.py b/sickbeard/providers/showrss.py new file mode 100644 index 0000000..0e0978e --- /dev/null +++ b/sickbeard/providers/showrss.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# +# Author: SickGear +# +# This file is part of SickGear. +# +# SickGear is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# SickGear is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with SickGear. If not, see . + +import re +import traceback + +from . import generic +from sickbeard import logger +from sickbeard.bs4_parser import BS4Parser +from sickbeard.helpers import tryInt, sanitizeSceneName +from lib.unidecode import unidecode +from six.moves.html_parser import HTMLParser + + +class ShowRSSProvider(generic.TorrentProvider): + + def __init__(self): + + generic.TorrentProvider.__init__(self, 'showRSS') + + self.url_base = 'https://showrss.info/' + self.urls = {'config_provider_home_uri': self.url_base, + 'login_action': self.url_base + 'login', + 'browse': self.url_base + 'browse/all', + 'search': self.url_base + 'browse/%s'} + + self.url = self.urls['config_provider_home_uri'] + + self.username, self.password, self.shows = 3 * [None] + + def _authorised(self, **kwargs): + + return super(ShowRSSProvider, self)._authorised(logged_in=(lambda y=None: self.logged_in(y))) + + def logged_in(self, y): + if all([None is y or 'logout' in y, + bool(filter(lambda c: 'remember_web_' in c, self.session.cookies.keys()))]): + if None is not y: + self.shows = dict(re.findall('', y)) + h = HTMLParser() + for k, v in self.shows.items(): + self.shows[k] = sanitizeSceneName(h.unescape(unidecode(v.decode('utf-8')))) + return True + return False + + def _search_provider(self, search_params, **kwargs): + + results = [] + if not self._authorised(): + return results + + items = {'Cache': [], 'Season': [], 'Episode': [], 'Propers': []} + + rc = dict((k, re.compile('(?i)' + v)) for (k, v) in {'get': 'magnet'}.items()) + urls = [] + for mode in search_params.keys(): + for search_string in search_params[mode]: + if 'Cache' == mode: + search_url = self.urls['browse'] + else: + search_string = isinstance(search_string, unicode) and unidecode(search_string) or search_string + show_name = filter(lambda x: x.lower() == re.sub('\s.*', '', search_string.lower()), + self.shows.values()) + if not show_name: + continue + search_url = self.urls['search'] % self.shows.keys()[self.shows.values().index(show_name[0])] + + if search_url in urls: + continue + urls += [search_url] + + html = self.get_url(search_url) + if self.should_skip(): + return results + + cnt = len(items[mode]) + try: + if not html or self._has_no_results(html): + raise generic.HaltParseException + + with BS4Parser(html, features=['html5lib', 'permissive']) as soup: + torrent_rows = soup.select('ul.user-timeline > li') + + if not len(torrent_rows): + raise generic.HaltParseException + + for tr in torrent_rows: + try: + anchor = tr.find('a', href=rc['get']) + title = self.regulate_title(anchor) + download_url = self._link(anchor['href']) + except (AttributeError, TypeError, ValueError): + continue + + if title and download_url: + items[mode].append((title, download_url, None, None)) + + except generic.HaltParseException: + pass + except (StandardError, Exception): + logger.log(u'Failed to parse. Traceback: %s' % traceback.format_exc(), logger.ERROR) + self._log_search(mode, len(items[mode]) - cnt, search_url) + + results = self._sort_seeding(mode, results + items[mode]) + + return results + + @staticmethod + def regulate_title(anchor): + title = '' + t1 = anchor.attrs.get('title').strip() + t2 = anchor.get_text().strip() + diff, x, offset = 0, 0, 0 + for x, c in enumerate(t2): + if c.lower() == t1[x-offset].lower(): + title += t1[x-offset] + diff = 0 + elif ' ' != c and ' ' == t1[x-offset]: + title += c + diff = 0 + if ' ' == t2[x+1]: + offset += 1 + else: + diff += 1 + if 1 < diff: + break + return '%s%s' % (title, re.sub('(?i)(xvid|divx|[hx].?26[45])\s(\w+)$', r'\1-\2', + ''.join(t1[x - (offset + diff)::]).strip())) + + @staticmethod + def ui_string(key): + + return ('showrss_tip' == key + and 'lists are not needed, the SickGear list is used as usual' or '') + + +provider = ShowRSSProvider() diff --git a/sickbeard/sbdatetime.py b/sickbeard/sbdatetime.py index 34bdab1..3566e64 100644 --- a/sickbeard/sbdatetime.py +++ b/sickbeard/sbdatetime.py @@ -113,10 +113,10 @@ class sbdatetime(datetime.datetime): 'july', 'august', 'september', 'october', 'november', 'december']) @static_or_instance - def convert_to_setting(self, dt=None): + def convert_to_setting(self, dt=None, force_local=False): obj = (dt, self)[self is not None] try: - if 'local' == sickbeard.TIMEZONE_DISPLAY: + if force_local or 'local' == sickbeard.TIMEZONE_DISPLAY: return obj.astimezone(sb_timezone) except (StandardError, Exception): pass diff --git a/sickbeard/scene_numbering.py b/sickbeard/scene_numbering.py index f4a8988..4a2da32 100644 --- a/sickbeard/scene_numbering.py +++ b/sickbeard/scene_numbering.py @@ -694,3 +694,66 @@ def fix_xem_numbering(indexer_id, indexer): if 0 < len(cl): my_db = db.DBConnection() my_db.mass_action(cl) + + +def set_scene_numbering_helper(indexerid, indexer, forSeason=None, forEpisode=None, forAbsolute=None, + sceneSeason=None, sceneEpisode=None, sceneAbsolute=None): + # sanitize: + indexerid = None if indexerid in [None, 'null', ''] else int(indexerid) + indexer = None if indexer in [None, 'null', ''] else int(indexer) + + show_obj = sickbeard.helpers.find_show_by_id(sickbeard.showList, {indexer: indexerid}, no_mapped_ids=True) + + if not show_obj: + result = {'success': False} + return result + + if not show_obj.is_anime: + for_season = None if forSeason in [None, 'null', ''] else int(forSeason) + for_episode = None if forEpisode in [None, 'null', ''] else int(forEpisode) + scene_season = None if sceneSeason in [None, 'null', ''] else int(sceneSeason) + scene_episode = None if sceneEpisode in [None, 'null', ''] else int(sceneEpisode) + action_log = u'Set episode scene numbering to %sx%s for episode %sx%s of "%s"' \ + % (scene_season, scene_episode, for_season, for_episode, show_obj.name) + ep_args = {'show': indexerid, 'season': for_season, 'episode': for_episode} + scene_args = {'indexer_id': indexerid, 'indexer': indexer, 'season': for_season, 'episode': for_episode, + 'sceneSeason': scene_season, 'sceneEpisode': scene_episode} + result = {'forSeason': for_season, 'forEpisode': for_episode, 'sceneSeason': None, 'sceneEpisode': None} + else: + for_absolute = None if forAbsolute in [None, 'null', ''] else int(forAbsolute) + scene_absolute = None if sceneAbsolute in [None, 'null', ''] else int(sceneAbsolute) + action_log = u'Set absolute scene numbering to %s for episode %s of "%s"' \ + % (scene_absolute, for_absolute, show_obj.name) + ep_args = {'show': indexerid, 'absolute': for_absolute} + scene_args = {'indexer_id': indexerid, 'indexer': indexer, 'absolute_number': for_absolute, + 'sceneAbsolute': scene_absolute} + result = {'forAbsolute': for_absolute, 'sceneAbsolute': None} + + if ep_args.get('absolute'): + ep_obj = show_obj.getEpisode(absolute_number=int(ep_args['absolute'])) + elif None is not ep_args['season'] and None is not ep_args['episode']: + ep_obj = show_obj.getEpisode(int(ep_args['season']), int(ep_args['episode'])) + else: + ep_obj = 'Invalid paramaters' + + if ep_obj is None: + ep_obj = "Episode couldn't be retrieved" + + result['success'] = not isinstance(ep_obj, str) + if result['success']: + logger.log(action_log, logger.DEBUG) + set_scene_numbering(**scene_args) + show_obj.flushEpisodes() + else: + result['errorMessage'] = ep_obj + + if not show_obj.is_anime: + scene_numbering = get_scene_numbering(indexerid, indexer, for_season, for_episode) + if scene_numbering: + (result['sceneSeason'], result['sceneEpisode']) = scene_numbering + else: + scene_numbering = get_scene_absolute_numbering(indexerid, indexer, for_absolute) + if scene_numbering: + result['sceneAbsolute'] = scene_numbering + + return result \ No newline at end of file diff --git a/sickbeard/scheduler.py b/sickbeard/scheduler.py index 7724a6b..ebdfc04 100644 --- a/sickbeard/scheduler.py +++ b/sickbeard/scheduler.py @@ -55,14 +55,13 @@ class Scheduler(threading.Thread): self._stop.set() self.unpause() - def check_paused(self): - if hasattr(self.action, 'check_paused'): - if self.action.check_paused(): + def set_paused_state(self): + if hasattr(self.action, 'is_enabled'): + self.silent = not self.action.is_enabled() + if self.silent: self.pause() - self.silent = True else: self.unpause() - self.silent = False def timeLeft(self): return self.cycleTime - (datetime.datetime.now() - self.lastRun) @@ -74,55 +73,60 @@ class Scheduler(threading.Thread): return False def run(self): - self.check_paused() + self.set_paused_state() # if self._unpause Event() is NOT set the loop pauses while self._unpause.wait() and not self._stop.is_set(): - try: - current_time = datetime.datetime.now() - should_run = False + if getattr(self.action, 'is_enabled', True): + try: + current_time = datetime.datetime.now() + should_run = False - # check if interval has passed - if current_time - self.lastRun >= self.cycleTime: - # check if wanting to start around certain time taking interval into account - if self.start_time: - hour_diff = current_time.time().hour - self.start_time.hour - if not hour_diff < 0 and hour_diff < self.cycleTime.seconds / 3600: - should_run = True + # check if interval has passed + if current_time - self.lastRun >= self.cycleTime: + # check if wanting to start around certain time taking interval into account + if self.start_time: + hour_diff = current_time.time().hour - self.start_time.hour + if not hour_diff < 0 and hour_diff < self.cycleTime.seconds / 3600: + should_run = True + else: + # set lastRun to only check start_time after another cycleTime + self.lastRun = current_time else: - # set lastRun to only check start_time after another cycleTime - self.lastRun = current_time - else: - should_run = True + should_run = True - if self.force: - should_run = True + if self.force: + should_run = True - if should_run and self.prevent_cycle_run is not None and self.prevent_cycle_run(): - logger.log(u'%s skipping this cycleTime' % self.name, logger.WARNING) - # set lastRun to only check start_time after another cycleTime - self.lastRun = current_time - should_run = False + if should_run and ((self.prevent_cycle_run is not None and self.prevent_cycle_run()) or + getattr(self.action, 'prevent_run', False)): + logger.log(u'%s skipping this cycleTime' % self.name, logger.WARNING) + # set lastRun to only check start_time after another cycleTime + self.lastRun = current_time + should_run = False - if should_run: - self.lastRun = current_time + if should_run: + self.lastRun = current_time - try: - if not self.silent: - logger.log(u"Starting new thread: " + self.name, logger.DEBUG) + try: + if not self.silent: + logger.log(u"Starting new thread: " + self.name, logger.DEBUG) - self.action.run() - except Exception as e: - logger.log(u"Exception generated in thread " + self.name + ": " + ex(e), logger.ERROR) - logger.log(repr(traceback.format_exc()), logger.ERROR) + self.action.run() + except Exception as e: + logger.log(u"Exception generated in thread " + self.name + ": " + ex(e), logger.ERROR) + logger.log(repr(traceback.format_exc()), logger.ERROR) - finally: - if self.force: - self.force = False + finally: + if self.force: + self.force = False + else: + # disabled schedulers will only be rechecked every 30 seconds until enabled + time.sleep(30) time.sleep(1) # exiting thread self._stop.clear() - self._unpause.clear() \ No newline at end of file + self._unpause.clear() diff --git a/sickbeard/search_propers.py b/sickbeard/search_propers.py index 51b5705..8c36337 100644 --- a/sickbeard/search_propers.py +++ b/sickbeard/search_propers.py @@ -28,10 +28,8 @@ class ProperSearcher: self.amActive = False @staticmethod - def check_paused(): - if sickbeard.DOWNLOAD_PROPERS: - return False - return True + def is_enabled(): + return sickbeard.DOWNLOAD_PROPERS def run(self): diff --git a/sickbeard/subtitles.py b/sickbeard/subtitles.py index 1989c0c..9ce797f 100644 --- a/sickbeard/subtitles.py +++ b/sickbeard/subtitles.py @@ -49,10 +49,10 @@ def sortedServiceList(): newList.append(curServiceDict) return newList - + def getEnabledServiceList(): return [x['name'] for x in sortedServiceList() if x['enabled']] - + def isValidLanguage(language): return subliminal.language.language_list(language) @@ -81,18 +81,26 @@ def subtitlesLanguages(video_path): def subtitleLanguageFilter(): return [language for language in subliminal.language.LANGUAGES if language[2] != ""] -class SubtitlesFinder(): + +class SubtitlesFinder: """ The SubtitlesFinder will be executed every hour but will not necessarly search and download subtitles. Only if the defined rule is true """ + def __init__(self): + self.amActive = False + @staticmethod - def check_paused(): - if sickbeard.USE_SUBTITLES: - return False - return True + def is_enabled(): + return sickbeard.USE_SUBTITLES + + def run(self): + if self.is_enabled(): + self.amActive = True + self._main() + self.amActive = False - def run(self, force=False): + def _main(self): if len(sickbeard.subtitles.getEnabledServiceList()) < 1: logger.log(u'Not enough services selected. At least 1 service is required to search subtitles in the background', logger.ERROR) return @@ -100,7 +108,7 @@ class SubtitlesFinder(): logger.log(u'Checking for subtitles', logger.MESSAGE) # get episodes on which we want subtitles - # criteria is: + # criteria is: # - show subtitles = 1 # - episode subtitles != config wanted languages or SINGLE (depends on config multi) # - search count < 2 and diff(airdate, now) > 1 week : now -> 1d @@ -114,7 +122,7 @@ class SubtitlesFinder(): if len(sqlResults) == 0: logger.log('No subtitles to download', logger.MESSAGE) return - + rules = self._getRules() now = datetime.datetime.now() for epToSub in sqlResults: @@ -122,26 +130,26 @@ class SubtitlesFinder(): if not ek.ek(os.path.isfile, epToSub['location']): logger.log('Episode file does not exist, cannot download subtitles for episode %dx%d of show %s' % (epToSub['season'], epToSub['episode'], epToSub['show_name']), logger.DEBUG) continue - + # Old shows rule throwaway = datetime.datetime.strptime('20110101', '%Y%m%d') if ((epToSub['airdate_daydiff'] > 7 and epToSub['searchcount'] < 2 and now - datetime.datetime.strptime(epToSub['lastsearch'], '%Y-%m-%d %H:%M:%S') > datetime.timedelta(hours=rules['old'][epToSub['searchcount']])) or - # Recent shows rule + # Recent shows rule (epToSub['airdate_daydiff'] <= 7 and epToSub['searchcount'] < 7 and now - datetime.datetime.strptime(epToSub['lastsearch'], '%Y-%m-%d %H:%M:%S') > datetime.timedelta(hours=rules['new'][epToSub['searchcount']]))): logger.log('Downloading subtitles for episode %dx%d of show %s' % (epToSub['season'], epToSub['episode'], epToSub['show_name']), logger.DEBUG) - + showObj = helpers.findCertainShow(sickbeard.showList, int(epToSub['showid'])) if not showObj: logger.log(u'Show not found', logger.DEBUG) return - + epObj = showObj.getEpisode(int(epToSub["season"]), int(epToSub["episode"])) if isinstance(epObj, str): logger.log(u'Episode not found', logger.DEBUG) return - + previous_subtitles = epObj.subtitles - + try: subtitles = epObj.downloadSubtitles() except: diff --git a/sickbeard/watchedstate.py b/sickbeard/watchedstate.py new file mode 100644 index 0000000..a32fc8b --- /dev/null +++ b/sickbeard/watchedstate.py @@ -0,0 +1,60 @@ +# +# This file is part of SickGear. +# +# SickGear is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# SickGear is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with SickGear. If not, see . + +import threading + +import sickbeard +from sickbeard import watchedstate_queue + + +class WatchedStateUpdater(object): + def __init__(self, name, queue_item): + + self.amActive = False + self.lock = threading.Lock() + self.name = name + self.queue_item = queue_item + + @property + def prevent_run(self): + return sickbeard.watchedStateQueueScheduler.action.is_in_queue(self.queue_item) + + def run(self): + if self.is_enabled(): + self.amActive = True + new_item = self.queue_item() + sickbeard.watchedStateQueueScheduler.action.add_item(new_item) + self.amActive = False + + +class EmbyWatchedStateUpdater(WatchedStateUpdater): + + def __init__(self): + super(EmbyWatchedStateUpdater, self).__init__('Emby', watchedstate_queue.EmbyWatchedStateQueueItem) + + @staticmethod + def is_enabled(): + return sickbeard.USE_EMBY and sickbeard.EMBY_WATCHEDSTATE_SCHEDULED + + +class PlexWatchedStateUpdater(WatchedStateUpdater): + + def __init__(self): + super(PlexWatchedStateUpdater, self).__init__('Plex', watchedstate_queue.PlexWatchedStateQueueItem) + + @staticmethod + def is_enabled(): + return sickbeard.USE_PLEX and sickbeard.PLEX_WATCHEDSTATE_SCHEDULED diff --git a/sickbeard/watchedstate_queue.py b/sickbeard/watchedstate_queue.py new file mode 100644 index 0000000..2df9cea --- /dev/null +++ b/sickbeard/watchedstate_queue.py @@ -0,0 +1,83 @@ +# +# This file is part of SickGear. +# +# SickGear is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# SickGear is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with SickGear. If not, see . + +from __future__ import with_statement + +from sickbeard import generic_queue, logger +from sickbeard.webserve import History + +EMBYWATCHEDSTATE = 10 +PLEXWATCHEDSTATE = 20 + + +class WatchedStateQueue(generic_queue.GenericQueue): + def __init__(self): + super(WatchedStateQueue, self).__init__() + # self.queue_name = 'WATCHEDSTATEQUEUE' + self.queue_name = 'Q' + + def is_in_queue(self, itemtype): + with self.lock: + for cur_item in self.queue + [self.currentItem]: + if isinstance(cur_item, itemtype): + return True + return False + + # method for possible UI usage, can be removed if not used + def queue_length(self): + length = {'emby': 0, 'plex': 0} + with self.lock: + for cur_item in [self.currentItem] + self.queue: + if isinstance(cur_item, EmbyWatchedStateQueueItem): + length['emby'] += 1 + elif isinstance(cur_item, PlexWatchedStateQueueItem): + length['plex'] += 1 + + return length + + def add_item(self, item): + if isinstance(item, EmbyWatchedStateQueueItem) and not self.is_in_queue(EmbyWatchedStateQueueItem): + # emby watched state item + generic_queue.GenericQueue.add_item(self, item) + elif isinstance(item, PlexWatchedStateQueueItem) and not self.is_in_queue(PlexWatchedStateQueueItem): + # plex watched state item + generic_queue.GenericQueue.add_item(self, item) + else: + logger.log(u'Not adding item, it\'s already in the queue', logger.DEBUG) + + +class EmbyWatchedStateQueueItem(generic_queue.QueueItem): + def __init__(self): + super(EmbyWatchedStateQueueItem, self).__init__('Emby Watched', EMBYWATCHEDSTATE) + + def run(self): + super(EmbyWatchedStateQueueItem, self).run() + try: + History.update_watched_state_emby() + finally: + self.finish() + + +class PlexWatchedStateQueueItem(generic_queue.QueueItem): + def __init__(self): + super(PlexWatchedStateQueueItem, self).__init__('Plex Watched', PLEXWATCHEDSTATE) + + def run(self): + super(PlexWatchedStateQueueItem, self).run() + try: + History.update_watched_state_plex() + finally: + self.finish() diff --git a/sickbeard/webapi.py b/sickbeard/webapi.py index b7c5ffa..979de40 100644 --- a/sickbeard/webapi.py +++ b/sickbeard/webapi.py @@ -27,6 +27,10 @@ import re import traceback import sickbeard import webserve +import glob + +from mimetypes import MimeTypes +from random import randint from sickbeard import db, logger, exceptions, history, ui, helpers from sickbeard import encodingKludge as ek @@ -35,12 +39,16 @@ from sickbeard import image_cache from sickbeard import classes from sickbeard import processTV from sickbeard import network_timezones, sbdatetime -from sickbeard.exceptions import ex +from sickbeard.exceptions import ex, MultipleShowObjectsException from sickbeard.common import SNATCHED, SNATCHED_ANY, SNATCHED_PROPER, SNATCHED_BEST, DOWNLOADED, SKIPPED, UNAIRED, IGNORED, ARCHIVED, WANTED, UNKNOWN from sickbeard.helpers import remove_article +from sickbeard.scene_numbering import set_scene_numbering_helper from common import Quality, qualityPresetStrings, statusStrings from sickbeard.indexers.indexer_config import * -from sickbeard.webserve import MainHandler +from sickbeard.indexers import indexer_config, indexer_api +from tornado import gen +from sickbeard.search_backlog import FORCED_BACKLOG +from sickbeard.webserve import NewHomeAddShows try: import json @@ -49,6 +57,7 @@ except ImportError: from lib import subliminal + dateFormat = "%Y-%m-%d" dateTimeFormat = "%Y-%m-%d %H:%M" timeFormat = '%A %I:%M %p' @@ -68,10 +77,24 @@ result_type_map = {RESULT_SUCCESS: "success", } # basically everything except RESULT_SUCCESS / success is bad +quality_map = {'sdtv': Quality.SDTV, + 'sddvd': Quality.SDDVD, + 'hdtv': Quality.HDTV, + 'rawhdtv': Quality.RAWHDTV, + 'fullhdtv': Quality.FULLHDTV, + 'hdwebdl': Quality.HDWEBDL, + 'fullhdwebdl': Quality.FULLHDWEBDL, + 'hdbluray': Quality.HDBLURAY, + 'fullhdbluray': Quality.FULLHDBLURAY, + 'uhd4kweb': Quality.UHD4KWEB, + 'unknown': Quality.UNKNOWN} + +quality_map_inversed = {v: k for k, v in quality_map.iteritems()} + class Api(webserve.BaseHandler): """ api class that returns json results """ - version = 4 # use an int since float-point is unpredictible + version = 10 # use an int since float-point is unpredictible intent = 4 def set_default_headers(self): @@ -79,13 +102,29 @@ class Api(webserve.BaseHandler): self.set_header('X-Robots-Tag', 'noindex, nofollow, noarchive, nocache, noodp, noydir, noimageindex, nosnippet') if sickbeard.SEND_SECURITY_HEADERS: self.set_header('X-Frame-Options', 'SAMEORIGIN') + self.set_header('X-Application', 'SickGear') + self.set_header('X-API-Version', Api.version) + def prepare(self): + # Incorporate request JSON into arguments dictionary. + if self.request.body: + try: + json_data = {'payloadjson': json.loads(self.request.body)} + self.request.arguments.update(json_data) + except (StandardError, Exception): + raise ApiError('Unable to parse JSON.') + super(Api, self).prepare() + + def post(self, route, *args, **kwargs): + return self.get(route, *args, **kwargs) + + @gen.coroutine def get(self, route, *args, **kwargs): route = route.strip('/') or 'index' kwargs = self.request.arguments for arg, value in kwargs.items(): - if len(value) == 1: + if not isinstance(value, dict) and len(value) == 1: kwargs[arg] = value[0] args = args[1:] @@ -287,6 +326,19 @@ class ApiCall(object): # RequestHandler self.handler = handler + # old sickbeard call + self._sickbeard_call = getattr(self, '_sickbeard_call', False) + + @property + def sickbeard_call(self): + if hasattr(self, '_sickbeard_call'): + return self._sickbeard_call + return False + + @sickbeard_call.setter + def sickbeard_call(self, v): + self._sickbeard_call = v + def run(self): # override with real output function in subclass return {} @@ -335,13 +387,13 @@ class ApiCall(object): msg = "The required parameters: '" + "','".join(self._missing) + "' where not set" return _responds(RESULT_ERROR, msg=msg) - def check_params(self, args, kwargs, key, default, required, type, allowedValues): + def check_params(self, args, kwargs, key, default, required, type, allowedValues, sub_type=None): # TODO: explain this """ function to check passed params for the shorthand wrapper and to detect missing/required param """ # Fix for applications that send tvdbid instead of indexerid - if key == "indexerid" and "indexerid" not in kwargs: + if self.sickbeard_call and key == "indexerid" and "indexerid" not in kwargs: key = "tvdbid" missing = True @@ -360,7 +412,8 @@ class ApiCall(object): if required: try: self._missing - self._requiredParams.append(key) + self._requiredParams[key] = {"allowedValues": allowedValues, + "defaultValue": orgDefault} except AttributeError: self._missing = [] self._requiredParams = {} @@ -378,14 +431,14 @@ class ApiCall(object): "defaultValue": orgDefault} if default: - default = self._check_param_type(default, key, type) + default = self._check_param_type(default, key, type, sub_type) if type == "bool": type = [] self._check_param_value(default, key, allowedValues) return default, args - def _check_param_type(self, value, name, type): + def _check_param_type(self, value, name, type, sub_type): """ checks if value can be converted / parsed to type will raise an error on failure or will convert it to type and return new converted value @@ -412,7 +465,34 @@ class ApiCall(object): else: error = True elif type == "list": - value = value.split("|") + if None is not sub_type: + if sub_type in (int, long): + if isinstance(value, (int, long)): + value = [value] + elif isinstance(value, basestring): + if '|' in value: + li = [int(v) for v in value.split('|')] + if any([not isinstance(v, (int, long)) for v in li]): + error = True + else: + value = li + else: + value = [int(value)] + else: + error = True + else: + li = value.split('|') + if any([sub_type is not type(v) for v in li]): + error = True + else: + value = li + else: + value = value.split("|") + elif type == "dict": + if isinstance(value, dict): + value = value + else: + error = True elif type == "string": pass elif type == "ignore": @@ -589,17 +669,7 @@ def _mapQuality(showObj): def _getQualityMap(): - return {Quality.SDTV: 'sdtv', - Quality.SDDVD: 'sddvd', - Quality.HDTV: 'hdtv', - Quality.RAWHDTV: 'rawhdtv', - Quality.FULLHDTV: 'fullhdtv', - Quality.HDWEBDL: 'hdwebdl', - Quality.FULLHDWEBDL: 'fullhdwebdl', - Quality.HDBLURAY: 'hdbluray', - Quality.FULLHDBLURAY: 'fullhdbluray', - Quality.UNKNOWN: 'unknown'} - + return quality_map_inversed def _getRootDirs(): if sickbeard.ROOT_DIRS == "": @@ -651,6 +721,83 @@ class IntParseError(Exception): # -------------------------------------------------------------------------------------# +class CMD_ListCommands(ApiCall): + _help = {"desc": "list help of all commands", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ display help information for all commands """ + out = '' + table_sickgear_commands = '' + table_sickbeard_commands = '' + for f, v in sorted(_functionMaper.iteritems(), key=lambda x: (re.sub(r'^s[bg]\.', '', x[0], flags=re.I), re.sub(r'^sg\.', '1', x[0], flags=re.I))): + if 'listcommands' == f: + continue + help = getattr(v, '_help', None) + is_old_command = isinstance(help, dict) and "SickGearCommand" in help + if is_old_command: + table_sickbeard_commands += '' % f + else: + table_sickgear_commands += '' % f + color = ("", " style='color: grey !important;'")[is_old_command] + out += '

%s%s

' % (color, f, ("", " (Sickbeard compatibility command)")[is_old_command]) + if isinstance(help, dict): + sg_c = '' + if "SickGearCommand" in help: + sg_c += '' % help['SickGearCommand'] + out += "

for all features use SickGear API Command: %s

" % help['SickGearCommand'] + if "desc" in help: + if is_old_command: + table_sickbeard_commands += '%s' % (help['desc'], sg_c) + else: + table_sickgear_commands += '' % help['desc'] + out += help['desc'] + + table = '' + + if "requiredParameters" in help and isinstance(help['requiredParameters'], dict): + for p, d in help['requiredParameters'].iteritems(): + des = '' + if isinstance(d, dict) and 'desc' in d: + des = d.get('desc') + table += "" % (p, des) + + if "optionalParameters" in help and isinstance(help['optionalParameters'], dict): + for p, d in help['optionalParameters'].iteritems(): + des = '' + if isinstance(d, dict) and 'desc' in d: + des = d.get('desc') + table += "" % (p, des) + if table: + out += "
%s
%s%s%s%s
%s required

%s

%s optional

%s

" + out += table + out += '
ParameterDescription
' + else: + if is_old_command: + table_sickbeard_commands += '%s' % 'no description' + else: + table_sickgear_commands += '%s' % 'no description' + + if is_old_command: + table_sickbeard_commands += '' + else: + table_sickgear_commands += '' + + if table_sickbeard_commands: + out = "

SickBeard Commands (compatibility):

" + table_sickbeard_commands + '
CommandDescriptionReplacement SickGear Command
' + out + + if table_sickgear_commands: + out = "

SickGear Commands:

" + table_sickgear_commands + '
CommandDescription
' + out + + return out + class CMD_Help(ApiCall): _help = {"desc": "display help information for a given subject/command", @@ -673,7 +820,7 @@ class CMD_Help(ApiCall): return out -class CMD_ComingEpisodes(ApiCall): +class CMD_SickGearComingEpisodes(ApiCall): _help = {"desc": "display the coming episodes", "optionalParameters": {"sort": {"desc": "change the sort order"}, "type": {"desc": "one or more of allowedValues separated by |"}, @@ -709,28 +856,51 @@ class CMD_ComingEpisodes(ApiCall): myDB = db.DBConnection() sql_results = myDB.select( - "SELECT airdate, airs, episode, name AS 'ep_name', description AS 'ep_plot', network, season, showid AS 'indexerid', show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', tv_shows.paused AS 'paused' FROM tv_episodes, tv_shows WHERE season != 0 AND airdate >= ? AND airdate <= ? AND tv_shows.indexer_id = tv_episodes.showid AND tv_episodes.status NOT IN (" + ','.join( - ['?'] * len(qualList)) + ")", [yesterday, next_week] + qualList) + "SELECT airdate, airs, runtime, tv_shows.indexer AS 'indexer', episode, name AS 'ep_name', " + "tv_episodes.status as 'status', description AS 'ep_plot', network, season, showid AS 'indexerid', " + "show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', " + "tv_shows.paused AS 'paused' FROM tv_episodes, tv_shows WHERE " + + ("", "tv_shows.indexer = %s AND " % INDEXER_TVDB)[self.sickbeard_call] + + "season != 0 AND airdate >= ? AND " + "airdate <= ? AND tv_shows.indexer_id = tv_episodes.showid AND tv_shows.indexer == tv_episodes.indexer AND " + "tv_episodes.status NOT IN (" + ','.join(['?'] * len(qualList)) + ")", [yesterday, next_week] + qualList) for cur_result in sql_results: - done_show_list.append(int(cur_result["indexerid"])) - - more_sql_results = myDB.select( - "SELECT airdate, airs, episode, name AS 'ep_name', description AS 'ep_plot', network, season, showid AS 'indexerid', show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', tv_shows.paused AS 'paused' FROM tv_episodes outer_eps, tv_shows WHERE season != 0 AND showid NOT IN (" + ','.join( - ['?'] * len( - done_show_list)) + ") AND tv_shows.indexer_id = outer_eps.showid AND airdate = (SELECT airdate FROM tv_episodes inner_eps WHERE inner_eps.season != 0 AND inner_eps.showid = outer_eps.showid AND inner_eps.airdate >= ? ORDER BY inner_eps.airdate ASC LIMIT 1) AND outer_eps.status NOT IN (" + ','.join( - ['?'] * len(Quality.DOWNLOADED + Quality.SNATCHED)) + ")", - done_show_list + [next_week] + Quality.DOWNLOADED + Quality.SNATCHED) + done_show_list.append((int(cur_result["indexerid"]), int(cur_result["indexer"]))) + + more_sql_results = [m for m in myDB.select( + "SELECT airdate, airs, runtime, tv_shows.indexer AS 'indexer', episode, name AS 'ep_name', " + "outer_eps.status as 'status', description AS 'ep_plot', network, season, showid AS 'indexerid', " + "show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', " + "tv_shows.paused AS 'paused' FROM tv_episodes outer_eps, tv_shows WHERE " + + ("", "tv_shows.indexer = %s AND " % INDEXER_TVDB)[self.sickbeard_call] + + "season != 0 AND " + "tv_shows.indexer_id = outer_eps.showid AND tv_shows.indexer == outer_eps.indexer AND " + "airdate = (SELECT airdate FROM tv_episodes inner_eps WHERE inner_eps.season != 0 AND " + "inner_eps.showid = outer_eps.showid AND inner_eps.indexer == outer_eps.indexer AND " + "inner_eps.airdate >= ? ORDER BY inner_eps.airdate ASC LIMIT 1) AND " + "outer_eps.status NOT IN (" + ','.join(['?'] * len(Quality.DOWNLOADED + Quality.SNATCHED)) + ")", + [next_week] + Quality.DOWNLOADED + Quality.SNATCHED) if (int(m['indexerid']), int(m['indexer'])) + not in done_show_list] sql_results += more_sql_results more_sql_results = myDB.select( - "SELECT airdate, airs, episode, name AS 'ep_name', description AS 'ep_plot', network, season, showid AS 'indexerid', show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', tv_shows.paused AS 'paused' FROM tv_episodes, tv_shows WHERE season != 0 AND tv_shows.indexer_id = tv_episodes.showid AND airdate <= ? AND airdate >= ? AND tv_episodes.status = ? AND tv_episodes.status NOT IN (" + ','.join( + "SELECT airdate, airs, runtime, tv_shows.indexer AS 'indexer', episode, name AS 'ep_name', " + "tv_episodes.status as 'status', description AS 'ep_plot', network, season, showid AS 'indexerid', " + "show_name, tv_shows.quality AS quality, tv_shows.status AS 'show_status', " + "tv_shows.paused AS 'paused' FROM tv_episodes, tv_shows WHERE " + + ("", "tv_shows.indexer = %s AND " % INDEXER_TVDB)[self.sickbeard_call] + + "season != 0 AND tv_shows.indexer_id = tv_episodes.showid AND tv_shows.indexer == tv_episodes.indexer AND " + "airdate <= ? AND airdate >= ? AND " + "tv_episodes.status = ? AND tv_episodes.status NOT IN (" + ','.join( ['?'] * len(qualList)) + ")", [tomorrow, recently, WANTED] + qualList) sql_results += more_sql_results sql_results = list(set(sql_results)) # make a dict out of the sql results - sql_results = [dict(row) for row in sql_results] + sql_results = [dict(row) for row in sql_results + if Quality.splitCompositeStatus(helpers.tryInt(row['status']))[0] not in + [DOWNLOADED, SNATCHED, SNATCHED_PROPER, SNATCHED_BEST, ARCHIVED, IGNORED, SKIPPED]] # multi dimension sort sorts = { @@ -752,9 +922,15 @@ class CMD_ComingEpisodes(ApiCall): # add parsed_datetime to the dict for index, item in enumerate(sql_results): - sql_results[index]['parsed_datetime'] = network_timezones.parse_date_time(item['airdate'], item['airs'], item['network']) + timezone, sql_results[index]['timezone'] = network_timezones.get_network_timezone(item['network'], + return_name=True) + p_t = network_timezones.parse_date_time(item['airdate'], item['airs'], timezone) + sql_results[index]['parsed_datetime'] = p_t + sql_results[index]['local_datetime'] = sbdatetime.sbdatetime.sbstrftime( + sbdatetime.sbdatetime.convert_to_setting(p_t, force_local=True), dateTimeFormat) sql_results[index]['data_show_name'] = value_maybe_article(item['show_name']) sql_results[index]['data_network'] = value_maybe_article(item['network']) + sql_results[index]['status_str'] = statusStrings[item['status']] sql_results.sort(sorts[self.sort]) @@ -801,7 +977,14 @@ class CMD_ComingEpisodes(ApiCall): # start day of the week on 1 (monday) ep['weekday'] = 1 + datetime.date.fromordinal(ep['airdate']).weekday() # Add tvdbid for backward compability - ep["tvdbid"] = ep['indexerid'] + try: + showObj = helpers.find_show_by_id(sickbeard.showList, {ep['indexer']: ep['indexerid']}) + ep['tvdbid'] = showObj.ids.get(INDEXER_TVDB, {'id': 0})['id'] + ep['ids'] = {k: v.get('id') for k, v in showObj.ids.iteritems()} + except (StandardError, Exception): + ep['tvdbid'] = (None, ep['indexerid'])[INDEXER_TVDB == ep['indexer']] + ep['ids'] = None + ep['airdate'] = sbdatetime.sbdatetime.sbfdate(datetime.date.fromordinal(ep['airdate']), d_preset=dateFormat) ep['parsed_datetime'] = sbdatetime.sbdatetime.sbfdatetime(ep['parsed_datetime'], d_preset=dateFormat, t_preset='%H:%M %z') @@ -814,19 +997,41 @@ class CMD_ComingEpisodes(ApiCall): return _responds(RESULT_SUCCESS, finalEpResults) -class CMD_Episode(ApiCall): +class CMD_ComingEpisodes(CMD_SickGearComingEpisodes): + _help = {"desc": "display the coming episodes", + "optionalParameters": {"sort": {"desc": "change the sort order"}, + "type": {"desc": "one or more of allowedValues separated by |"}, + "paused": { + "desc": "0 to exclude paused shows, 1 to include them, or omitted to use the SB default"}, + }, + "SickGearCommand": "sg.future", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearComingEpisodes.__init__(self, handler, args, kwargs) + + +class CMD_SickGearEpisode(ApiCall): _help = {"desc": "display detailed info about an episode", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, "season": {"desc": "the season number"}, "episode": {"desc": "the episode number"} - }, + }, "optionalParameters": {"full_path": { - "desc": "show the full absolute path (if valid) instead of a relative path for the episode location"} - } - } + "desc": "show the full absolute path (if valid) instead of a relative path for the episode location"}, + + }, + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) self.s, args = self.check_params(args, kwargs, "season", None, True, "int", []) self.e, args = self.check_params(args, kwargs, "episode", None, True, "int", []) @@ -837,14 +1042,16 @@ class CMD_Episode(ApiCall): def run(self): """ display detailed info about an episode """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") myDB = db.DBConnection(row_type="dict") sqlResults = myDB.select( - "SELECT name, description, airdate, status, location, file_size, release_name, subtitles FROM tv_episodes WHERE showid = ? AND episode = ? AND season = ?", - [self.indexerid, self.e, self.s]) + "SELECT name, description, airdate, status, location, file_size, release_name, subtitles, absolute_number, " + "scene_season, scene_episode, scene_absolute_number FROM tv_episodes WHERE indexer = ? AND showid = ? " + "AND episode = ? AND season = ?", + [self.indexer, self.indexerid, self.e, self.s]) if not len(sqlResults) == 1: raise ApiError("Episode not found") episode = sqlResults[0] @@ -865,7 +1072,8 @@ class CMD_Episode(ApiCall): elif not showPath: # show dir is broken ... episode path will be empty episode["location"] = "" # convert stuff to human form - episode['airdate'] = sbdatetime.sbdatetime.sbfdate(sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(int(episode['airdate']), showObj.airs, showObj.network)), d_preset=dateFormat) + timezone, episode['timezone'] = network_timezones.get_network_timezone(showObj.network, return_name=True) + episode['airdate'] = sbdatetime.sbdatetime.sbfdate(sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(int(episode['airdate']), showObj.airs, timezone)), d_preset=dateFormat) status, quality = Quality.splitCompositeStatus(int(episode["status"])) episode["status"] = _get_status_Strings(status) episode["quality"] = _get_quality_string(quality) @@ -874,16 +1082,39 @@ class CMD_Episode(ApiCall): return _responds(RESULT_SUCCESS, episode) -class CMD_EpisodeSearch(ApiCall): +class CMD_Episode(CMD_SickGearEpisode): + _help = {"desc": "display detailed info about an episode", + "requiredParameters": {"indexerid": {"desc": "unique id of a show"}, + "season": {"desc": "the season number"}, + "episode": {"desc": "the episode number"} + }, + "optionalParameters": {"full_path": { + "desc": "show the full absolute path (if valid) instead of a relative path for the episode location"}, + }, + "SickGearCommand": "sg.episode", + } + + def __init__(self, handler, args, kwargs): + # required + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearEpisode.__init__(self, handler, args, kwargs) + + +class CMD_SickGearEpisodeSearch(ApiCall): _help = {"desc": "search for an episode. the response might take some time", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, "season": {"desc": "the season number"}, "episode": {"desc": "the episode number"} - } + }, } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) self.s, args = self.check_params(args, kwargs, "season", None, True, "int", []) self.e, args = self.check_params(args, kwargs, "episode", None, True, "int", []) @@ -893,7 +1124,7 @@ class CMD_EpisodeSearch(ApiCall): def run(self): """ search for an episode """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -920,32 +1151,55 @@ class CMD_EpisodeSearch(ApiCall): return _responds(RESULT_FAILURE, msg='Unable to find episode') -class CMD_EpisodeSetStatus(ApiCall): +class CMD_EpisodeSearch(CMD_SickGearEpisodeSearch): + _help = {"desc": "search for an episode. the response might take some time", + "requiredParameters": {"tvdbid": {"desc": "thetvdb.com id of a show"}, + "season": {"desc": "the season number"}, + "episode": {"desc": "the episode number"} + }, + "SickGearCommand": "episode.search", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearEpisodeSearch.__init__(self, handler, args, kwargs) + + +class CMD_SickGearEpisodeSetStatus(ApiCall): _help = {"desc": "set status of an episode or season (when no ep is provided)", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, "season": {"desc": "the season number"}, - "status": {"desc": "the status values: wanted, skipped, archived, ignored, failed"} - }, + "status": {"desc": "the status values: wanted, skipped, archived, ignored, failed, snatched, downloaded"} + }, "optionalParameters": {"episode": {"desc": "the episode number"}, - "force": {"desc": "should we replace existing (downloaded) episodes or not"} - } - } + "force": {"desc": "should we replace existing (downloaded) episodes or not"}, + "quality": {"desc": "set quality of episode(s), only for statuses: snatched, downloaded, archived"}, + } + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) self.s, args = self.check_params(args, kwargs, "season", None, True, "int", []) self.status, args = self.check_params(args, kwargs, "status", None, True, "string", - ["wanted", "skipped", "archived", "ignored", "failed"]) + ["wanted", "skipped", "archived", "ignored", "failed", "snatched", "downloaded"]) # optional self.e, args = self.check_params(args, kwargs, "episode", None, False, "int", []) self.force, args = self.check_params(args, kwargs, "force", 0, False, "bool", []) + self.quality, args = self.check_params(args, kwargs, "quality", None, False, "string", [q for q in quality_map]) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): """ set status of an episode or a season (when no ep is provided) """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -958,6 +1212,12 @@ class CMD_EpisodeSetStatus(ApiCall): # the allowed values has at least one item that could not be matched against the internal status strings raise ApiError("The status string could not be matched to a status. Report to Devs!") + if None is not self.quality: + if self.status not in (SNATCHED, SNATCHED_BEST, SNATCHED_PROPER, DOWNLOADED, ARCHIVED): + return _responds(RESULT_FAILURE, msg="Can't set status %s together with quailty: %s" % + (statusStrings[self.status], self.quality)) + self.quality = quality_map[self.quality] + ep_list = [] if self.e: epObj = showObj.getEpisode(self.s, self.e) @@ -996,13 +1256,16 @@ class CMD_EpisodeSetStatus(ApiCall): continue # allow the user to force setting the status for an already downloaded episode - if epObj.status in Quality.DOWNLOADED and not self.force: + if epObj.status in Quality.DOWNLOADED and not self.force and None is self.quality: ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is already marked as DOWNLOADED")) failure = True continue - epObj.status = self.status + if None is not self.quality: + epObj.status = Quality.compositeStatus(self.status, self.quality) + else: + epObj.status = self.status result = epObj.get_sql() if None is not result: sql_l.append(result) @@ -1032,16 +1295,40 @@ class CMD_EpisodeSetStatus(ApiCall): return _responds(RESULT_SUCCESS, msg='All status set successfully.' + extra_msg) -class CMD_SubtitleSearch(ApiCall): - _help = {"desc": "search episode subtitles. the response might take some time", +class CMD_EpisodeSetStatus(CMD_SickGearEpisodeSetStatus): + _help = {"desc": "set status of an episode or season (when no ep is provided)", "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, "season": {"desc": "the season number"}, + "status": {"desc": "the status values: wanted, skipped, archived, ignored, failed"} + }, + "optionalParameters": {"episode": {"desc": "the episode number"}, + "force": {"desc": "should we replace existing (downloaded) episodes or not"} + }, + "SickGearCommand": "sg.episode.setstatus", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + kwargs['indexer'] = INDEXER_TVDB + CMD_SickGearEpisodeSetStatus.__init__(self, handler, args, kwargs) + + +class CMD_SickGearSubtitleSearch(ApiCall): + _help = {"desc": "search episode subtitles. the response might take some time", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + "season": {"desc": "the season number"}, "episode": {"desc": "the episode number"} - } + }, } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) self.s, args = self.check_params(args, kwargs, "season", None, True, "int", []) self.e, args = self.check_params(args, kwargs, "episode", None, True, "int", []) @@ -1051,7 +1338,7 @@ class CMD_SubtitleSearch(ApiCall): def run(self): """ search episode subtitles """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -1084,16 +1371,37 @@ class CMD_SubtitleSearch(ApiCall): return response -class CMD_Exceptions(ApiCall): +class CMD_SubtitleSearch(ApiCall): + _help = {"desc": "search episode subtitles. the response might take some time", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "season": {"desc": "the season number"}, + "episode": {"desc": "the episode number"} + }, + "SickGearCommand": "sg.episode.subtitlesearch", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + ApiCall.__init__(self, handler, args, kwargs) + + +class CMD_SickGearExceptions(ApiCall): _help = {"desc": "display scene exceptions for all or a given show", - "optionalParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, - } - } + "optionalParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + } + } def __init__(self, handler, args, kwargs): # required # optional self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, False, "int", + [i for i in indexer_api.indexerApi().indexers]) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) @@ -1111,7 +1419,7 @@ class CMD_Exceptions(ApiCall): scene_exceptions[indexerid].append(row["show_name"]) else: - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -1125,12 +1433,95 @@ class CMD_Exceptions(ApiCall): return _responds(RESULT_SUCCESS, scene_exceptions) -class CMD_History(ApiCall): - _help = {"desc": "display sickbeard downloaded/snatched history", +class CMD_Exceptions(CMD_SickGearExceptions): + _help = {"desc": "display scene exceptions for all or a given show", + "optionalParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.exceptions", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearExceptions.__init__(self, handler, args, kwargs) + + +class CMD_SetExceptions(ApiCall): + _help = {"desc": "set scene exceptions for a given show", + "requiredParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + "forseason": {"desc": "exception for season, -1 for all seasons"}, + }, + "optionalParameters": {"add": {"desc": "list of exceptions to add"}, + "remove": {"desc": "list of exceptions to remove"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.forseason, args = self.check_params(args, kwargs, "forseason", None, True, "int", []) + # optional + self.add, args = self.check_params(args, kwargs, "add", None, False, "list", []) + self.remove, args = self.check_params(args, kwargs, "remove", None, False, "list", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + if not self.add and not self.remove: + return _responds(RESULT_FAILURE, 'No Exceptions provided to be add or removed.') + + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, 'Could not find any show in db from indexer: %s with id: %s' % + (self.indexer, self.indexerid)) + + myDB = db.DBConnection(row_type="dict") + sqlResults = myDB.select("SELECT show_name, season, indexer_id AS 'indexerid' FROM scene_exceptions WHERE " + "indexer_id = ? and season = ?", [self.indexerid, self.forseason]) + + cl = [] + curexep = [(s['show_name'], s['season']) for s in sqlResults] + add_list = [] + remove_list = [] + if self.remove: + for r in self.remove: + if (r, self.forseason) in curexep: + cl.append(['DELETE FROM scene_exceptions WHERE indexer_id = ? AND season = ? AND show_name = ?', + [self.indexerid, self.forseason, r]]) + try: + curexep.remove((r, self.forseason)) + except ValueError: + pass + remove_list.append(r) + + if self.add: + for a in self.add: + if (a, self.forseason) not in curexep: + cl.append(['INSERT INTO scene_exceptions (show_name, indexer_id, season) VALUES (?,?,?)', + [a, self.indexerid, self.forseason]]) + curexep.append((a, self.forseason)) + add_list.append(a) + + if cl: + myDB.mass_action(cl) + return _responds(RESULT_SUCCESS, data={'added': add_list, 'removed': remove_list, 'for season': self.forseason, + 'current': [c[0] for c in curexep], 'indexer': self.indexer, + 'indexerid': self.indexerid}, + msg='Exceptions changed.') + + +class CMD_SickGearHistory(ApiCall): + _help = {"desc": "display sickgear downloaded/snatched history", "optionalParameters": {"limit": {"desc": "limit returned results"}, "type": {"desc": "only show a specific type of results"}, - } - } + } + } def __init__(self, handler, args, kwargs): # required @@ -1141,7 +1532,7 @@ class CMD_History(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ display sickbeard downloaded/snatched history """ + """ display sickgear downloaded/snatched history """ typeCodes = [] if self.type == "downloaded": @@ -1158,12 +1549,15 @@ class CMD_History(ApiCall): ulimit = min(int(self.limit), 100) if ulimit == 0: sqlResults = myDB.select( - "SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.indexer_id AND action in (" + ','.join( - ['?'] * len(typeCodes)) + ") ORDER BY date DESC", typeCodes) + "SELECT h.*, show_name, s.indexer FROM history h, tv_shows s WHERE h.showid=s.indexer_id" + + ("", " AND s.indexer=%s" % INDEXER_TVDB)[self.sickbeard_call] + + " AND action in (" + ','.join(['?'] * len(typeCodes)) + ") ORDER BY date DESC", typeCodes) else: sqlResults = myDB.select( - "SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.indexer_id AND action in (" + ','.join( - ['?'] * len(typeCodes)) + ") ORDER BY date DESC LIMIT ?", typeCodes + [ulimit]) + "SELECT h.*, show_name, s.indexer FROM history h, tv_shows s WHERE h.showid=s.indexer_id" + + ("", " AND s.indexer=%s" % INDEXER_TVDB)[self.sickbeard_call] + + " AND action in (" + ','.join(['?'] * len(typeCodes)) + ") ORDER BY date DESC LIMIT ?", + typeCodes + [ulimit]) results = [] for row in sqlResults: @@ -1179,15 +1573,31 @@ class CMD_History(ApiCall): row["resource_path"] = os.path.dirname(row["resource"]) row["resource"] = os.path.basename(row["resource"]) # Add tvdbid for backward compability - row['tvdbid'] = row['indexerid'] + row['tvdbid'] = (None, row['indexerid'])[INDEXER_TVDB == row['indexer']] results.append(row) return _responds(RESULT_SUCCESS, results) -class CMD_HistoryClear(ApiCall): - _help = {"desc": "clear sickbeard's history", - } +class CMD_History(CMD_SickGearHistory): + _help = {"desc": "display sickgear downloaded/snatched history", + "optionalParameters": {"limit": {"desc": "limit returned results"}, + "type": {"desc": "only show a specific type of results"}, + }, + "SickGearCommand": "sg.history", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearHistory.__init__(self, handler, args, kwargs) + + +class CMD_SickGearHistoryClear(ApiCall): + _help = {"desc": "clear sickgear's history", + } def __init__(self, handler, args, kwargs): # required @@ -1196,16 +1606,29 @@ class CMD_HistoryClear(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ clear sickbeard's history """ + """ clear sickgear's history """ myDB = db.DBConnection() myDB.action("DELETE FROM history WHERE 1=1") return _responds(RESULT_SUCCESS, msg="History cleared") -class CMD_HistoryTrim(ApiCall): - _help = {"desc": "trim sickbeard's history by removing entries greater than 30 days old" - } +class CMD_HistoryClear(CMD_SickGearHistoryClear): + _help = {"desc": "clear sickgear's history", + "SickGearCommand": "sg.history.clear", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearHistoryClear.__init__(self, handler, args, kwargs) + + +class CMD_SickGearHistoryTrim(ApiCall): + _help = {"desc": "trim sickgear's history by removing entries greater than 30 days old" + } def __init__(self, handler, args, kwargs): # required @@ -1214,7 +1637,7 @@ class CMD_HistoryTrim(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ trim sickbeard's history """ + """ trim sickgear's history """ myDB = db.DBConnection() myDB.action("DELETE FROM history WHERE date < " + str( (datetime.datetime.today() - datetime.timedelta(days=30)).strftime(history.dateFormat))) @@ -1222,11 +1645,24 @@ class CMD_HistoryTrim(ApiCall): return _responds(RESULT_SUCCESS, msg="Removed history entries greater than 30 days old") -class CMD_Logs(ApiCall): - _help = {"desc": "view sickbeard's log", +class CMD_HistoryTrim(CMD_SickGearHistoryTrim): + _help = {"desc": "trim sickgear's history by removing entries greater than 30 days old", + "SickGearCommand": "sg.history.trim", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearHistoryTrim.__init__(self, handler, args, kwargs) + + +class CMD_SickGearLogs(ApiCall): + _help = {"desc": "view sickgear's log", "optionalParameters": {"min_level ": { "desc": "the minimum level classification of log entries to show, with each level inherting its above level"}} - } + } def __init__(self, handler, args, kwargs): # required @@ -1297,7 +1733,22 @@ class CMD_Logs(ApiCall): return _responds(RESULT_SUCCESS, final_data) -class CMD_PostProcess(ApiCall): +class CMD_Logs(CMD_SickGearLogs): + _help = {"desc": "view sickgear's log", + "optionalParameters": {"min_level ": { + "desc": "the minimum level classification of log entries to show, with each level inherting its above level"}}, + "SickGearCommand": "sg.logs", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearLogs.__init__(self, handler, args, kwargs) + + +class CMD_SickGearPostProcess(ApiCall): _help = {"desc": "Manual postprocess TV Download Dir", "optionalParameters": {"path": {"desc": "Post process this folder"}, "force_replace": {"desc": "Force already Post Processed Dir/Files"}, @@ -1339,8 +1790,28 @@ class CMD_PostProcess(ApiCall): return _responds(RESULT_SUCCESS, data=data, msg="Started postprocess for %s" % self.path) -class CMD_SickBeard(ApiCall): - _help = {"desc": "display misc sickbeard related information"} +class CMD_PostProcess(CMD_SickGearPostProcess): + _help = {"desc": "Manual postprocess TV Download Dir", + "optionalParameters": {"path": {"desc": "Post process this folder"}, + "force_replace": {"desc": "Force already Post Processed Dir/Files"}, + "return_data": {"desc": "Returns result for the process"}, + "process_method": {"desc": "Symlink, hardlink, move or copy the file"}, + "is_priority": {"desc": "Replace the file even if it exists in a higher quality)"}, + "type": {"desc": "What type of postprocess request is this, auto of manual"} + }, + "SickGearCommand": "sg.postprocess", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearPostProcess.__init__(self, handler, args, kwargs) + + +class CMD_SickGear(ApiCall): + _help = {"desc": "display misc sickgear related information"} def __init__(self, handler, args, kwargs): # required @@ -1349,19 +1820,31 @@ class CMD_SickBeard(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ display misc sickbeard related information """ - data = {"sb_version": sickbeard.BRANCH, "api_version": Api.version, - "api_commands": sorted(_functionMaper.keys())} + """ display misc sickgear related information """ + data = {"sb_version": sickbeard.BRANCH, "api_version": Api.version, "fork": "SickGear", + "api_commands": sorted(x for x in _functionMaper.keys() if 'listcommands' != x)} return _responds(RESULT_SUCCESS, data) -class CMD_SickBeardAddRootDir(ApiCall): - _help = {"desc": "add a sickbeard user's parent directory", +class CMD_SickBeard(CMD_SickGear): + _help = {"desc": "display misc sickgear related information", + "SickGearCommand": "sg",} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGear.__init__(self, handler, args, kwargs) + + +class CMD_SickGearAddRootDir(ApiCall): + _help = {"desc": "add a sickgear user's parent directory", "requiredParameters": {"location": {"desc": "the full path to root (parent) directory"} - }, + }, "optionalParameters": {"default": {"desc": "make the location passed the default root (parent) directory"} - } - } + } + } def __init__(self, handler, args, kwargs): # required @@ -1372,7 +1855,7 @@ class CMD_SickBeardAddRootDir(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ add a parent directory to sickbeard's config """ + """ add a parent directory to sickgear's config """ self.location = urllib.unquote_plus(self.location) location_matched = 0 @@ -1413,7 +1896,24 @@ class CMD_SickBeardAddRootDir(ApiCall): return _responds(RESULT_SUCCESS, _getRootDirs(), msg="Root directories updated") -class CMD_SickBeardCheckScheduler(ApiCall): +class CMD_SickBeardAddRootDir(CMD_SickGearAddRootDir): + _help = {"desc": "add a sickgear user's parent directory", + "requiredParameters": {"location": {"desc": "the full path to root (parent) directory"} + }, + "optionalParameters": {"default": {"desc": "make the location passed the default root (parent) directory"} + }, + "SickGearCommand": "sg.addrootdir", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearAddRootDir.__init__(self, handler, args, kwargs) + + +class CMD_SickGearCheckScheduler(ApiCall): _help = {"desc": "query the scheduler"} def __init__(self, handler, args, kwargs): @@ -1437,10 +1937,22 @@ class CMD_SickBeardCheckScheduler(ApiCall): return _responds(RESULT_SUCCESS, data) -class CMD_SickBeardDeleteRootDir(ApiCall): - _help = {"desc": "delete a sickbeard user's parent directory", +class CMD_SickBeardCheckScheduler(CMD_SickGearCheckScheduler): + _help = {"desc": "query the scheduler", + "SickGearCommand": "sg.checkscheduler"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearCheckScheduler.__init__(self, handler, args, kwargs) + + +class CMD_SickGearDeleteRootDir(ApiCall): + _help = {"desc": "delete a sickgear user's parent directory", "requiredParameters": {"location": {"desc": "the full path to root (parent) directory"}} - } + } def __init__(self, handler, args, kwargs): # required @@ -1450,7 +1962,7 @@ class CMD_SickBeardDeleteRootDir(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ delete a parent directory from sickbeard's config """ + """ delete a parent directory from sickgear's config """ if sickbeard.ROOT_DIRS == "": return _responds(RESULT_FAILURE, _getRootDirs(), msg="No root directories detected") @@ -1483,26 +1995,77 @@ class CMD_SickBeardDeleteRootDir(ApiCall): return _responds(RESULT_SUCCESS, _getRootDirs(), msg="Root directory deleted") -class CMD_SickBeardForceSearch(ApiCall): - _help = {'desc': 'force the episode recent search early'} +class CMD_SickBeardDeleteRootDir(CMD_SickGearDeleteRootDir): + _help = {"desc": "delete a sickgear user's parent directory", + "requiredParameters": {"location": {"desc": "the full path to root (parent) directory"}}, + "SickGearCommand": "sg.deleterootdir" + } def __init__(self, handler, args, kwargs): # required # optional # super, missing, help - ApiCall.__init__(self, handler, args, kwargs) + self.sickbeard_call = True + CMD_SickGearDeleteRootDir.__init__(self, handler, args, kwargs) - def run(self): - """ force the episode search early """ - # Searching all providers for any needed episodes - result = sickbeard.recentSearchScheduler.forceRun() - if result: - return _responds(RESULT_SUCCESS, msg='Episode recent search successfully forced') - return _responds(RESULT_FAILURE, msg='Can not force the episode recent search because it\'s already active') +class CMD_SickGearForceSearch(ApiCall): + _help = {'desc': 'force the given search type searches', + "requiredParameters": {"searchtype": {"desc": "type of search to be forced: recent, backlog, proper"}} + } + + def __init__(self, handler, args, kwargs): + # required + self.searchtype, args = self.check_params(args, kwargs, "searchtype", "recent", True, "string", + ["recent", "backlog", "proper"]) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ force the given search type search """ + result = None + if 'recent' == self.searchtype: + result = sickbeard.recentSearchScheduler.forceRun() + elif 'backlog' == self.searchtype: + result = sickbeard.backlogSearchScheduler.force_search(force_type=FORCED_BACKLOG) + elif 'proper' == self.searchtype: + result = sickbeard.properFinderScheduler.forceRun() + if result: + return _responds(RESULT_SUCCESS, msg='%s search successfully forced' % self.searchtype) + return _responds(RESULT_FAILURE, + msg='Can not force the %s search because it\'s already active' % self.searchtype) + + +class CMD_SickBeardForceSearch(CMD_SickGearForceSearch): + _help = {'desc': 'force the episode recent search early', + "SickGearCommand": "sg.forcesearch",} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['searchtype'] = 'recent' + self.sickbeard_call = True + CMD_SickGearForceSearch.__init__(self, handler, args, kwargs) + + +class CMD_SickGearSearchQueue(ApiCall): + _help = {'desc': 'list sickgear\'s search queue'} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ list sickgear's search queue """ + return _responds(RESULT_SUCCESS, sickbeard.searchQueueScheduler.action.queue_length()) -class CMD_SickBeardGetDefaults(ApiCall): - _help = {"desc": "get sickbeard user defaults"} + +class CMD_SickGearGetDefaults(ApiCall): + _help = {"desc": "get sickgear user defaults"} def __init__(self, handler, args, kwargs): # required @@ -1511,17 +2074,29 @@ class CMD_SickBeardGetDefaults(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ get sickbeard user defaults """ + """ get sickgear user defaults """ anyQualities, bestQualities = _mapQuality(sickbeard.QUALITY_DEFAULT) data = {"status": statusStrings[sickbeard.STATUS_DEFAULT].lower(), "flatten_folders": int(sickbeard.FLATTEN_FOLDERS_DEFAULT), "initial": anyQualities, - "archive": bestQualities, "future_show_paused": int(sickbeard.EPISODE_VIEW_DISPLAY_PAUSED)} + "archive": bestQualities, "future_show_paused": int(sickgear.EPISODE_VIEW_DISPLAY_PAUSED)} return _responds(RESULT_SUCCESS, data) -class CMD_SickBeardGetMessages(ApiCall): +class CMD_SickBeardGetDefaults(CMD_SickGearGetDefaults): + _help = {"desc": "get sickgear user defaults", + "SickGearCommand": "sg.getdefaults"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearGetDefaults.__init__(self, handler, args, kwargs) + + +class CMD_SickGearGetMessages(ApiCall): _help = {"desc": "get all messages"} def __init__(self, handler, args, kwargs): @@ -1539,8 +2114,20 @@ class CMD_SickBeardGetMessages(ApiCall): return _responds(RESULT_SUCCESS, messages) -class CMD_SickBeardGetRootDirs(ApiCall): - _help = {"desc": "get sickbeard user parent directories"} +class CMD_SickBeardGetMessages(CMD_SickGearGetMessages): + _help = {"desc": "get all messages", + "SickGearCommand": "sg.getmessages"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearGetMessages.__init__(self, handler, args, kwargs) + + +class CMD_SickGearGetQualities(ApiCall): + _help = {"desc": "get all qualities"} def __init__(self, handler, args, kwargs): # required @@ -1549,15 +2136,135 @@ class CMD_SickBeardGetRootDirs(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ get the parent directories defined in sickbeard's config """ + return _responds(RESULT_SUCCESS, quality_map) + + +class CMD_SickGearGetIndexers(ApiCall): + _help = {"desc": "get indexer list", + "optionalParameters": {"searchable-only ": {"desc": "searchable indexers only"}}} + + def __init__(self, handler, args, kwargs): + # required + # optional + self.searchable_only, args = self.check_params(args, kwargs, "searchable-only", False, False, "bool", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + result = {} + for i in indexer_config.indexerConfig: + for d, v in indexer_config.indexerConfig[i].iteritems(): + if self.searchable_only and (indexer_config.indexerConfig[i].get('mapped_only') or + not indexer_config.indexerConfig[i].get('active') or + indexer_config.indexerConfig[i].get('defunct')): + continue + if d in ['id', 'name', 'show_url', 'mapped_only', 'main_url'] and \ + isinstance(v, (basestring, tuple, dict, list, int, long, float, bool)): + if 'mapped_only' == d: + key = 'searchable' + val = not v and indexer_config.indexerConfig[i].get('active') and \ + not indexer_config.indexerConfig[i].get('defunct') + else: + key = d + val = (v, '%s{INDEXER-ID}' % v)['show_url' == d] + result.setdefault(i, {}).update({key: val}) + return _responds(RESULT_SUCCESS, result) + + +class CMD_SickGearGetIndexerIcon(ApiCall): + _help = {"desc": "get indexer icon", + "requiredParameters": {"indexer": {"desc": "indexer"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().all_indexers]) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + # doesn't work + i = indexer_config.indexerConfig.get(self.indexer) + if not i: + self.handler.set_status(404) + return _responds(RESULT_FAILURE, 'Icon not found') + img = i['icon'] + image = ek.ek(os.path.join, sickbeard.PROG_DIR, 'gui', 'slick', 'images', img) + if not ek.ek(os.path.isfile, image): + self.handler.set_status(404) + return _responds(RESULT_FAILURE, 'Icon not found') + return {'outputType': 'image', 'image': self.handler.getImage(image)} + + +class CMD_SickGearGetNetworkIcon(ApiCall): + _help = {"desc": "get network icon", + "requiredParameters": {"network": {"desc": "name of network"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.network, args = self.check_params(args, kwargs, "network", None, True, "string", []) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + image = ek.ek(os.path.join, sickbeard.PROG_DIR, 'gui', 'slick', 'images', 'network', + '%s.png' % self.network.lower()) + if not ek.ek(os.path.isfile, image): + self.handler.set_status(404) + return _responds(RESULT_FAILURE, 'Icon not found') + return {'outputType': 'image', 'image': self.handler.getImage(image)} + + +class CMD_SickGearGetqualityStrings(ApiCall): + _help = {"desc": "get human readable quality strings"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + return _responds(RESULT_SUCCESS, Quality.qualityStrings) + + +class CMD_SickGearGetRootDirs(ApiCall): + _help = {"desc": "get sickgear user parent directories"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ get the parent directories defined in sickgear's config """ return _responds(RESULT_SUCCESS, _getRootDirs()) -class CMD_SickBeardPauseBacklog(ApiCall): +class CMD_SickBeardGetRootDirs(CMD_SickGearGetRootDirs): + _help = {"desc": "get sickgear user parent directories", + "SickGearCommand": "sg.getrootdirs"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearGetRootDirs.__init__(self, handler, args, kwargs) + + +class CMD_SickGearPauseBacklog(ApiCall): _help = {"desc": "pause the backlog search", "optionalParameters": {"pause ": {"desc": "pause or unpause the global backlog"}} - } + } def __init__(self, handler, args, kwargs): # required @@ -1576,8 +2283,22 @@ class CMD_SickBeardPauseBacklog(ApiCall): return _responds(RESULT_SUCCESS, msg="Backlog unpaused") -class CMD_SickBeardPing(ApiCall): - _help = {"desc": "check to see if sickbeard is running"} +class CMD_SickBeardPauseBacklog(CMD_SickGearPauseBacklog): + _help = {"desc": "pause the backlog search", + "optionalParameters": {"pause ": {"desc": "pause or unpause the global backlog"}}, + "SickGearCommand": "sg.pausebacklog" + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearPauseBacklog.__init__(self, handler, args, kwargs) + + +class CMD_SickGearPing(ApiCall): + _help = {"desc": "check to see if sickgear is running",} def __init__(self, handler, args, kwargs): # required @@ -1586,7 +2307,7 @@ class CMD_SickBeardPing(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ check to see if sickbeard is running """ + """ check to see if sickgear is running """ self.handler.set_header('Cache-Control', "max-age=0,no-cache,no-store") if sickbeard.started: return _responds(RESULT_SUCCESS, {"pid": sickbeard.PID}, "Pong") @@ -1594,8 +2315,20 @@ class CMD_SickBeardPing(ApiCall): return _responds(RESULT_SUCCESS, msg="Pong") -class CMD_SickBeardRestart(ApiCall): - _help = {"desc": "restart sickbeard"} +class CMD_SickBeardPing(CMD_SickGearPing): + _help = {"desc": "check to see if sickgear is running", + "SickGearCommand": "sg.ping"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearPing.__init__(self, handler, args, kwargs) + + +class CMD_SickGearRestart(ApiCall): + _help = {"desc": "restart sickgear"} def __init__(self, handler, args, kwargs): # required @@ -1604,16 +2337,29 @@ class CMD_SickBeardRestart(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ restart sickbeard """ + """ restart sickgear """ sickbeard.events.put(sickbeard.events.SystemEvent.RESTART) return _responds(RESULT_SUCCESS, msg="SickGear is restarting...") -class CMD_SickBeardSearchIndexers(ApiCall): +class CMD_SickBeardRestart(CMD_SickGearRestart): + _help = {"desc": "restart sickgear", + "SickGearCommand": "sg.restart"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearRestart.__init__(self, handler, args, kwargs) + + +class CMD_SickGearSearchIndexers(ApiCall): _help = {"desc": "search for show on the indexers with a given string and language", "optionalParameters": {"name": {"desc": "name of the show you want to search for"}, "indexerid": {"desc": "thetvdb.com or tvrage.com unique id of a show"}, - "lang": {"desc": "the 2 letter abbreviation lang id"} + "lang": {"desc": "the 2 letter abbreviation lang id"}, + "indexer": {"desc": "indexer to search, use -1 to search all indexers"} } } @@ -1628,54 +2374,74 @@ class CMD_SickBeardSearchIndexers(ApiCall): # optional self.name, args = self.check_params(args, kwargs, "name", None, False, "string", []) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) - self.lang, args = self.check_params(args, kwargs, "lang", "en", False, "string", self.valid_languages.keys()) - self.indexer, args = self.check_params(args, kwargs, "indexer", 1, False, "int", []) + # self.lang, args = self.check_params(args, kwargs, "lang", "en", False, "string", self.valid_languages.keys()) + self.indexers, args = self.check_params(args, kwargs, "indexers", -1, False, "list", + [-1] + [i for i in indexer_api.indexerApi().search_indexers], int) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ search for show at tvdb with a given string and language """ - if self.name and not self.indexerid: # only name was given - lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() - lINDEXER_API_PARMS['language'] = self.lang - lINDEXER_API_PARMS['custom_ui'] = classes.AllShowsListUI - t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) + """ search for show at indexers with a given string and language """ + if 1 > len(self.indexers) and -1 in self.indexers: + raise ApiError('Mix of -1 (all Indexer) and specific Indexer not allowed') - apiData = None + all_indexer = 1 == len(self.indexers) and -1 == self.indexers[0] - try: - apiData = t[str(self.name).encode()] - except Exception as e: - pass + if self.name and not self.indexerid: # only name was given + results = [] + indexertosearch = (self.indexers, [i for i in indexer_api.indexerApi().indexers if + indexer_api.indexerApi(i).config.get('active') and + not indexer_api.indexerApi(i).config.get('mapped_only') and + not indexer_api.indexerApi(i).config.get('defunct')])[all_indexer] + for i in indexertosearch: + lINDEXER_API_PARMS = sickbeard.indexerApi(i).api_params.copy() + lINDEXER_API_PARMS['language'] = 'en' + lINDEXER_API_PARMS['custom_ui'] = classes.AllShowsNoFilterListUI + t = sickbeard.indexerApi(i).indexer(**lINDEXER_API_PARMS) + + apiData = None - if not apiData: - return _responds(RESULT_FAILURE, msg="Did not get result from tvdb") + try: + apiData = t[str(self.name).encode(), False] + except (StandardError, Exception): + pass + + for curSeries in apiData: + s = {"indexerid": int(curSeries['id']), + "name": curSeries['seriesname'], + "first_aired": curSeries['firstaired'], + "indexer": i, + "aliases": curSeries.get('aliases', None), + "relevance": NewHomeAddShows.get_UWRatio(self.name, curSeries['seriesname'], + curSeries.get('aliases', None))} + if INDEXER_TVDB == i: + s["tvdbid"] = int(curSeries['id']) + else: + s["tvdbid"] = None + results.append(s) - results = [] - for curSeries in apiData: - results.append({"indexerid": int(curSeries['id']), - "tvdbid": int(curSeries['id']), - "name": curSeries['seriesname'], - "first_aired": curSeries['firstaired'], - "indexer": self.indexer}) + if not results: + return _responds(RESULT_FAILURE, msg="Did not get result from %s" % + ', '.join([sickbeard.indexerApi(i).name for i in indexertosearch])) - lang_id = self.valid_languages[self.lang] - return _responds(RESULT_SUCCESS, {"results": results, "langid": lang_id}) + results = sorted(results, key=lambda x: x['relevance'], reverse=True) - elif self.indexerid: - lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() + return _responds(RESULT_SUCCESS, {"results": results, "langid": 'en'}) - lang_id = self.valid_languages[self.lang] - if self.lang and not self.lang == 'en': - lINDEXER_API_PARMS['language'] = self.lang + elif self.indexerid and not all_indexer and 1 == len(self.indexers): + lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexers[0]).api_params.copy() + + lang_id = 'en' + lINDEXER_API_PARMS['language'] = 'en' + lINDEXER_API_PARMS['custom_ui'] = classes.AllShowsNoFilterListUI lINDEXER_API_PARMS['actors'] = False - t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) + t = sickbeard.indexerApi(self.indexers[0]).indexer(**lINDEXER_API_PARMS) try: - myShow = t[int(self.indexerid)] + myShow = t[int(self.indexerid), False] except (sickbeard.indexer_shownotfound, sickbeard.indexer_error): logger.log(u"API :: Unable to find show with id " + str(self.indexerid), logger.WARNING) return _responds(RESULT_SUCCESS, {"results": [], "langid": lang_id}) @@ -1687,17 +2453,42 @@ class CMD_SickBeardSearchIndexers(ApiCall): return _responds(RESULT_FAILURE, msg="Show contains no name, invalid result") showOut = [{"indexerid": self.indexerid, - "tvdbid": self.indexerid, + "indexer": self.indexers[0], "name": unicode(myShow.data['seriesname']), - "first_aired": myShow.data['firstaired']}] + "first_aired": myShow.data['firstaired'], + "aliases": myShow.data.get('aliases', None), + "relevance": NewHomeAddShows.get_UWRatio(self.name, myShow.data['seriesname'], + myShow.data.get('aliases', None))}] + + if INDEXER_TVDB == self.indexers[0]: + showOut[0]["tvdbid"] = int(myShow.data['id']) + else: + showOut[0]["tvdbid"] = None + showOut = sorted(showOut, key=lambda x: x['relevance'], reverse=True) return _responds(RESULT_SUCCESS, {"results": showOut, "langid": lang_id}) else: - return _responds(RESULT_FAILURE, msg="Either indexerid or name is required") + return _responds(RESULT_FAILURE, msg="Either indexer + indexerid or name is required") + + +class CMD_SickBeardSearchIndexers(CMD_SickGearSearchIndexers): + _help = {"desc": "search for show on the tvdb with a given string and language", + "optionalParameters": {"name": {"desc": "name of the show you want to search for"}, + "indexerid": {"desc": "thetvdb.com unique id of a show"}, + "lang": {"desc": "the 2 letter abbreviation lang id"}, + }, + "SickGearCommand": "sg.searchtv", + } + + def __init__(self, handler, args, kwargs): + kwargs['indexers'] = INDEXER_TVDB + # super, missing, help + self.sickbeard_call = True + CMD_SickGearSearchIndexers.__init__(self, handler, args, kwargs) class CMD_SickBeardSetDefaults(ApiCall): - _help = {"desc": "set sickbeard user defaults", + _help = {"desc": "set sickgear user defaults", "optionalParameters": {"initial": {"desc": "initial quality for the show"}, "archive": {"desc": "archive quality for the show"}, "flatten_folders": {"desc": "flatten subfolders within the show directory"}, @@ -1708,12 +2499,8 @@ class CMD_SickBeardSetDefaults(ApiCall): def __init__(self, handler, args, kwargs): # required # optional - self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", - ["sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", - "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown"]) - self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", - ["sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", - "hdbluray", "fullhdbluray"]) + self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", [q for q in quality_map]) + self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", [q for q in quality_map]) self.future_show_paused, args = self.check_params(args, kwargs, "future_show_paused", None, False, "bool", []) self.flatten_folders, args = self.check_params(args, kwargs, "flatten_folders", None, False, "bool", []) self.status, args = self.check_params(args, kwargs, "status", None, False, "string", @@ -1722,18 +2509,7 @@ class CMD_SickBeardSetDefaults(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ set sickbeard user defaults """ - - quality_map = {'sdtv': Quality.SDTV, - 'sddvd': Quality.SDDVD, - 'hdtv': Quality.HDTV, - 'rawhdtv': Quality.RAWHDTV, - 'fullhdtv': Quality.FULLHDTV, - 'hdwebdl': Quality.HDWEBDL, - 'fullhdwebdl': Quality.FULLHDWEBDL, - 'hdbluray': Quality.HDBLURAY, - 'fullhdbluray': Quality.FULLHDBLURAY, - 'unknown': Quality.UNKNOWN} + """ set sickgear user defaults """ iqualityID = [] aqualityID = [] @@ -1771,8 +2547,81 @@ class CMD_SickBeardSetDefaults(ApiCall): return _responds(RESULT_SUCCESS, msg="Saved defaults") +class CMD_SickGearSetSceneNumber(ApiCall): + _help = {"desc": "set Scene Numbers", + "requiredParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + }, + "optionalParameters": {"forSeason": {"desc": "season number of a show"}, + "forEpisode": {"desc": "episode number of a show"}, + "forAbsolute": {"desc": "absolute episode number of a show"}, + "sceneSeason": {"desc": "scene season number of a show to set"}, + "sceneEpisode": {"desc": "scene episode number of a show to set"}, + "sceneAbsolute": {"desc": "scene absolute episode number of a show to set"}, + } + } + + def __init__(self, handler, args, kwargs): + # required + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + # optional + self.forSeason, args = self.check_params(args, kwargs, "forSeason", None, False, "int", []) + self.forEpisode, args = self.check_params(args, kwargs, "forEpisode", None, False, "int", []) + self.forAbsolute, args = self.check_params(args, kwargs, "forAbsolute", None, False, "int", []) + self.sceneSeason, args = self.check_params(args, kwargs, "sceneSeason", None, False, "int", []) + self.sceneEpisode, args = self.check_params(args, kwargs, "sceneEpisode", None, False, "int", []) + self.sceneAbsolute, args = self.check_params(args, kwargs, "sceneAbsolute", None, False, "int", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ saving scene numbers """ + + result = set_scene_numbering_helper(self.indexerid, self.indexer, self.forSeason, self.forEpisode, + self.forAbsolute, self.sceneSeason, self.sceneEpisode, self.sceneEpisode) + + if not result['success']: + return _responds(RESULT_FAILURE, result) + + return _responds(RESULT_SUCCESS, result) + + +class CMD_SickGearActivateSceneNumber(ApiCall): + _help = {"desc": "De-/Activate Scene Numbers", + "requiredParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + "activate": {"desc": "de-/activate scene numbering"}}, + } + + def __init__(self, handler, args, kwargs): + # required + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.activate, args = self.check_params(args, kwargs, "activate", None, True, "bool", []) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ de-/activate scene numbers """ + + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Can't find show") + + showObj.scene = int(self.activate) + showObj.saveToDB() + + return _responds(RESULT_SUCCESS, data={'indexer': self.indexer, 'indexerid': self.indexerid, + 'show_name': showObj.name, 'scenenumbering': showObj.is_scene}, + msg="Scene Numbering %sactivated" % ('de', '')[self.activate]) + + class CMD_SickBeardShutdown(ApiCall): - _help = {"desc": "shutdown sickbeard"} + _help = {"desc": "shutdown sickgear"} def __init__(self, handler, args, kwargs): # required @@ -1781,27 +2630,300 @@ class CMD_SickBeardShutdown(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ shutdown sickbeard """ + """ shutdown sickgear """ sickbeard.events.put(sickbeard.events.SystemEvent.SHUTDOWN) return _responds(RESULT_SUCCESS, msg="SickGear is shutting down...") -class CMD_Show(ApiCall): +class CMD_SickGearListIgnoreWords(ApiCall): + _help = {"desc": "list ignore words", + "optionalParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + } + } + + def __init__(self, handler, args, kwargs): + # required + # optional + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, False, "int", + [i for i in indexer_api.indexerApi().indexers]) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ list ignore words """ + if self.indexer and self.indexerid: + myDB = db.DBConnection() + sqlResults = myDB.select('SELECT show_name, rls_ignore_words FROM tv_shows WHERE indexer = ? AND ' + 'indexer_id = ?', [self.indexer, self.indexerid]) + if sqlResults: + ignore_words = sqlResults[0]['rls_ignore_words'] + return_data = {'type': 'show', 'indexer': self.indexer, 'indexerid': self.indexerid, + 'show name': sqlResults[0]['show_name']} + return_type = '%s:' % sqlResults[0]['show_name'] + else: + return _responds(RESULT_FAILURE, msg='Show not found.') + elif (None is self.indexer) != (None is self.indexerid): + return _responds(RESULT_FAILURE, msg='You must supply indexer + indexerid.') + else: + ignore_words = sickbeard.IGNORE_WORDS + return_data = {'type': 'global'} + return_type = 'Global' + + return_data['use regex'] = ignore_words.startswith('regex:') + return_data['ignore words'] = [w.strip() for w in ignore_words.replace('regex:', '').split(',')] + return _responds(RESULT_SUCCESS, data=return_data, msg="%s ignore words" % return_type) + + +class CMD_SickGearSetIgnoreWords(ApiCall): + _help = {"desc": "set ignore words", + "optionalParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + "add": {"desc": "add words to list"}, + "remove": {"desc": "remove words from list"}, + "regex": {"desc": "interpret ALL (including existing) ignore words as regex"}, + } + } + + def __init__(self, handler, args, kwargs): + # required + # optional + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, False, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.add, args = self.check_params(args, kwargs, "add", None, False, "list", []) + self.remove, args = self.check_params(args, kwargs, "remove", None, False, "list", []) + self.regex, args = self.check_params(args, kwargs, "regex", None, False, "bool", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ set ignore words """ + if not self.add and not self.remove: + return _responds(RESULT_FAILURE, msg="No words to add/remove provided") + + def _create_ignore_words(): + use_regex = ignore_words.startswith('regex:') + ignore_list = [w.strip() for w in ignore_words.replace('regex:', '').split(',')] + + if None is not self.regex: + use_regex = self.regex + if self.add: + for a in self.add: + ignore_list.append(a) + if self.remove: + for r in self.remove: + try: + ignore_list.remove(r) + except ValueError: + pass + return use_regex, ignore_list, '%s%s' % (('', 'regex:')[use_regex], ', '.join(ignore_list)) + + if self.indexer and self.indexerid: + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Show not found") + + myDB = db.DBConnection() + sqlResults = myDB.select('SELECT show_name, rls_ignore_words FROM tv_shows WHERE indexer = ? AND ' + 'indexer_id = ?', [self.indexer, self.indexerid]) + + ignore_words = '' + if sqlResults: + ignore_words = sqlResults[0]['rls_ignore_words'] + + return_data = {'type': 'show', 'indexer': self.indexer, 'indexerid': self.indexerid, + 'show name': sqlResults[0]['show_name']} + return_type = '%s:' % sqlResults[0]['show_name'] + + use_regex, ignore_list, new_ignore_words = _create_ignore_words() + myDB.action('UPDATE tv_shows SET rls_ignore_words = ? WHERE indexer = ? AND indexer_id = ?', + [new_ignore_words, self.indexer, self.indexerid]) + elif (None is self.indexer) != (None is self.indexerid): + return _responds(RESULT_FAILURE, msg='You must supply indexer + indexerid.') + else: + ignore_words = sickbeard.IGNORE_WORDS + use_regex, ignore_list, new_ignore_words = _create_ignore_words() + sickbeard.IGNORE_WORDS = new_ignore_words + sickbeard.save_config() + return_data = {'type': 'global'} + return_type = 'Global' + + return_data['use regex'] = use_regex + return_data['ignore words'] = ignore_list + return _responds(RESULT_SUCCESS, data=return_data, msg="%s set ignore words" % return_type) + + +class CMD_SickGearListRequireWords(ApiCall): + _help = {"desc": "list requried words", + "optionalParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + } + } + + def __init__(self, handler, args, kwargs): + # required + # optional + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, False, "int", + [i for i in indexer_api.indexerApi().indexers]) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ list required words """ + if self.indexer and self.indexerid: + myDB = db.DBConnection() + sqlResults = myDB.select('SELECT show_name, rls_require_words FROM tv_shows WHERE indexer = ? ' + 'AND indexer_id = ?', [self.indexer, self.indexerid]) + if sqlResults: + required_words = sqlResults[0]['rls_require_words'] + return_data = {'type': 'show', 'indexer': self.indexer, 'indexerid': self.indexerid, + 'show name': sqlResults[0]['show_name']} + return_type = '%s:' % sqlResults[0]['show_name'] + else: + return _responds(RESULT_FAILURE, msg='Show not found.') + elif (None is self.indexer) != (None is self.indexerid): + return _responds(RESULT_FAILURE, msg='You must supply indexer + indexerid.') + else: + required_words = sickbeard.REQUIRE_WORDS + return_data = {'type': 'global'} + return_type = 'Global' + + return_data['use regex'] = required_words.startswith('regex:') + return_data['required words'] = [w.strip() for w in required_words.replace('regex:', '').split(',')] + return _responds(RESULT_SUCCESS, data=return_data, msg="%s required words" % return_type) + + +class CMD_SickGearSetRequrieWords(ApiCall): + _help = {"desc": "set required words", + "optionalParameters": {"indexerid": {"desc": "unique id of a show"}, + "indexer": {"desc": "indexer of a show"}, + "add": {"desc": "add words to list"}, + "remove": {"desc": "remove words from list"}, + "regex": {"desc": "interpret ALL (including existing) ignore words as regex"}, + } + } + + def __init__(self, handler, args, kwargs): + # required + # optional + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, False, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, False, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.add, args = self.check_params(args, kwargs, "add", None, False, "list", []) + self.remove, args = self.check_params(args, kwargs, "remove", None, False, "list", []) + self.regex, args = self.check_params(args, kwargs, "regex", None, False, "bool", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ set ignore words """ + if not self.add and not self.remove: + return _responds(RESULT_FAILURE, msg="No words to add/remove provided") + + def _create_required_words(): + use_regex = requried_words.startswith('regex:') + require_list = [w.strip() for w in requried_words.replace('regex:', '').split(',')] + + if None is not self.regex: + use_regex = self.regex + if self.add: + for a in self.add: + require_list.append(a) + if self.remove: + for r in self.remove: + try: + require_list.remove(r) + except ValueError: + pass + return use_regex, require_list, '%s%s' % (('', 'regex:')[use_regex], ', '.join(require_list)) + + if self.indexer and self.indexerid: + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Show not found") + + myDB = db.DBConnection() + sqlResults = myDB.select('SELECT show_name, rls_require_words FROM tv_shows WHERE indexer = ? AND ' + 'indexer_id = ?', [self.indexer, self.indexerid]) + + requried_words = '' + if sqlResults: + requried_words = sqlResults[0]['rls_require_words'] + + return_data = {'type': 'show', 'indexer': self.indexer, 'indexerid': self.indexerid, + 'show name': sqlResults[0]['show_name']} + return_type = '%s:' % sqlResults[0]['show_name'] + + use_regex, required_list, new_required_words = _create_required_words() + myDB.action('UPDATE tv_shows SET rls_require_words = ? WHERE indexer = ? AND indexer_id = ?', + [new_required_words, self.indexer, self.indexerid]) + elif (None is self.indexer) != (None is self.indexerid): + return _responds(RESULT_FAILURE, msg='You must supply indexer + indexerid.') + else: + requried_words = sickbeard.REQUIRE_WORDS + use_regex, required_list, new_required_words = _create_required_words() + sickbeard.REQUIRE_WORDS = new_required_words + sickbeard.save_config() + return_data = {'type': 'global'} + return_type = 'Global' + + return_data['use regex'] = use_regex + return_data['required words'] = required_list + return _responds(RESULT_SUCCESS, data=return_data, msg="%s set requried words" % return_type) + + +class CMD_SickGearUpdateWatchedState(ApiCall): + _help = {"desc": "Update db with details of media file that is watched or unwatched", + "requiredParameters": { + "payloadjson": { + "desc": "Payload is a dict of dicts transmitted as JSON via POST request"}, + }} + + def __init__(self, handler, args, kwargs): + # required + self.payloadjson, args = self.check_params(args, kwargs, "payloadjson", None, True, "dict", []) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ Update db with details of media file that is watched or unwatched """ + payload = self.payloadjson.copy() + + from webserve import MainHandler + MainHandler.update_watched_state(payload, as_json=False) + + if not payload: + return _responds(RESULT_FAILURE, msg='Request made to SickGear with invalid payload') + + return _responds(RESULT_SUCCESS, payload) + + +class CMD_SickGearShow(ApiCall): _help = {"desc": "display information for a given show", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, + "optionalParameters": {"overview": {"desc": "include overview"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional + self.overview, args = self.check_params(args, kwargs, "overview", False, False, "bool", []) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): """ display information for a given show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -1838,15 +2960,31 @@ class CMD_Show(ApiCall): showDict["airs"] = str(showObj.airs).replace('am', ' AM').replace('pm', ' PM').replace(' ', ' ') showDict["indexerid"] = self.indexerid showDict["tvrage_id"] = showObj.ids.get(INDEXER_TVRAGE, {'id': 0})['id'] + showDict['ids'] = {k: v.get('id') for k, v in showObj.ids.iteritems()} showDict["tvrage_name"] = showObj.name showDict["network"] = showObj.network if not showDict["network"]: showDict["network"] = "" showDict["status"] = showObj.status + showDict["scenenumbering"] = showObj.is_scene + showDict["upgrade_once"] = showObj.upgrade_once + showDict["ignorewords"] = showObj.rls_ignore_words + showDict["requirewords"] = showObj.rls_require_words + if self.overview: + showDict["overview"] = showObj.overview + showDict["tag"] = showObj.tag + showDict["imdb_id"] = showObj.imdbid + showDict["classification"] = showObj.classification + showDict["runtime"] = showObj.runtime + showDict["startyear"] = showObj.startyear + showDict["indexer"] = showObj.indexer + timezone, showDict['timezone'] = network_timezones.get_network_timezone(showDict['network'], return_name=True) if showObj.nextaired: - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(showObj.nextaired, showDict['airs'], showDict['network'])) - showDict['airs'] = sbdatetime.sbdatetime.sbftime(dtEpisodeAirs, t_preset=timeFormat).lstrip('0').replace(' 0', ' ') + dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting( + network_timezones.parse_date_time(showObj.nextaired, showDict['airs'], timezone)) + showDict['airs'] = sbdatetime.sbdatetime.sbftime(dtEpisodeAirs, + t_preset=timeFormat).lstrip('0').replace(' 0', ' ') showDict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) else: showDict['next_ep_airdate'] = '' @@ -1854,39 +2992,49 @@ class CMD_Show(ApiCall): return _responds(RESULT_SUCCESS, showDict) -class CMD_ShowAddExisting(ApiCall): - _help = {"desc": "add a show in sickbeard with an existing folder", - "requiredParameters": {"tvdbid or tvrageid": {"desc": "thetvdb.com or tvrage.com id"}, +class CMD_Show(CMD_SickGearShow): + _help = {"desc": "display information for a given thetvdb.com show", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "optionalParameters": {"overview": {"desc": "include overview"}, + }, + "SickGearCommand": "sg.show", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShow.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowAddExisting(ApiCall): + _help = {"desc": "add a show in SickGear with an existing folder", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "indexer id of a show"}, "location": {"desc": "full path to the existing folder for the show"} }, "optionalParameters": {"initial": {"desc": "initial quality for the show"}, "archive": {"desc": "archive quality for the show"}, + "upgrade_once": {"desc": "upgrade only once"}, "flatten_folders": {"desc": "flatten subfolders for the show"}, "subtitles": {"desc": "allow search episode subtitle"} } } def __init__(self, handler, args, kwargs): - if "tvdbid" in args or "tvdbid" in kwargs: - _INDEXER_INT = 1 - _INDEXER = "tvdbid" - elif "tvrageid" in args or "tvrageid" in kwargs: - _INDEXER_INT = 2 - _INDEXER = "tvrageid" - else: - _INDEXER_INT = None - _INDEXER = None # required - self.indexerid, args = self.check_params(args, kwargs, _INDEXER, None, True, "int", []) - self.indexer = _INDEXER_INT + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().search_indexers]) self.location, args = self.check_params(args, kwargs, "location", None, True, "string", []) # optional - self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", - ["sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", - "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown"]) - self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", - ["sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", - "hdbluray", "fullhdbluray"]) + self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", [q for q in quality_map]) + self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", [q for q in quality_map]) + self.upgradeonce, args = self.check_params(args, kwargs, "upgrade_once", False, False, "bool", []) + self.flatten_folders, args = self.check_params(args, kwargs, "flatten_folders", str(sickbeard.FLATTEN_FOLDERS_DEFAULT), False, "bool", []) self.subtitles, args = self.check_params(args, kwargs, "subtitles", int(sickbeard.USE_SUBTITLES), False, "int", @@ -1895,8 +3043,8 @@ class CMD_ShowAddExisting(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ add a show in sickbeard with an existing folder """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ add a show in sickgear with an existing folder """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if showObj: return _responds(RESULT_FAILURE, msg="An existing indexerid already exists in the database") @@ -1916,17 +3064,6 @@ class CMD_ShowAddExisting(ApiCall): if not indexerName: return _responds(RESULT_FAILURE, msg="Unable to retrieve information from indexer") - quality_map = {'sdtv': Quality.SDTV, - 'sddvd': Quality.SDDVD, - 'hdtv': Quality.HDTV, - 'rawhdtv': Quality.RAWHDTV, - 'fullhdtv': Quality.FULLHDTV, - 'hdwebdl': Quality.HDWEBDL, - 'fullhdwebdl': Quality.FULLHDWEBDL, - 'hdbluray': Quality.HDBLURAY, - 'fullhdbluray': Quality.FULLHDBLURAY, - 'unknown': Quality.UNKNOWN} - #use default quality as a failsafe newQuality = int(sickbeard.QUALITY_DEFAULT) iqualityID = [] @@ -1943,72 +3080,79 @@ class CMD_ShowAddExisting(ApiCall): newQuality = Quality.combineQualities(iqualityID, aqualityID) sickbeard.showQueueScheduler.action.addShow(int(self.indexer), int(self.indexerid), self.location, SKIPPED, - newQuality, int(self.flatten_folders)) + newQuality, int(self.flatten_folders), + upgrade_once=self.upgradeonce) return _responds(RESULT_SUCCESS, {"name": indexerName}, indexerName + " has been queued to be added") -class CMD_ShowAddNew(ApiCall): - _help = {"desc": "add a new show to sickbeard", - "requiredParameters": {"tvdbid or tvrageid": {"desc": "thetvdb.com or tvrage.com id"} - }, +class CMD_ShowAddExisting(CMD_SickGearShowAddExisting): + _help = {"desc": "add a show in sickgear with an existing folder", + "requiredParameters": {"tvdbid": {"desc": "thetvdb.com id"}, + "location": {"desc": "full path to the existing folder for the show"} + }, + "optionalParameters": {"initial": {"desc": "initial quality for the show"}, + "archive": {"desc": "archive quality for the show"}, + "flatten_folders": {"desc": "flatten subfolders for the show"}, + "subtitles": {"desc": "allow search episode subtitle"} + }, + "SickGearCommand": "sg.show.addexisting", + } + + def __init__(self, handler, args, kwargs): + kwargs['indexer'] = INDEXER_TVDB + # required + kwargs['indexerid'], args = self.check_params(args, kwargs, "tvdbid", None, True, "int", []) + # super, missing, help + self.sickbeard_call = True + CMD_SickGearShowAddExisting.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowAddNew(ApiCall): + _help = {"desc": "add a new show to sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of show"}, + "indexerid": {"desc": "id of show"}, + }, "optionalParameters": {"initial": {"desc": "initial quality for the show"}, "location": {"desc": "base path for where the show folder is to be created"}, "archive": {"desc": "archive quality for the show"}, + "upgrade_once": {"desc": "upgrade only once"}, "flatten_folders": {"desc": "flatten subfolders for the show"}, "status": {"desc": "status of missing episodes"}, - "lang": {"desc": "the 2 letter lang abbreviation id"}, "subtitles": {"desc": "allow search episode subtitle"}, "anime": {"desc": "set show to anime"}, "scene": {"desc": "show searches episodes by scene numbering"} - } - } - - valid_languages = { - 'el': 20, 'en': 7, 'zh': 27, 'it': 15, 'cs': 28, 'es': 16, 'ru': 22, - 'nl': 13, 'pt': 26, 'no': 9, 'tr': 21, 'pl': 18, 'fr': 17, 'hr': 31, - 'de': 14, 'da': 10, 'fi': 11, 'hu': 19, 'ja': 25, 'he': 24, 'ko': 32, - 'sv': 8, 'sl': 30} + } + } def __init__(self, handler, args, kwargs): - if "tvdbid" in args or "tvdbid" in kwargs: - _INDEXER_INT = 1 - _INDEXER = "tvdbid" - elif "tvrageid" in args or "tvrageid" in kwargs: - _INDEXER_INT = 2 - _INDEXER = "tvrageid" - else: - _INDEXER_INT = None - _INDEXER = None # required - self.indexerid, args = self.check_params(args, kwargs, _INDEXER, None, True, "int", []) - self.indexer = _INDEXER_INT + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().search_indexers]) # optional self.location, args = self.check_params(args, kwargs, "location", None, False, "string", []) - self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", - ["sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", - "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown"]) - self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", - ["sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", - "hdbluray", "fullhdbluray"]) + self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", [q for q in quality_map]) + self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", [q for q in quality_map]) + self.upgradeonce, args = self.check_params(args, kwargs, "upgrade_once", False, False, "bool", []) self.flatten_folders, args = self.check_params(args, kwargs, "flatten_folders", str(sickbeard.FLATTEN_FOLDERS_DEFAULT), False, "bool", []) self.status, args = self.check_params(args, kwargs, "status", None, False, "string", ["wanted", "skipped", "archived", "ignored"]) - self.lang, args = self.check_params(args, kwargs, "lang", "en", False, "string", self.valid_languages.keys()) self.subtitles, args = self.check_params(args, kwargs, "subtitles", int(sickbeard.USE_SUBTITLES), False, "int", []) self.anime, args = self.check_params(args, kwargs, "anime", int(sickbeard.ANIME_DEFAULT), False, "int", []) self.scene, args = self.check_params(args, kwargs, "scene", int(sickbeard.SCENE_DEFAULT), False, "int", []) + self.lang = 'en' # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ add a show in sickbeard with an existing folder """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ add a show in sickgear with an existing folder """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if showObj: return _responds(RESULT_FAILURE, msg="An existing indexerid already exists in database") @@ -2024,17 +3168,6 @@ class CMD_ShowAddNew(ApiCall): if not ek.ek(os.path.isdir, self.location): return _responds(RESULT_FAILURE, msg="'" + self.location + "' is not a valid location") - quality_map = {'sdtv': Quality.SDTV, - 'sddvd': Quality.SDDVD, - 'hdtv': Quality.HDTV, - 'rawhdtv': Quality.RAWHDTV, - 'fullhdtv': Quality.FULLHDTV, - 'hdwebdl': Quality.HDWEBDL, - 'fullhdwebdl': Quality.FULLHDWEBDL, - 'hdbluray': Quality.HDBLURAY, - 'fullhdbluray': Quality.FULLHDBLURAY, - 'unknown': Quality.UNKNOWN} - # use default quality as a failsafe newQuality = int(sickbeard.QUALITY_DEFAULT) iqualityID = [] @@ -2094,146 +3227,410 @@ class CMD_ShowAddNew(ApiCall): else: helpers.chmodAsParent(showPath) - sickbeard.showQueueScheduler.action.addShow(int(self.indexer), int(self.indexerid), showPath, newStatus, - newQuality, - int(self.flatten_folders), self.lang, self.subtitles, self.anime, - self.scene, new_show=True) # @UndefinedVariable + sickbeard.showQueueScheduler.action.addShow(int(self.indexer), int(self.indexerid), showPath, newStatus, + newQuality, + int(self.flatten_folders), self.lang, self.subtitles, self.anime, + self.scene, new_show=True, upgrade_once=self.upgradeonce) # @UndefinedVariable + + return _responds(RESULT_SUCCESS, {"name": indexerName}, indexerName + " has been queued to be added") + + +class CMD_ShowAddNew(CMD_SickGearShowAddNew): + _help = {"desc": "add a new show to sickgear", + "requiredParameters": {"tvdbid": {"desc": "thetvdb.com id"} + }, + "optionalParameters": {"initial": {"desc": "initial quality for the show"}, + "location": {"desc": "base path for where the show folder is to be created"}, + "archive": {"desc": "archive quality for the show"}, + "flatten_folders": {"desc": "flatten subfolders for the show"}, + "status": {"desc": "status of missing episodes"}, + "lang": {"desc": "the 2 letter lang abbreviation id"}, + "subtitles": {"desc": "allow search episode subtitle"}, + "anime": {"desc": "set show to anime"}, + "scene": {"desc": "show searches episodes by scene numbering"} + }, + "SickGearCommand": "sg.show.addnew", + } + + valid_languages = { + 'el': 20, 'en': 7, 'zh': 27, 'it': 15, 'cs': 28, 'es': 16, 'ru': 22, + 'nl': 13, 'pt': 26, 'no': 9, 'tr': 21, 'pl': 18, 'fr': 17, 'hr': 31, + 'de': 14, 'da': 10, 'fi': 11, 'hu': 19, 'ja': 25, 'he': 24, 'ko': 32, + 'sv': 8, 'sl': 30} + + def __init__(self, handler, args, kwargs): + kwargs['indexer'] = INDEXER_TVDB + kwargs['indexerid'], args = self.check_params(args, kwargs, "tvdbid", None, True, "int", []) + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearShowAddNew.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowCache(ApiCall): + _help = {"desc": "check sickgear's cache to see if the banner or poster image for a show is valid", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ check sickgear's cache to see if the banner or poster image for a show is valid """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Show not found") + + #TODO: catch if cache dir is missing/invalid.. so it doesn't break show/show.cache + #return {"poster": 0, "banner": 0} + + cache_obj = image_cache.ImageCache() + + has_poster = 0 + has_banner = 0 + + if ek.ek(os.path.isfile, cache_obj.poster_path(showObj.indexerid)): + has_poster = 1 + if ek.ek(os.path.isfile, cache_obj.banner_path(showObj.indexerid)): + has_banner = 1 + + return _responds(RESULT_SUCCESS, {"poster": has_poster, "banner": has_banner}) + + +class CMD_ShowCache(CMD_SickGearShowCache): + _help = {"desc": "check sickgear's cache to see if the banner or poster image for a show is valid", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.cache", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowCache.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowDelete(ApiCall): + _help = {"desc": "delete a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ delete a show in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Show not found") + + if sickbeard.showQueueScheduler.action.isBeingAdded( + showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable + return _responds(RESULT_FAILURE, msg="Show can not be deleted while being added or updated") + + showObj.deleteShow() + return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been deleted") - return _responds(RESULT_SUCCESS, {"name": indexerName}, indexerName + " has been queued to be added") +class CMD_ShowDelete(CMD_SickGearShowDelete): + _help = {"desc": "delete a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.delete", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowDelete.__init__(self, handler, args, kwargs) -class CMD_ShowCache(ApiCall): - _help = {"desc": "check sickbeard's cache to see if the banner or poster image for a show is valid", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"} + +class CMD_SickGearShowGetQuality(ApiCall): + _help = {"desc": "get quality setting for a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ check sickbeard's cache to see if the banner or poster image for a show is valid """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ get quality setting for a show in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") - #TODO: catch if cache dir is missing/invalid.. so it doesn't break show/show.cache - #return {"poster": 0, "banner": 0} + anyQualities, bestQualities = _mapQuality(showObj.quality) - cache_obj = image_cache.ImageCache() + data = {"initial": anyQualities, "archive": bestQualities} - has_poster = 0 - has_banner = 0 + if not self.sickbeard_call: + data['upgrade_once'] = showObj.upgrade_once - if ek.ek(os.path.isfile, cache_obj.poster_path(showObj.indexerid)): - has_poster = 1 - if ek.ek(os.path.isfile, cache_obj.banner_path(showObj.indexerid)): - has_banner = 1 + return _responds(RESULT_SUCCESS, data) - return _responds(RESULT_SUCCESS, {"poster": has_poster, "banner": has_banner}) +class CMD_ShowGetQuality(CMD_SickGearShowGetQuality): + _help = {"desc": "get quality setting for a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.getquality", + } -class CMD_ShowDelete(ApiCall): - _help = {"desc": "delete a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowGetQuality.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowGetPoster(ApiCall): + _help = {"desc": "get the poster stored for a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ delete a show in sickbeard """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: - return _responds(RESULT_FAILURE, msg="Show not found") + """ get the poster for a show in sickgear """ + return {'outputType': 'image', 'image': self.handler.showPoster(self.indexerid, 'poster', True)} - if sickbeard.showQueueScheduler.action.isBeingAdded( - showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable - return _responds(RESULT_FAILURE, msg="Show can not be deleted while being added or updated") - showObj.deleteShow() - return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been deleted") +class CMD_ShowGetPoster(CMD_SickGearShowGetPoster): + _help = {"desc": "get the poster stored for a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.getposter", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowGetPoster.__init__(self, handler, args, kwargs) -class CMD_ShowGetQuality(ApiCall): - _help = {"desc": "get quality setting for a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"} +class CMD_SickGearShowGetBanner(ApiCall): + _help = {"desc": "get the banner stored for a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ get quality setting for a show in sickbeard """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: - return _responds(RESULT_FAILURE, msg="Show not found") + """ get the banner for a show in sickgear """ + return {'outputType': 'image', 'image': self.handler.showPoster(self.indexerid, 'banner', True)} - anyQualities, bestQualities = _mapQuality(showObj.quality) - return _responds(RESULT_SUCCESS, {"initial": anyQualities, "archive": bestQualities}) +class CMD_ShowGetBanner(CMD_SickGearShowGetBanner): + _help = {"desc": "get the banner stored for a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.getbanner", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowGetBanner.__init__(self, handler, args, kwargs) -class CMD_ShowGetPoster(ApiCall): - _help = {"desc": "get the poster stored for a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"} +class CMD_SickGearShowListFanart(ApiCall): + _help = {"desc": "list the fanart's stored for a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ get the poster for a show in sickbeard """ - return {'outputType': 'image', 'image': self.handler.showPoster(self.indexerid, 'poster', True)} + """ list the fanart's for a show in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) + if not showObj: + return _responds(RESULT_FAILURE, msg="Show not found") + fanart = [] + rating_names = {10: 'group', 20: 'favorite', 30: 'avoid'} + cache_obj = image_cache.ImageCache() + for img in ek.ek(glob.glob, cache_obj.fanart_path(showObj.indexerid).replace('fanart.jpg', '*')) or []: + match = re.search(r'\.(\d+(?:\.(\w*?(\d*)))?\.(?:\w{5,8}))\.fanart\.', img, re.I) + if match and match.group(1): + fanart += [(match.group(1), rating_names.get(sickbeard.FANART_RATINGS.get(str(self.indexerid), {}).get(match.group(1), ''), ''))] + + return _responds(RESULT_SUCCESS, fanart) -class CMD_ShowGetBanner(ApiCall): - _help = {"desc": "get the banner stored for a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"} + +class CMD_SickGearShowRateFanart(ApiCall): + _help = {"desc": "rate the fanart's stored for a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + "fanartname": {"desc": "fanart name form sg.show.listfanart"}, + "rating": {"desc": "rate: unrate, group, favorite, avoid"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + self.fanartname, args = self.check_params(args, kwargs, "fanartname", None, True, "string", []) + self.rating, args = self.check_params(args, kwargs, "rating", None, True, "string", + ['unrate', 'group', 'favorite', 'avoid']) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ get the banner for a show in sickbeard """ - return {'outputType': 'image', 'image': self.handler.showPoster(self.indexerid, 'banner', True)} + """ rate the fanart's for a show in sickgear """ + cache_obj = image_cache.ImageCache() + fanartfile = cache_obj.fanart_path(self.indexerid).replace('fanart.jpg', '%s.fanart.jpg' % self.fanartname) + if not ek.ek(os.path.isfile, fanartfile): + return _responds(RESULT_FAILURE, msg='Unknown Fanart') + fan_ratings = {'unrate': 0, 'group': 10, 'favorite': 20, 'avoid': 30} + if 'unrate' == self.rating and str(self.indexerid) in sickbeard.FANART_RATINGS \ + and self.fanartname in sickbeard.FANART_RATINGS[str(self.indexerid)]: + del sickbeard.FANART_RATINGS[str(self.indexerid)][self.fanartname] + else: + sickbeard.FANART_RATINGS[str(self.indexerid)][self.fanartname] = fan_ratings[self.rating] + sickbeard.save_config() + return _responds(RESULT_SUCCESS, msg='Rated Fanart: %s = %s' % (self.fanartname, self.rating)) + + +class CMD_SickGearShowGetFanart(ApiCall): + _help = {"desc": "get the fanart stored for a show in sickgear. X-Fanartname response header resturns Fanart name or default for not found", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, + "optionalParameters": {"fanartname": {"desc": "fanart name form sg.show.listfanart"}, + }, + } + def __init__(self, handler, args, kwargs): + # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) + self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) + # optional + self.fanartname, args = self.check_params(args, kwargs, "fanartname", None, False, "string", []) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) -class CMD_ShowPause(ApiCall): - _help = {"desc": "set a show's paused state in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, - }, + def run(self): + """ get the fanart for a show in sickgear """ + cache_obj = image_cache.ImageCache() + default_fanartfile = ek.ek(os.path.join, sickbeard.PROG_DIR, 'gui', 'slick', 'images', 'trans.png') + fanartfile = default_fanartfile + used_fanart = 'default' + if self.fanartname: + fanartfile = cache_obj.fanart_path(self.indexerid).replace('fanart.jpg', '%s.fanart.jpg' % self.fanartname) + if not ek.ek(os.path.isfile, fanartfile): + fanartfile = default_fanartfile + used_fanart = self.fanartname + else: + fanart = [] + for img in ek.ek(glob.glob, cache_obj.fanart_path(self.indexerid).replace('fanart.jpg', '*')) or []: + if not ek.ek(os.path.isfile, img): + continue + match = re.search(r'\.(\d+(?:\.(\w*?(\d*)))?\.(?:\w{5,8}))\.fanart\.', img, re.I) + if match and match.group(1): + fanart += [(img, match.group(1), sickbeard.FANART_RATINGS.get(str(self.indexerid), {}).get(match.group(1), 0))] + if fanart: + fanartsorted = sorted([f for f in fanart if f[2] != 30], key=lambda x: x[2], reverse=True) + max_fa = max([f[2] for f in fanartsorted]) + fanartsorted = [f for f in fanartsorted if f[2] == max_fa] + if fanartsorted: + random_fanart = randint(0, len(fanartsorted) - 1) + fanartfile = fanartsorted[random_fanart][0] + used_fanart = fanartsorted[random_fanart][1] + + if fanartfile and ek.ek(os.path.isfile, fanartfile): + with ek.ek(open, fanartfile, 'rb') as f: + mime_type, encoding = MimeTypes().guess_type(fanartfile) + self.handler.set_header('X-Fanartname', used_fanart) + self.handler.set_header('Content-Type', mime_type) + return {'outputType': 'image', 'image': f.read()} + + # we should never get here + return _responds(RESULT_FAILURE, msg='No Fanart found') + + +class CMD_SickGearShowPause(ApiCall): + _help = {"desc": "set a show's paused state in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, "optionalParameters": {"pause": {"desc": "set the pause state of the show"} - } - } + } + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional self.pause, args = self.check_params(args, kwargs, "pause", 0, False, "bool", []) @@ -2241,8 +3638,8 @@ class CMD_ShowPause(ApiCall): ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ set a show's paused state in sickbeard """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ set a show's paused state in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -2256,22 +3653,42 @@ class CMD_ShowPause(ApiCall): return _responds(RESULT_FAILURE, msg=str(showObj.name) + " was unable to be paused") -class CMD_ShowRefresh(ApiCall): - _help = {"desc": "refresh a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, - } - } +class CMD_ShowPause(CMD_SickGearShowPause): + _help = {"desc": "set a show's paused state in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "optionalParameters": {"pause": {"desc": "set the pause state of the show"} + }, + "SickGearCommand": "sg.show.pause", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowPause.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowRefresh(ApiCall): + _help = {"desc": "refresh a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"},}, + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ refresh a show in sickbeard """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ refresh a show in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -2283,16 +3700,35 @@ class CMD_ShowRefresh(ApiCall): return _responds(RESULT_FAILURE, msg="Unable to refresh " + str(showObj.name)) -class CMD_ShowSeasonList(ApiCall): +class CMD_ShowRefresh(CMD_SickGearShowRefresh): + _help = {"desc": "refresh a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.refresh", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowRefresh.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowSeasonList(ApiCall): _help = {"desc": "display the season list for a given show", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, - }, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, "optionalParameters": {"sort": {"desc": "change the sort order from descending to ascending"} - } - } + } + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional self.sort, args = self.check_params(args, kwargs, "sort", "desc", False, "string", @@ -2302,17 +3738,19 @@ class CMD_ShowSeasonList(ApiCall): def run(self): """ display the season list for a given show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") myDB = db.DBConnection(row_type="dict") if self.sort == "asc": - sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season ASC", - [self.indexerid]) + sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? AND indexer = ? " + "ORDER BY season ASC", + [self.indexerid, self.indexer]) else: - sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season DESC", - [self.indexerid]) + sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? AND indexer = ? " + "ORDER BY season DESC", + [self.indexerid, self.indexer]) seasonList = [] # a list with all season numbers for row in sqlResults: seasonList.append(int(row["season"])) @@ -2320,16 +3758,37 @@ class CMD_ShowSeasonList(ApiCall): return _responds(RESULT_SUCCESS, seasonList) -class CMD_ShowSeasons(ApiCall): +class CMD_ShowSeasonList(CMD_SickGearShowSeasonList): + _help = {"desc": "display the season list for a given show", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "optionalParameters": {"sort": {"desc": "change the sort order from descending to ascending"} + }, + "SickGearCommand": "sg.show.seasonlist", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowSeasonList.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowSeasons(ApiCall): _help = {"desc": "display a listing of episodes for all or a given season", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, - }, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, "optionalParameters": {"season": {"desc": "the season number"}, - } - } + } + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional self.season, args = self.check_params(args, kwargs, "season", None, False, "int", []) @@ -2338,22 +3797,30 @@ class CMD_ShowSeasons(ApiCall): def run(self): """ display a listing of episodes for all or a given show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") myDB = db.DBConnection(row_type="dict") if self.season == None: - sqlResults = myDB.select("SELECT name, episode, airdate, status, season FROM tv_episodes WHERE showid = ?", - [self.indexerid]) + sqlResults = myDB.select("SELECT name, description, absolute_number, scene_absolute_number, episode, " + "scene_episode, scene_season, airdate, status, season FROM tv_episodes " + "WHERE showid = ? AND indexer = ?", + [self.indexerid, self.indexer]) seasons = {} for row in sqlResults: status, quality = Quality.splitCompositeStatus(int(row["status"])) row["status"] = _get_status_Strings(status) row["quality"] = _get_quality_string(quality) - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(row['airdate'],showObj.airs,showObj.network)) + timezone, row['timezone'] = network_timezones.get_network_timezone(showObj.network, return_name=True) + dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time( + row['airdate'], showObj.airs, timezone)) row['airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + row['scene_episode'] = helpers.tryInt(row['scene_episode']) + row['scene_season'] = helpers.tryInt(row['scene_season']) + row['absolute_number'] = helpers.tryInt(row['absolute_number']) + row['scene_absolute_number'] = helpers.tryInt(row['scene_absolute_number']) curSeason = int(row["season"]) curEpisode = int(row["episode"]) del row["season"] @@ -2364,8 +3831,9 @@ class CMD_ShowSeasons(ApiCall): else: sqlResults = myDB.select( - "SELECT name, episode, airdate, status FROM tv_episodes WHERE showid = ? AND season = ?", - [self.indexerid, self.season]) + "SELECT name, description, absolute_number, scene_absolute_number, episode, scene_episode, " + "scene_season, airdate, status FROM tv_episodes WHERE showid = ? AND indexer = ? AND season = ?", + [self.indexerid, self.indexer, self.season]) if len(sqlResults) is 0: return _responds(RESULT_FAILURE, msg="Season not found") seasons = {} @@ -2375,8 +3843,14 @@ class CMD_ShowSeasons(ApiCall): status, quality = Quality.splitCompositeStatus(int(row["status"])) row["status"] = _get_status_Strings(status) row["quality"] = _get_quality_string(quality) - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(row['airdate'], showObj.airs, showObj.network)) + timezone, row['timezone'] = network_timezones.get_network_timezone(showObj.network, return_name=True) + dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time( + row['airdate'], showObj.airs, timezone)) row['airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + row['scene_episode'] = helpers.tryInt(row['scene_episode']) + row['scene_season'] = helpers.tryInt(row['scene_season']) + row['absolute_number'] = helpers.tryInt(row['absolute_number']) + row['scene_absolute_number'] = helpers.tryInt(row['scene_absolute_number']) if not curEpisode in seasons: seasons[curEpisode] = {} seasons[curEpisode] = row @@ -2384,50 +3858,58 @@ class CMD_ShowSeasons(ApiCall): return _responds(RESULT_SUCCESS, seasons) -class CMD_ShowSetQuality(ApiCall): +class CMD_ShowSeasons(CMD_SickGearShowSeasons): + _help = {"desc": "display a listing of episodes for all or a given season", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "optionalParameters": {"season": {"desc": "the season number"}, + }, + "SickGearCommand": "sg.show.seasons", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowSeasons.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowSetQuality(ApiCall): _help = { - "desc": "set desired quality of a show in sickbeard. if neither initial or archive are provided then the config default quality will be used", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"} - }, + "desc": "set desired quality of a show in sickgear. if neither initial or archive are provided then the config default quality will be used", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"} + }, "optionalParameters": {"initial": {"desc": "initial quality for the show"}, - "archive": {"desc": "archive quality for the show"} - } - } + "archive": {"desc": "archive quality for the show"}, + "upgrade_once": {"desc": "upgrade only once"} + } + } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # this for whatever reason removes hdbluray not sdtv... which is just wrong. reverting to previous code.. plus we didnt use the new code everywhere. # self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", _getQualityMap().values()[1:]) - self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", - ["sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", - "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown"]) - self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", - ["sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", - "hdbluray", "fullhdbluray"]) + self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", [q for q in quality_map]) + self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", [q for q in quality_map]) + self.upgradeonce, args = self.check_params(args, kwargs, "upgrade_once", False, False, "bool", []) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ set the quality for a show in sickbeard by taking in a deliminated + """ set the quality for a show in sickgear by taking in a deliminated string of qualities, map to their value and combine for new values """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") - quality_map = {'sdtv': Quality.SDTV, - 'sddvd': Quality.SDDVD, - 'hdtv': Quality.HDTV, - 'rawhdtv': Quality.RAWHDTV, - 'fullhdtv': Quality.FULLHDTV, - 'hdwebdl': Quality.HDWEBDL, - 'fullhdwebdl': Quality.FULLHDWEBDL, - 'hdbluray': Quality.HDBLURAY, - 'fullhdbluray': Quality.FULLHDBLURAY, - 'unknown': Quality.UNKNOWN} - #use default quality as a failsafe newQuality = int(sickbeard.QUALITY_DEFAULT) iqualityID = [] @@ -2444,18 +3926,46 @@ class CMD_ShowSetQuality(ApiCall): newQuality = Quality.combineQualities(iqualityID, aqualityID) showObj.quality = newQuality + showObj.upgrade_once = self.upgradeonce + + showObj.saveToDB() + return _responds(RESULT_SUCCESS, msg=showObj.name + " quality has been changed to " + _get_quality_string(showObj.quality)) -class CMD_ShowStats(ApiCall): +class CMD_ShowSetQuality(CMD_SickGearShowSetQuality): + _help = { + "desc": "set desired quality of a show in sickgear. if neither initial or archive are provided then the config default quality will be used", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"} + }, + "optionalParameters": {"initial": {"desc": "initial quality for the show"}, + "archive": {"desc": "archive quality for the show"} + }, + "SickGearCommand": "sg.show.setquality", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowSetQuality.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowStats(ApiCall): _help = {"desc": "display episode statistics for a given show", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help @@ -2463,7 +3973,7 @@ class CMD_ShowStats(ApiCall): def run(self): """ display episode statistics for a given show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -2494,8 +4004,9 @@ class CMD_ShowStats(ApiCall): episode_qualities_counts_snatch[statusCode] = 0 myDB = db.DBConnection(row_type="dict") - sqlResults = myDB.select("SELECT status, season FROM tv_episodes WHERE season != 0 AND showid = ?", - [self.indexerid]) + sqlResults = myDB.select("SELECT status, season FROM tv_episodes WHERE season != 0 AND showid = ? " + "AND indexer = ?", + [self.indexerid, self.indexer]) # the main loop that goes through all episodes for row in sqlResults: status, quality = Quality.splitCompositeStatus(int(row["status"])) @@ -2552,22 +4063,41 @@ class CMD_ShowStats(ApiCall): return _responds(RESULT_SUCCESS, episodes_stats) -class CMD_ShowUpdate(ApiCall): - _help = {"desc": "update a show in sickbeard", - "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, +class CMD_ShowStats(CMD_SickGearShowStats): + _help = {"desc": "display episode statistics for a given show", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.stats", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowStats.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowUpdate(ApiCall): + _help = {"desc": "update a show in sickgear", + "requiredParameters": {"indexer": {"desc": "indexer of a show"}, + "indexerid": {"desc": "unique id of a show"}, + }, } - } def __init__(self, handler, args, kwargs): # required + self.indexer, args = self.check_params(args, kwargs, "indexer", None, True, "int", + [i for i in indexer_api.indexerApi().search_indexers]) self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ update a show in sickbeard """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + """ update a show in sickgear """ + showObj = helpers.find_show_by_id(sickbeard.showList, {self.indexer: self.indexerid}) if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") @@ -2579,27 +4109,49 @@ class CMD_ShowUpdate(ApiCall): return _responds(RESULT_FAILURE, msg="Unable to update " + str(showObj.name)) -class CMD_Shows(ApiCall): - _help = {"desc": "display all shows in sickbeard", +class CMD_ShowUpdate(CMD_SickGearShowUpdate): + _help = {"desc": "update a show in sickgear", + "requiredParameters": {"indexerid": {"desc": "thetvdb.com id of a show"}, + }, + "SickGearCommand": "sg.show.update", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + kwargs['indexer'] = INDEXER_TVDB + self.sickbeard_call = True + CMD_SickGearShowUpdate.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShows(ApiCall): + _help = {"desc": "display all shows in sickgear", "optionalParameters": {"sort": {"desc": "sort the list of shows by show name instead of indexerid"}, "paused": {"desc": "only show the shows that are set to paused"}, - }, - } + "overview": {"desc": "include overview"}, + }, + } def __init__(self, handler, args, kwargs): # required # optional self.sort, args = self.check_params(args, kwargs, "sort", "id", False, "string", ["id", "name"]) self.paused, args = self.check_params(args, kwargs, "paused", None, False, "bool", []) + self.overview, args = self.check_params(args, kwargs, "overview", False, False, "bool", []) # super, missing, help ApiCall.__init__(self, handler, args, kwargs) def run(self): - """ display_is_int_multi( self.indexerid )shows in sickbeard """ + """ display_is_int_multi( self.indexerid )shows in sickgear """ shows = {} + for curShow in sickbeard.showList: - if self.paused != None and bool(self.paused) != bool(curShow.paused): + if self.sickbeard_call and INDEXER_TVDB != curShow.indexer: + continue + + if self.paused is not None and bool(self.paused) != bool(curShow.paused): continue showDict = { @@ -2610,17 +4162,35 @@ class CMD_Shows(ApiCall): "sports": curShow.sports, "anime": curShow.anime, "indexerid": curShow.indexerid, + "indexer": curShow.indexer, "tvdbid": curShow.ids.get(INDEXER_TVDB , {'id': 0})['id'], + 'ids': {k: v.get('id') for k, v in curShow.ids.iteritems()}, "tvrage_id": curShow.ids.get(INDEXER_TVRAGE, {'id': 0})['id'], "tvrage_name": curShow.name, "network": curShow.network, "show_name": curShow.name, "status": curShow.status, "subtitles": curShow.subtitles, + "scenenumbering": curShow.is_scene, + "upgrade_once": curShow.upgrade_once, + "ignorewords": curShow.rls_ignore_words, + "requirewords": curShow.rls_require_words, + "tag": curShow.tag, + "imdb_id": curShow.imdbid, + "classification": curShow.classification, + "runtime": curShow.runtime, + "startyear": curShow.startyear, } + if self.overview: + showDict["overview"] = curShow.overview + + timezone, showDict['timezone'] = network_timezones.get_network_timezone(showDict['network'], + return_name=True) + if curShow.nextaired: - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time(curShow.nextaired, curShow.airs, showDict['network'])) + dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting(network_timezones.parse_date_time( + curShow.nextaired, curShow.airs, timezone)) showDict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) else: showDict['next_ep_airdate'] = '' @@ -2636,9 +4206,120 @@ class CMD_Shows(ApiCall): return _responds(RESULT_SUCCESS, shows) -class CMD_ShowsStats(ApiCall): +class CMD_Shows(CMD_SickGearShows): + _help = {"desc": "display all thetvdb.com shows in sickgear", + "optionalParameters": {"sort": {"desc": "sort the list of shows by show name instead of indexerid"}, + "paused": {"desc": "only show the shows that are set to paused"}, + "overview": {"desc": "include overview"}, + }, + "SickGearCommand": "sg.shows", + } + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearShows.__init__(self, handler, args, kwargs) + + +class CMD_SickGearShowsBrowseTrakt(ApiCall): + _help = {"desc": "browse trakt shows in sickgear", + "requiredParameters": {"type": {"desc": "type to browse: anticipated, newshows, newseasons, popular, " + "trending, recommended, watchlist"}, + }, + "optionalParameters": {"account_id": {"desc": "account_id for recommended, watchlist - " + "see sg.listtraktaccounts"}, + }, + } + + def __init__(self, handler, args, kwargs): + # required + self.type, args = self.check_params(args, kwargs, "type", "anticipated", True, "string", + ["anticipated", "newshows", "newseasons", "popular", "trending", + "recommended", "watchlist"]) + # optional + self.account, args = self.check_params(args, kwargs, "account_id", None, False, "int", + [s for s in sickbeard.TRAKT_ACCOUNTS]) + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ browse trakt shows in sickgear """ + urls = {'anticipated': 'shows/anticipated?limit=%s&' % 100, + 'newshows': '/calendars/all/shows/new/%s/%s?' % (sbdatetime.sbdatetime.sbfdate( + dt=datetime.datetime.now() + datetime.timedelta(days=-16), d_preset='%Y-%m-%d'), 32), + 'newseasons': '/calendars/all/shows/premieres/%s/%s?' % (sbdatetime.sbdatetime.sbfdate( + dt=datetime.datetime.now() + datetime.timedelta(days=-16), d_preset='%Y-%m-%d'), 32), + 'popular': 'shows/popular?limit=%s&' % 100, + 'trending': 'shows/trending?limit=%s&' % 100, + 'recommended': 'recommendations/shows?limit=%s&' % 100, + } + kwargs = {} + if self.type in ('recommended', 'watchlist'): + if not self.account: + return _responds(RESULT_FAILURE, msg='Need Trakt account') + kwargs['send_oauth'] = self.account + urls['watchlist'] = 'users/%s/watchlist/shows?limit=%s&' % (sickbeard.TRAKT_ACCOUNTS[self.account].slug, 100) + try: + data, oldest, newest = NewHomeAddShows.get_trakt_data(urls[self.type], **kwargs) + except Exception as e: + return _responds(RESULT_FAILURE, msg=e.message) + return _responds(RESULT_SUCCESS, data) + + +class CMD_SickGearListTraktAccounts(ApiCall): + _help = {"desc": "list Trakt accounts in sickgear"} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ list Trakt accounts in sickgear """ + accounts = [{'name': v.name, 'account_id': v.account_id} for a, v in sickbeard.TRAKT_ACCOUNTS.iteritems()] + return _responds(RESULT_SUCCESS, accounts) + + +class CMD_SickGearShowsForceUpdate(ApiCall): + _help = {"desc": "force the daily show update now."} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ force the daily show update now """ + if sickbeard.showQueueScheduler.action.isShowUpdateRunning() or sickbeard.showUpdateScheduler.action.amActive: + return _responds(RESULT_FAILURE, msg="show update already running.") + + result = sickbeard.showUpdateScheduler.forceRun() + if result: + return _responds(RESULT_SUCCESS, msg="daily show update started") + return _responds(RESULT_FAILURE, msg="can't start show update currently") + + +class CMD_SickGearShowsQueue(ApiCall): + _help = {"desc": "list the show update queue."} + + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + ApiCall.__init__(self, handler, args, kwargs) + + def run(self): + """ list the show update queue """ + return _responds(RESULT_SUCCESS, sickbeard.showQueueScheduler.action.queue_length()) + + +class CMD_SickGearShowsStats(ApiCall): _help = {"desc": "display the global shows and episode stats" - } + } def __init__(self, handler, args, kwargs): # required @@ -2650,68 +4331,149 @@ class CMD_ShowsStats(ApiCall): """ display the global shows and episode stats """ stats = {} + indexer_limit = ('', ' AND indexer = %s' % INDEXER_TVDB)[self.sickbeard_call] myDB = db.DBConnection() today = str(datetime.date.today().toordinal()) - stats["shows_total"] = len(sickbeard.showList) + stats["shows_total"] = (len(sickbeard.showList), + len([x for x in sickbeard.showList if x.indexer == INDEXER_TVDB]))[self.sickbeard_call] stats["shows_active"] = len( - [show for show in sickbeard.showList if show.paused == 0 and show.status != "Ended"]) + [show for show in sickbeard.showList if show.paused == 0 and show.status != "Ended" + and (not self.sickbeard_call or show.indexer == INDEXER_TVDB)]) stats["ep_downloaded"] = myDB.select("SELECT COUNT(*) FROM tv_episodes WHERE status IN (" + ",".join( [str(show) for show in - Quality.DOWNLOADED + Quality.ARCHIVED]) + ") AND season != 0 and episode != 0 AND airdate <= " + today + "")[0][ - 0] + Quality.DOWNLOADED + Quality.ARCHIVED]) + ") AND season != 0 and episode != 0 AND airdate <= " + today + + indexer_limit)[0][0] stats["ep_total"] = myDB.select( "SELECT COUNT(*) FROM tv_episodes WHERE season != 0 AND episode != 0 AND (airdate != 1 OR status IN (" + ",".join( [str(show) for show in Quality.SNATCHED_ANY + Quality.DOWNLOADED + Quality.ARCHIVED]) + - ")) AND airdate <= " + today + " AND status != " + str(IGNORED) + "")[0][0] + ")) AND airdate <= " + today + " AND status != " + str(IGNORED) + indexer_limit)[0][0] return _responds(RESULT_SUCCESS, stats) # WARNING: never define a cmd call string that contains a "_" (underscore) +class CMD_ShowsStats(CMD_SickGearShowsStats): + _help = {"desc": "display the global thetvdb.com shows and episode stats", + "SickGearCommand": "sg.shows.stats", + } +# this is reserved for cmd indexes used while cmd chaining + def __init__(self, handler, args, kwargs): + # required + # optional + # super, missing, help + self.sickbeard_call = True + CMD_SickGearShowsStats.__init__(self, handler, args, kwargs) + +# WARNING: never define a param name that contains a "." (dot) +# this is reserved for cmd namspaces used while cmd chaining # this is reserved for cmd indexes used while cmd chaining # WARNING: never define a param name that contains a "." (dot) # this is reserved for cmd namspaces used while cmd chaining + + _functionMaper = {"help": CMD_Help, + "listcommands": CMD_ListCommands, "future": CMD_ComingEpisodes, + "sg.future": CMD_SickGearComingEpisodes, "episode": CMD_Episode, + "sg.episode": CMD_SickGearEpisode, "episode.search": CMD_EpisodeSearch, + "sg.episode.search": CMD_SickGearEpisodeSearch, "episode.setstatus": CMD_EpisodeSetStatus, + "sg.episode.setstatus": CMD_SickGearEpisodeSetStatus, "episode.subtitlesearch": CMD_SubtitleSearch, + "sg.episode.subtitlesearch": CMD_SickGearSubtitleSearch, "exceptions": CMD_Exceptions, + "sg.exceptions": CMD_SickGearExceptions, + 'sg.setexceptions': CMD_SetExceptions, "history": CMD_History, + "sg.history": CMD_SickGearHistory, "history.clear": CMD_HistoryClear, + "sg.history.clear": CMD_SickGearHistoryClear, "history.trim": CMD_HistoryTrim, + "sg.history.trim": CMD_SickGearHistoryTrim, "logs": CMD_Logs, + "sg.logs": CMD_Logs, "sb": CMD_SickBeard, + "sg": CMD_SickGear, "postprocess": CMD_PostProcess, + "sg.postprocess": CMD_SickGearPostProcess, "sb.addrootdir": CMD_SickBeardAddRootDir, + "sg.addrootdir": CMD_SickGearAddRootDir, "sb.checkscheduler": CMD_SickBeardCheckScheduler, + "sg.checkscheduler": CMD_SickGearCheckScheduler, "sb.deleterootdir": CMD_SickBeardDeleteRootDir, + "sg.deleterootdir": CMD_SickGearDeleteRootDir, "sb.forcesearch": CMD_SickBeardForceSearch, + "sg.forcesearch": CMD_SickGearForceSearch, + "sg.searchqueue": CMD_SickGearSearchQueue, "sb.getdefaults": CMD_SickBeardGetDefaults, + "sg.getdefaults": CMD_SickGearGetDefaults, "sb.getmessages": CMD_SickBeardGetMessages, + "sg.getmessages": CMD_SickGearGetMessages, + "sg.getqualities": CMD_SickGearGetQualities, + "sg.getqualitystrings": CMD_SickGearGetqualityStrings, "sb.getrootdirs": CMD_SickBeardGetRootDirs, + "sg.getrootdirs": CMD_SickGearGetRootDirs, "sb.pausebacklog": CMD_SickBeardPauseBacklog, + "sg.pausebacklog": CMD_SickGearPauseBacklog, "sb.ping": CMD_SickBeardPing, + "sg.ping": CMD_SickGearPing, "sb.restart": CMD_SickBeardRestart, + "sg.restart": CMD_SickGearRestart, "sb.searchtvdb": CMD_SickBeardSearchIndexers, + "sg.searchtv": CMD_SickGearSearchIndexers, "sb.setdefaults": CMD_SickBeardSetDefaults, + "sg.setscenenumber": CMD_SickGearSetSceneNumber, + "sg.activatescenenumbering": CMD_SickGearActivateSceneNumber, + "sg.getindexers": CMD_SickGearGetIndexers, + "sg.getindexericon": CMD_SickGearGetIndexerIcon, + "sg.getnetworkicon": CMD_SickGearGetNetworkIcon, "sb.shutdown": CMD_SickBeardShutdown, + "sg.listignorewords": CMD_SickGearListIgnoreWords, + "sg.setignorewords": CMD_SickGearSetIgnoreWords, + "sg.listrequiredwords": CMD_SickGearListRequireWords, + "sg.setrequiredwords": CMD_SickGearSetRequrieWords, + "sg.updatewatchedstate": CMD_SickGearUpdateWatchedState, "show": CMD_Show, + "sg.show": CMD_SickGearShow, "show.addexisting": CMD_ShowAddExisting, + "sg.show.addexisting": CMD_SickGearShowAddExisting, "show.addnew": CMD_ShowAddNew, + "sg.show.addnew": CMD_SickGearShowAddNew, "show.cache": CMD_ShowCache, + "sg.show.cache": CMD_SickGearShowCache, "show.delete": CMD_ShowDelete, + "sg.show.delete": CMD_SickGearShowDelete, "show.getquality": CMD_ShowGetQuality, + "sg.show.getquality": CMD_SickGearShowGetQuality, "show.getposter": CMD_ShowGetPoster, + "sg.show.getposter": CMD_SickGearShowGetPoster, "show.getbanner": CMD_ShowGetBanner, + "sg.show.getbanner": CMD_SickGearShowGetBanner, + "sg.show.listfanart": CMD_SickGearShowListFanart, + "sg.show.ratefanart": CMD_SickGearShowRateFanart, + "sg.show.getfanart": CMD_SickGearShowGetFanart, "show.pause": CMD_ShowPause, + "sg.show.pause": CMD_SickGearShowPause, "show.refresh": CMD_ShowRefresh, + "sg.show.refresh": CMD_SickGearShowRefresh, "show.seasonlist": CMD_ShowSeasonList, + "sg.show.seasonlist": CMD_SickGearShowSeasonList, "show.seasons": CMD_ShowSeasons, + "sg.show.seasons": CMD_SickGearShowSeasons, "show.setquality": CMD_ShowSetQuality, + "sg.show.setquality": CMD_SickGearShowSetQuality, "show.stats": CMD_ShowStats, + "sg.show.stats": CMD_SickGearShowStats, "show.update": CMD_ShowUpdate, + "sg.show.update": CMD_SickGearShowUpdate, "shows": CMD_Shows, - "shows.stats": CMD_ShowsStats -} + "sg.shows": CMD_SickGearShows, + "sg.shows.browsetrakt": CMD_SickGearShowsBrowseTrakt, + "sg.listtraktaccounts": CMD_SickGearListTraktAccounts, + "shows.stats": CMD_ShowsStats, + "sg.shows.stats": CMD_SickGearShowsStats, + "sg.shows.forceupdate": CMD_SickGearShowsForceUpdate, + "sg.shows.queue": CMD_SickGearShowsQueue, + } diff --git a/sickbeard/webserve.py b/sickbeard/webserve.py index a51d7cf..446d19a 100644 --- a/sickbeard/webserve.py +++ b/sickbeard/webserve.py @@ -23,7 +23,9 @@ import base64 import datetime import dateutil.parser import glob +import hashlib import itertools +import io import os import random import re @@ -32,6 +34,7 @@ import time import traceback import urllib import threading +import zipfile from mimetypes import MimeTypes from Cheetah.Template import Template @@ -51,7 +54,7 @@ from sickbeard.helpers import has_image_ext, remove_article, starify from sickbeard.indexers.indexer_config import INDEXER_TVDB, INDEXER_TVRAGE, INDEXER_TRAKT from sickbeard.scene_numbering import get_scene_numbering, set_scene_numbering, get_scene_numbering_for_show, \ get_xem_numbering_for_show, get_scene_absolute_numbering_for_show, get_xem_absolute_numbering_for_show, \ - get_scene_absolute_numbering + get_scene_absolute_numbering, set_scene_numbering_helper from sickbeard.name_cache import buildNameCache from sickbeard.browser import foldersAtPath from sickbeard.blackandwhitelist import BlackAndWhiteList, short_group_names @@ -71,9 +74,11 @@ from lib.libtrakt.exceptions import TraktException, TraktAuthException from lib.libtrakt.indexerapiinterface import TraktSearchTypes from trakt_helpers import build_config, trakt_collection_remove_account from sickbeard.bs4_parser import BS4Parser + +from lib.fuzzywuzzy import fuzz +from lib.send2trash import send2trash from lib.tmdb_api import TMDB from lib.tvdb_api.tvdb_exceptions import tvdb_exception -from lib.fuzzywuzzy import fuzz try: import json @@ -145,6 +150,13 @@ class BaseHandler(RequestHandler): return self.get_secure_cookie('sickgear-session-%s' % helpers.md5_for_text(sickbeard.WEB_PORT)) return True + def getImage(self, image): + if ek.ek(os.path.isfile, image): + mime_type, encoding = MimeTypes().guess_type(image) + self.set_header('Content-Type', mime_type) + with ek.ek(open, image, 'rb') as img: + return img.read() + def showPoster(self, show=None, which=None, api=None): # Redirect initial poster/banner thumb to default images if 'poster' == which[0:6]: @@ -175,9 +187,14 @@ class BaseHandler(RequestHandler): static_image_path = image_file_name if api: + used_file = ek.ek(os.path.basename, static_image_path) + if static_image_path.startswith('/images'): + used_file = 'default' + static_image_path = ek.ek(os.path.join, sickbeard.PROG_DIR, 'gui', 'slick', static_image_path[1:]) mime_type, encoding = MimeTypes().guess_type(static_image_path) self.set_header('Content-Type', mime_type) - with open(static_image_path, 'rb') as img: + self.set_header('X-Filename', used_file) + with ek.ek(open, static_image_path, 'rb') as img: return img.read() else: static_image_path = os.path.normpath(static_image_path.replace(sickbeard.CACHE_DIR, '/cache')) @@ -275,6 +292,253 @@ class CalendarHandler(BaseHandler): return ical + 'END:VCALENDAR' +class RepoHandler(BaseStaticFileHandler): + + def get(self, path, include_body=True, *args, **kwargs): + super(RepoHandler, self).get(path, include_body) + logger.log('Kodi req... get(path): %s' % path, logger.DEBUG) + + def set_extra_headers(self, *args, **kwargs): + super(RepoHandler, self).set_extra_headers(*args, **kwargs) + self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + + def initialize(self, *args, **kwargs): + super(RepoHandler, self).initialize(*args, **kwargs) + + logger.log('Kodi req... initialize(path): %s' % kwargs['path'], logger.DEBUG) + cache_client = ek.ek(os.path.join, sickbeard.CACHE_DIR, 'clients') + cache_client_kodi = ek.ek(os.path.join, cache_client, 'kodi') + cache_client_kodi_watchedstate = ek.ek(os.path.join, cache_client_kodi, 'service.sickgear.watchedstate.updater') + for folder in (cache_client, + cache_client_kodi, + ek.ek(os.path.join, cache_client_kodi, 'repository.sickgear'), + cache_client_kodi_watchedstate, + ek.ek(os.path.join, cache_client_kodi_watchedstate, 'resources'), + ek.ek(os.path.join, cache_client_kodi_watchedstate, 'resources', 'language'), + ek.ek(os.path.join, cache_client_kodi_watchedstate, 'resources', 'language', 'English'), + ): + if not ek.ek(os.path.exists, folder): + ek.ek(os.mkdir, folder) + + with io.open(ek.ek(os.path.join, cache_client_kodi, 'index.html'), 'w') as fh: + fh.write(self.render_kodi_index()) + with io.open(ek.ek(os.path.join, cache_client_kodi, 'repository.sickgear', 'index.html'), 'w') as fh: + fh.write(self.render_kodi_repository_sickgear_index()) + with io.open(ek.ek(os.path.join, cache_client_kodi_watchedstate, 'index.html'), 'w') as fh: + fh.write(self.render_kodi_service_sickgear_watchedstate_updater_index()) + with io.open(ek.ek(os.path.join, cache_client_kodi_watchedstate, 'resources', 'index.html'), 'w') as fh: + fh.write(self.render_kodi_service_sickgear_watchedstate_updater_resources_index()) + with io.open(ek.ek( + os.path.join, + cache_client_kodi_watchedstate, 'resources', 'language', 'index.html'), 'w') as fh: + fh.write(self.render_kodi_service_sickgear_watchedstate_updater_resources_language_index()) + with io.open(ek.ek( + os.path.join, + cache_client_kodi_watchedstate, 'resources', 'language', 'English', 'index.html'), 'w') as fh: + fh.write(self.render_kodi_service_sickgear_watchedstate_updater_resources_language_english_index()) + + ''' + + if add-on rendered md5 changes, update its zip and then flag to update repo addon + if repo rendered md5 changes or flag is true, update the repo addon, where repo version *must* be increased + + ''' + repo_md5_file = ek.ek(os.path.join, cache_client_kodi, 'addons.xml.md5') + saved_md5 = None + try: + with io.open(repo_md5_file, 'r') as fh: + saved_md5 = fh.readline() + except(StandardError, Exception): + pass + rendered_md5 = self.render_kodi_repo_addons_xml_md5() + if saved_md5 != rendered_md5: + with io.open(ek.ek(os.path.join, cache_client_kodi, 'repository.sickgear', 'addon.xml'), 'w') as fh: + fh.write(self.render_kodi_repo_addon_xml()) + with io.open(ek.ek(os.path.join, cache_client_kodi_watchedstate, 'addon.xml'), 'w') as fh: + fh.write(self.get_watchedstate_updater_addon_xml()) + with io.open(ek.ek(os.path.join, cache_client_kodi, 'addons.xml'), 'w') as fh: + fh.write(self.render_kodi_repo_addons_xml()) + with io.open(ek.ek(os.path.join, cache_client_kodi, 'addons.xml.md5'), 'w') as fh: + fh.write(rendered_md5) + + def save_zip(name, version, zip_path, zip_method): + zip_name = '%s-%s.zip' % (name, version) + zip_file = ek.ek(os.path.join, zip_path, zip_name) + for f in helpers.scantree(zip_path, ['resources']): + if f.is_file(follow_symlinks=False) and f.name[-4:] in ('.zip', '.md5'): + try: + ek.ek(os.remove, f.path) + except OSError: + logger.log('Unable to delete %s: %r / %s' % (f.path, e, str(e)), logger.WARNING) + zip_data = zip_method() + with io.open(zip_file, 'wb') as zh: + zh.write(zip_data) + + # Force a UNIX line ending, like the md5sum utility. + with io.open(ek.ek(os.path.join, zip_path, '%s.md5' % zip_name), 'w', newline='\n') as zh: + zh.write(u'%s *%s\n' % (self.md5ify(zip_data), zip_name)) + + aid, ver = self.repo_sickgear_details() + save_zip(aid, ver, ek.ek(os.path.join, cache_client_kodi, 'repository.sickgear'), + self.kodi_repository_sickgear_zip) + + aid, ver = self.addon_watchedstate_details() + save_zip(aid, ver, cache_client_kodi_watchedstate, + self.kodi_service_sickgear_watchedstate_updater_zip) + + for (src, dst) in ( + (('repository.sickgear', 'icon.png'), + (cache_client_kodi, 'repository.sickgear', 'icon.png')), + (('service.sickgear.watchedstate.updater', 'icon.png'), + (cache_client_kodi_watchedstate, 'icon.png')), + (('service.sickgear.watchedstate.updater', 'resources', 'settings.xml'), + (cache_client_kodi_watchedstate, 'resources', 'settings.xml')), + (('service.sickgear.watchedstate.updater', 'resources', 'language', 'English', 'strings.xml'), + (cache_client_kodi_watchedstate, 'resources', 'language', 'English', 'strings.xml')), + ): + helpers.copyFile(ek.ek( + os.path.join, *(sickbeard.PROG_DIR, 'sickbeard', 'clients', 'kodi') + src), ek.ek(os.path.join, *dst)) + + def get_content_type(self): + if '.md5' == self.absolute_path[-4:]: + return 'text/plain' + return super(RepoHandler, self).get_content_type() + + def index(self, basepath, filelist): + t = PageTemplate(headers=self.request.headers, file='repo_index.tmpl') + t.basepath = basepath + t.filelist = filelist + return t.respond() + + def render_kodi_index(self): + return self.index('/kodi/', + ['repository.sickgear/', + 'service.sickgear.watchedstate.updater/', + 'addons.xml', + 'addons.xml.md5', + ]) + + def render_kodi_repository_sickgear_index(self): + aid, version = self.repo_sickgear_details() + return self.index('/kodi/repository.sickgear/', + ['addon.xml', + 'icon.png', + '%s-%s.zip' % (aid, version), + '%s-%s.zip.md5' % (aid, version), + ]) + + def render_kodi_service_sickgear_watchedstate_updater_index(self): + aid, version = self.addon_watchedstate_details() + return self.index('/kodi/service.sickgear.watchedstate.updater/', + ['resources/', + 'addon.xml', + 'icon.png', + '%s-%s.zip' % (aid, version), + '%s-%s.zip.md5' % (aid, version), + ]) + + def render_kodi_service_sickgear_watchedstate_updater_resources_index(self): + return self.index('/kodi/service.sickgear.watchedstate.updater/resources', + ['language/', + 'settings.xml', + 'icon.png', + ]) + + def render_kodi_service_sickgear_watchedstate_updater_resources_language_index(self): + return self.index('/kodi/service.sickgear.watchedstate.updater/resources/language', + ['English/', + ]) + + def render_kodi_service_sickgear_watchedstate_updater_resources_language_english_index(self): + return self.index('/kodi/service.sickgear.watchedstate.updater/resources/language/English', + ['strings.xml', + ]) + + def repo_sickgear_details(self): + return re.findall('(?si)addon\sid="(repository\.[^"]+)[^>]+version="([^"]+)', + self.render_kodi_repo_addon_xml())[0] + + def addon_watchedstate_details(self): + return re.findall('(?si)addon\sid="([^"]+)[^>]+version="([^"]+)', + self.get_watchedstate_updater_addon_xml())[0] + + @staticmethod + def get_watchedstate_updater_addon_xml(): + with io.open(ek.ek(os.path.join, sickbeard.PROG_DIR, 'sickbeard', 'clients', + 'kodi', 'service.sickgear.watchedstate.updater', 'addon.xml'), 'r') as fh: + return fh.read().strip() + + def render_kodi_repo_addon_xml(self): + t = PageTemplate(headers=self.request.headers, file='repo_kodi_addon.tmpl') + return t.respond().strip() + + def render_kodi_repo_addons_xml(self): + t = PageTemplate(headers=self.request.headers, file='repo_kodi_addons.tmpl') + t.watchedstate_updater_addon_xml = re.sub( + '(?m)^([\s]*<)', r'\t\1', + '\n'.join(self.get_watchedstate_updater_addon_xml().split('\n')[1:])) # skip xml header + + t.repo_xml = re.sub( + '(?m)^([\s]*<)', r'\t\1', + '\n'.join(self.render_kodi_repo_addon_xml().split('\n')[1:])) + + return t.respond() + + def render_kodi_repo_addons_xml_md5(self): + return self.md5ify('\n'.join(self.render_kodi_repo_addons_xml().split('\n')[1:])) + + @staticmethod + def md5ify(string): + return u'%s' % hashlib.new('md5', string).hexdigest() + + def kodi_repository_sickgear_zip(self): + bfr = io.BytesIO() + + try: + with zipfile.ZipFile(bfr, 'w') as zh: + zh.writestr('repository.sickgear/addon.xml', self.render_kodi_repo_addon_xml(), zipfile.ZIP_DEFLATED) + + with io.open(ek.ek(os.path.join, sickbeard.PROG_DIR, + 'sickbeard', 'clients', 'kodi', 'repository.sickgear', 'icon.png'), 'rb') as fh: + infile = fh.read() + zh.writestr('repository.sickgear/icon.png', infile, zipfile.ZIP_DEFLATED) + except OSError as e: + logger.log('Unable to zip %s: %r / %s' % (f.path, e, str(e)), logger.WARNING) + + zip_data = bfr.getvalue() + bfr.close() + return zip_data + + @staticmethod + def kodi_service_sickgear_watchedstate_updater_zip(): + bfr = io.BytesIO() + + basepath = ek.ek(os.path.join, sickbeard.PROG_DIR, 'sickbeard', 'clients', 'kodi') + + zip_path = ek.ek(os.path.join, basepath, 'service.sickgear.watchedstate.updater') + devenv_src = ek.ek(os.path.join, sickbeard.PROG_DIR, 'tests', '_devenv.py') + devenv_dst = ek.ek(os.path.join, zip_path, '_devenv.py') + if sickbeard.ENV.get('DEVENV') and ek.ek(os.path.exists, devenv_src): + helpers.copyFile(devenv_src, devenv_dst) + else: + helpers.remove_file_failed(devenv_dst) + + for f in helpers.scantree(zip_path): + if f.is_file(follow_symlinks=False) and f.name[-4:] not in '.xcf': + try: + with io.open(f.path, 'rb') as fh: + infile = fh.read() + + with zipfile.ZipFile(bfr, 'a') as zh: + zh.writestr(ek.ek(os.path.relpath, f.path, basepath), infile, zipfile.ZIP_DEFLATED) + except OSError as e: + logger.log('Unable to zip %s: %r / %s' % (f.path, e, str(e)), logger.WARNING) + + zip_data = bfr.getvalue() + bfr.close() + return zip_data + + class IsAliveHandler(BaseHandler): def get(self, *args, **kwargs): kwargs = self.request.arguments @@ -602,6 +866,39 @@ class MainHandler(WebHandler): sickbeard.save_config() + def update_watched_state_kodi(self, payload=None, as_json=True): + + data = {} + try: + data = json.loads(payload) + except (StandardError, Exception): + pass + + mapped = 0 + mapping = None + maps = [x.split('=') for x in sickbeard.KODI_PARENT_MAPS.split(',') if any(x)] + for k, d in data.iteritems(): + d['label'] = '%s%s{Kodi}' % (d['label'], bool(d['label']) and ' ' or '') + try: + d['played'] = 100 * int(d['played']) + except (StandardError, Exception): + d['played'] = 0 + + for m in maps: + result, change = helpers.path_mapper(m[0], m[1], d['path_file']) + if change: + if not mapping: + mapping = (states[idx]['path_file'], result) + mapped += 1 + states[idx]['path_file'] = result + break + + if mapping: + logger.log('Folder mappings used, the first of %s is [%s] in Kodi is [%s] in SickGear' % + (mapped, mapping[0], mapping[1])) + + return self.update_watched_state(data, as_json) + @staticmethod def getFooterTime(change_layout=True, json_dump=True, *args, **kwargs): @@ -636,6 +933,128 @@ class MainHandler(WebHandler): return next_event + @staticmethod + def update_watched_state(payload=None, as_json=True): + """ + Update db with details of media file that is watched or unwatched + + :param payload: Payload is a dict of dicts + :type payload: JSON or Dict + Each dict key in payload is an arbitrary value used to return its associated success or fail response. + Each dict value in payload comprises a dict of key value pairs where, + key: path_file: Path and filename of media, required for media to be found. + type: path_file: String + key: played: Optional default=100. Percentage times media has played. If 0, show is set as unwatched. + type: played: String + key: label: Optional default=''. Profile name or label in use while playing media. + type: label: String + key: date_watched: Optional default=current time. Datetime stamp that episode changed state. + type: date_watched: Timestamp + + Example: + dict( + key01=dict(path_file='\\media\\path\\', played=100, label='Bob', date_watched=1509850398.0), + key02=dict(path_file='\\media\\path\\file-played1.mkv', played=100, label='Sue', date_watched=1509850398.0), + key03=dict(path_file='\\media\\path\\file-played2.mkv', played=0, label='Rita', date_watched=1509850398.0) + ) + JSON: '{"key01": {"path_file": "\\media\\path\\file_played1.mkv", "played": 100, "label": "Bob", "date_watched": 1509850398.0}}' + :param as_json: True returns result as JSON otherwise Dict + :type as_json: Boolean + :return: if OK, the value of each dict is '' else fail reason string else None if payload is invalid. + :rtype: JSON if as_json is True otherwise None but with payload dict modified + Example: + Dict: {'key123': {''}} : on success + As JSON: '{"key123": {""}}' : on success + Dict: {'key123': {'error reason'}} + As JSON: '{"key123": {"error reason"}}' + Dict: {'error': {'error reason'}} : 'error' used as default key when bad key, value, or json + JSON: '{"error": {"error reason"}}' : 'error' used as default key when bad key, value, or json + +Example case code using API endpoint, copy/paste, edit to suit, save, then run with: python sg_watched.py +``` +import json +import urllib2 + +# SickGear APIkey +sg_apikey = '0123456789abcdef' +# SickGear server detail +sg_host = 'http://localhost:8081' + +url = '%s/api/%s/?cmd=sg.updatewatchedstate' % (sg_host, sg_apikey) +payload = json.dumps(dict( + key01=dict(path_file='\\media\\path\\', played=100, label='Bob', date_watched=1509850398.0), + key02=dict(path_file='\\media\\path\\file-played1.mkv', played=100, label='Sue', date_watched=1509850398.0), + key03=dict(path_file='\\media\\path\\file-played2.mkv', played=0, label='Rita', date_watched=1509850398.0) +)) +# payload is POST'ed to SG +rq = urllib2.Request(url, data=payload) +r = urllib2.urlopen(rq) +print json.load(r) +r.close() +``` + """ + try: + data = json.loads(payload) + except ValueError: + payload = {} + data = payload + except TypeError: + data = payload + + sql_results = None + if data: + my_db = db.DBConnection(row_type='dict') + + media_paths = map(lambda (_, d): ek.ek(os.path.basename, d['path_file']), data.iteritems()) + sql_results = my_db.select( + 'SELECT episode_id, status, location, file_size FROM tv_episodes WHERE file_size > 0 AND (%s)' % + ' OR '.join(['location LIKE "%%%s"' % x for x in media_paths])) + + if sql_results: + cl = [] + + ep_results = {} + map(lambda r: ep_results.update({'%s' % ek.ek(os.path.basename, r['location']).lower(): dict( + episode_id=r['episode_id'], status=r['status'], location=r['location'], file_size=r['file_size'])}), + sql_results) + + for (k, v) in iteritems(data): + + bname = (ek.ek(os.path.basename, v.get('path_file')) or '').lower() + if not bname: + msg = 'Missing media file name provided' + data[k] = msg + logger.log('Update watched state skipped an item: %s' % msg, logger.WARNING) + continue + + if bname in ep_results: + date_watched = now = sbdatetime.sbdatetime.now().totimestamp(default=0) + if 1500000000 < date_watched: + date_watched = sickbeard.helpers.tryInt(float(v.get('date_watched'))) + + ep_data = ep_results[bname] + # using label and location with upsert to list multi-client items at same location + # can omit label to have the latest scanned client upsert an existing client row based on location + cl.extend(db.mass_upsert_sql( + 'tv_episodes_watched', + dict(tvep_id=ep_data['episode_id'], clientep_id=v.get('media_id', '') or '', + played=v.get('played', 1), + date_watched=date_watched, date_added=now, + status=ep_data['status'], file_size=ep_data['file_size']), + dict(location=ep_data['location'], label=v.get('label', '')), sanitise=False)) + + data[k] = '' + + if cl: + my_db.mass_action(cl) + + if as_json: + if not data: + data = dict(error='Request made to SickGear with invalid payload') + logger.log('Update watched state failed: %s' % data['error'], logger.WARNING) + + return json.dumps(data) + def toggleDisplayShowSpecials(self, show): sickbeard.DISPLAY_SHOW_SPECIALS = not sickbeard.DISPLAY_SHOW_SPECIALS @@ -644,7 +1063,8 @@ class MainHandler(WebHandler): def setHistoryLayout(self, layout): - if layout not in ('compact', 'detailed'): + if layout not in ('compact', 'detailed', 'compact_watched', 'detailed_watched', + 'compact_stats', 'graph_stats', 'provider_failures'): layout = 'detailed' sickbeard.HISTORY_LAYOUT = layout @@ -2458,50 +2878,8 @@ class Home(MainHandler): def setSceneNumbering(self, show, indexer, forSeason=None, forEpisode=None, forAbsolute=None, sceneSeason=None, sceneEpisode=None, sceneAbsolute=None): - # sanitize: - show = None if show in [None, 'null', ''] else int(show) - indexer = None if indexer in [None, 'null', ''] else int(indexer) - - show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, show) - - if not show_obj.is_anime: - for_season = None if forSeason in [None, 'null', ''] else int(forSeason) - for_episode = None if forEpisode in [None, 'null', ''] else int(forEpisode) - scene_season = None if sceneSeason in [None, 'null', ''] else int(sceneSeason) - scene_episode = None if sceneEpisode in [None, 'null', ''] else int(sceneEpisode) - action_log = u'Set episode scene numbering to %sx%s for episode %sx%s of "%s"'\ - % (scene_season, scene_episode, for_season, for_episode, show_obj.name) - ep_args = {'show': show, 'season': for_season, 'episode': for_episode} - scene_args = {'indexer_id': show, 'indexer': indexer, 'season': for_season, 'episode': for_episode, - 'sceneSeason': scene_season, 'sceneEpisode': scene_episode} - result = {'forSeason': for_season, 'forEpisode': for_episode, 'sceneSeason': None, 'sceneEpisode': None} - else: - for_absolute = None if forAbsolute in [None, 'null', ''] else int(forAbsolute) - scene_absolute = None if sceneAbsolute in [None, 'null', ''] else int(sceneAbsolute) - action_log = u'Set absolute scene numbering to %s for episode %s of "%s"'\ - % (scene_absolute, for_absolute, show_obj.name) - ep_args = {'show': show, 'absolute': for_absolute} - scene_args = {'indexer_id': show, 'indexer': indexer, 'absolute_number': for_absolute, - 'sceneAbsolute': scene_absolute} - result = {'forAbsolute': for_absolute, 'sceneAbsolute': None} - - ep_obj = self._getEpisode(**ep_args) - result['success'] = not isinstance(ep_obj, str) - if result['success']: - logger.log(action_log, logger.DEBUG) - set_scene_numbering(**scene_args) - show_obj.flushEpisodes() - else: - result['errorMessage'] = ep_obj - - if not show_obj.is_anime: - scene_numbering = get_scene_numbering(show, indexer, for_season, for_episode) - if scene_numbering: - (result['sceneSeason'], result['sceneEpisode']) = scene_numbering - else: - scene_numbering = get_scene_absolute_numbering(show, indexer, for_absolute) - if scene_numbering: - result['sceneAbsolute'] = scene_numbering + result = set_scene_numbering_helper(show, indexer, forSeason, forEpisode, forAbsolute, sceneSeason, + sceneEpisode, sceneAbsolute) return json.dumps(result) @@ -2549,7 +2927,11 @@ class HomePostProcess(Home): return t.respond() def processEpisode(self, dir=None, nzbName=None, jobName=None, quiet=None, process_method=None, force=None, - force_replace=None, failed='0', type='auto', stream='0', dupekey=None, is_basedir='1', **kwargs): + force_replace=None, failed='0', type='auto', stream='0', dupekey=None, is_basedir='1', + client=None, **kwargs): + + if 'test' in kwargs and kwargs['test'] in ['True', True, 1, '1']: + return 'Connection success!' if not dir and ('0' == failed or not nzbName): self.redirect('/home/postprocess/') @@ -2566,6 +2948,15 @@ class HomePostProcess(Home): break showObj = helpers.find_show_by_id(sickbeard.showList, {indexer: int(m.group(2))}, no_mapped_ids=True) + + skip_failure_processing = isinstance(client, basestring) and 'nzbget' == client and \ + (not isinstance(dupekey, basestring) or None is re.search(r'^SickGear-([A-Za-z]*)(\d+)-', dupekey)) + + if isinstance(client, basestring) and 'nzbget' == client and \ + sickbeard.NZBGET_SCRIPT_VERSION != kwargs.get('ppVersion', '0'): + logger.log('Calling SickGear-NG.py script %s is not current version %s, please update.' % + (kwargs.get('ppVersion', '0'), sickbeard.NZBGET_SCRIPT_VERSION), logger.ERROR) + result = processTV.processDir(dir.decode('utf-8') if dir else None, nzbName.decode('utf-8') if nzbName else None, process_method=process_method, type=type, cleanup='cleanup' in kwargs and kwargs['cleanup'] in ['on', '1'], @@ -2573,7 +2964,8 @@ class HomePostProcess(Home): force_replace=force_replace in ['on', '1'], failed='0' != failed, webhandler=self.send_message if stream != '0' else None, - showObj=showObj, is_basedir=is_basedir in ['on', '1']) + showObj=showObj, is_basedir=is_basedir in ['on', '1'], + skip_failure_processing=skip_failure_processing) if '0' != stream: return @@ -2730,7 +3122,7 @@ class NewHomeAddShows(Home): re.sub(r'([,.!][^,.!]*?)$', '...', re.sub(r'([.!?])(?=\w)', r'\1 ', self.encode_html((show.get('overview', '') or '')[:250:].strip()))), - self._get_UWRatio(term, show['seriesname'], show.get('aliases', [])), None, None, + self.get_UWRatio(term, show['seriesname'], show.get('aliases', [])), None, None, self._make_search_image_url(iid, show) ] for show in shows.itervalues()] for iid, shows in results.iteritems())) @@ -2791,7 +3183,8 @@ class NewHomeAddShows(Home): ('%s.jpg' % show['id'], show['id']) return img_url - def _get_UWRatio(self, search_term, showname, aliases): + @classmethod + def get_UWRatio(cls, search_term, showname, aliases): s = fuzz.UWRatio(search_term, showname) # check aliases and give them a little lower score for a in aliases: @@ -3452,15 +3845,9 @@ class NewHomeAddShows(Home): return self.redirect('/home/addShows/%s' % ('trakt_trending', sickbeard.TRAKT_MRU)[any(sickbeard.TRAKT_MRU)]) - def browse_trakt(self, url_path, browse_title, *args, **kwargs): - - browse_type = 'Trakt' + @staticmethod + def get_trakt_data(url_path, *args, **kwargs): normalised, filtered = ([], []) - - if not sickbeard.USE_TRAKT and ('recommended' in kwargs.get('mode', '') or 'watchlist' in kwargs.get('mode', '')): - error_msg = 'To browse personal recommendations, enable Trakt.tv in Config/Notifications/Social' - return self.browse_shows(browse_type, browse_title, filtered, error_msg=error_msg, show_header=1, **kwargs) - error_msg = None try: account = kwargs.get('send_oauth', None) @@ -3488,7 +3875,7 @@ class NewHomeAddShows(Home): if not normalised: error_msg = 'No items in watchlist. Use the "Add to watchlist" button at the Trakt website' - return self.browse_shows(browse_type, browse_title, filtered, error_msg=error_msg, show_header=1, **kwargs) + raise Exception(error_msg) oldest_dt = 9999999 newest_dt = 0 @@ -3496,8 +3883,8 @@ class NewHomeAddShows(Home): newest = None for item in normalised: ignore = ''' - ((bbc|channel\s*?5.*?|itv)\s*?(drama|documentaries))|bbc\s*?(comedy|music)|music\s*?specials|tedtalks - ''' + ((bbc|channel\s*?5.*?|itv)\s*?(drama|documentaries))|bbc\s*?(comedy|music)|music\s*?specials|tedtalks + ''' if re.search(ignore, item['show']['title'].strip(), re.I | re.X): continue try: @@ -3523,25 +3910,55 @@ class NewHomeAddShows(Home): when_past=dt_ordinal < datetime.datetime.now().toordinal(), # air time not yet available 16.11.2015 episode_number='' if 'episode' not in item else item['episode']['number'] or 1, episode_overview=('' if 'episode' not in item else - self.encode_html(item['episode']['overview'][:250:].strip()) or ''), + item['episode']['overview'].strip() or ''), episode_season='' if 'episode' not in item else item['episode']['season'] or 1, genres=('' if 'genres' not in item['show'] else ', '.join(['%s' % v for v in item['show']['genres']])), ids=item['show']['ids'], images=images, overview=('' if 'overview' not in item['show'] or None is item['show']['overview'] else - self.encode_html(item['show']['overview'][:250:].strip())), + item['show']['overview'].strip()), rating=0 < item['show'].get('rating', 0) and ('%.2f' % (item['show'].get('rating') * 10)).replace('.00', '') or 0, title=item['show']['title'].strip(), url_src_db='https://trakt.tv/shows/%s' % item['show']['ids']['slug'], url_tvdb=('', '%s%s' % (sickbeard.indexerApi(INDEXER_TVDB).config['show_url'], - item['show']['ids']['tvdb']))[isinstance(item['show']['ids']['tvdb'], (int, long)) - and 0 < item['show']['ids']['tvdb']], + item['show']['ids']['tvdb']))[ + isinstance(item['show']['ids']['tvdb'], (int, long)) + and 0 < item['show']['ids']['tvdb']], votes='0' if 'votes' not in item['show'] else item['show']['votes'])) - except: + except (StandardError, Exception): pass + if 'web_ui' in kwargs: + return filtered, oldest, newest, error_msg + + return filtered, oldest, newest + + def browse_trakt(self, url_path, browse_title, *args, **kwargs): + + browse_type = 'Trakt' + normalised, filtered = ([], []) + + if not sickbeard.USE_TRAKT and ('recommended' in kwargs.get('mode', '') or 'watchlist' in kwargs.get('mode', '')): + error_msg = 'To browse personal recommendations, enable Trakt.tv in Config/Notifications/Social' + return self.browse_shows(browse_type, browse_title, filtered, error_msg=error_msg, show_header=1, **kwargs) + + try: + filtered, oldest, newest, error_msg = self.get_trakt_data(url_path, web_ui=True, + send_oauth=kwargs.get('send_oauth', None)) + except (StandardError, Exception): + error_msg = 'No items in watchlist. Use the "Add to watchlist" button at the Trakt website' + return self.browse_shows(browse_type, browse_title, filtered, error_msg=error_msg, show_header=1, **kwargs) + + for item in filtered: + key = 'episode_overview' + if item[key]: + item[key] = self.encode_html(item[key][:250:].strip()) + key = 'overview' + if item[key]: + item[key] = self.encode_html(item[key][:250:].strip()) + kwargs.update(dict(oldest=oldest, newest=newest, error_msg=error_msg)) if 'recommended' not in kwargs.get('mode', '') and 'watchlist' not in kwargs.get('mode', ''): @@ -4541,7 +4958,7 @@ class Manage(MainHandler): for release in toRemove: item = re.sub('_{3,}', '%', release) - myDB.action('DELETE FROM failed WHERE release like ?', [item]) + myDB.action('DELETE FROM failed WHERE `release` like ?', [item]) if toRemove: return self.redirect('/manage/failedDownloads/') @@ -4567,12 +4984,6 @@ class ManageSearches(Manage): t.recent_search_status = sickbeard.searchQueueScheduler.action.is_recentsearch_in_progress() t.find_propers_status = sickbeard.searchQueueScheduler.action.is_propersearch_in_progress() t.queue_length = sickbeard.searchQueueScheduler.action.queue_length() - t.provider_fail_stats = filter(lambda stat: len(stat['fails']), [{ - 'active': p.is_active(), 'name': p.name, 'prov_id': p.get_id(), 'prov_img': p.image_name(), - 'fails': p.fails.fails_sorted, 'tmr_limit_time': p.tmr_limit_time, - 'next_try': p.get_next_try_time, 'has_limit': getattr(p, 'has_limit', False)} - for p in sickbeard.providerList + sickbeard.newznabProviderList]) - t.provider_fails = 0 < len([p for p in t.provider_fail_stats if len(p['fails'])]) t.submenu = self.ManageMenu('Search') @@ -4696,73 +5107,168 @@ class showProcesses(Manage): class History(MainHandler): - def index(self, limit=100): - # sqlResults = myDB.select('SELECT h.*, show_name, name FROM history h, tv_shows s, tv_episodes e WHERE h.showid=s.indexer_id AND h.showid=e.showid AND h.season=e.season AND h.episode=e.episode ORDER BY date DESC LIMIT '+str(numPerPage*(p-1))+', '+str(numPerPage)) - myDB = db.DBConnection() - if limit == '0': - sqlResults = myDB.select( - 'SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.indexer_id ORDER BY date DESC') - else: - sqlResults = myDB.select( - 'SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.indexer_id ORDER BY date DESC LIMIT ?', - [limit]) - - history = {'show_id': 0, 'season': 0, 'episode': 0, 'quality': 0, - 'actions': [{'time': '', 'action': '', 'provider': ''}]} - compact = [] - - for sql_result in sqlResults: - - if not any((history['show_id'] == sql_result['showid'] - and history['season'] == sql_result['season'] - and history['episode'] == sql_result['episode'] - and history['quality'] == sql_result['quality']) - for history in compact): - - history = {} - history['show_id'] = sql_result['showid'] - history['season'] = sql_result['season'] - history['episode'] = sql_result['episode'] - history['quality'] = sql_result['quality'] - history['show_name'] = sql_result['show_name'] - history['resource'] = sql_result['resource'] - - action = {} - history['actions'] = [] - - action['time'] = sql_result['date'] - action['action'] = sql_result['action'] - action['provider'] = sql_result['provider'] - action['resource'] = sql_result['resource'] - history['actions'].append(action) - history['actions'].sort(key=lambda x: x['time']) - compact.append(history) - else: - index = [i for i, dict in enumerate(compact) \ - if dict['show_id'] == sql_result['showid'] \ - and dict['season'] == sql_result['season'] \ - and dict['episode'] == sql_result['episode'] - and dict['quality'] == sql_result['quality']][0] - - action = {} - history = compact[index] - - action['time'] = sql_result['date'] - action['action'] = sql_result['action'] - action['provider'] = sql_result['provider'] - action['resource'] = sql_result['resource'] - history['actions'].append(action) - history['actions'].sort(key=lambda x: x['time'], reverse=True) + flagname_help_watched = 'ui_history_help_watched_supported_clients' + flagname_wdf = 'ui_history_watched_delete_files' + flagname_wdr = 'ui_history_watched_delete_records' + + def toggle_help(self): + db.DBConnection().toggle_flag(self.flagname_help_watched) + + def index(self, limit=100): t = PageTemplate(headers=self.request.headers, file='history.tmpl') - t.historyResults = sqlResults - t.compactResults = compact t.limit = limit - t.submenu = [ - {'title': 'Clear History', 'path': 'history/clearHistory'}, - {'title': 'Trim History', 'path': 'history/trimHistory'}, - ] + + my_db = db.DBConnection(row_type='dict') + + result_sets = [] + if sickbeard.HISTORY_LAYOUT in ('compact', 'detailed'): + + # sqlResults = myDB.select('SELECT h.*, show_name, name FROM history h, tv_shows s, tv_episodes e + # WHERE h.showid=s.indexer_id AND h.showid=e.showid AND h.season=e.season AND h.episode=e.episode + # ORDER BY date DESC LIMIT '+str(numPerPage*(p-1))+', '+str(numPerPage)) + sql = 'SELECT h.*, show_name' \ + ' FROM history h, tv_shows s' \ + ' WHERE h.showid=s.indexer_id' \ + ' ORDER BY date DESC%s' % (' LIMIT %s' % limit, '')['0' == limit] + sql_results = my_db.select(sql) + + compact = [] + + for sql_result in sql_results: + + action = dict(time=sql_result['date'], action=sql_result['action'], + provider=sql_result['provider'], resource=sql_result['resource']) + + if not any((record['show_id'] == sql_result['showid'] + and record['season'] == sql_result['season'] + and record['episode'] == sql_result['episode'] + and record['quality'] == sql_result['quality']) for record in compact): + + cur_res = dict(show_id=sql_result['showid'], show_name=sql_result['show_name'], + season=sql_result['season'], episode=sql_result['episode'], + quality=sql_result['quality'], resource=sql_result['resource'], actions=[]) + + cur_res['actions'].append(action) + cur_res['actions'].sort(key=lambda x: x['time']) + + compact.append(cur_res) + else: + index = [i for i, record in enumerate(compact) + if record['show_id'] == sql_result['showid'] + and record['season'] == sql_result['season'] + and record['episode'] == sql_result['episode'] + and record['quality'] == sql_result['quality']][0] + + cur_res = compact[index] + + cur_res['actions'].append(action) + cur_res['actions'].sort(key=lambda x: x['time'], reverse=True) + + t.compact_results = compact + t.history_results = sql_results + t.submenu = [{'title': 'Clear History', 'path': 'history/clearHistory'}, + {'title': 'Trim History', 'path': 'history/trimHistory'}] + + result_sets = ['compact_results', 'history_results'] + + elif 'watched' in sickbeard.HISTORY_LAYOUT: + + t.hide_watched_help = my_db.has_flag(self.flagname_help_watched) + + t.results = my_db.select( + 'SELECT tvs.show_name, ' + ' tve.indexer, tve.showid, tve.season, tve.episode, tve.status, tve.file_size,' + ' tvew.rowid, tvew.tvep_id, tvew.label, tvew.played, tvew.date_watched,' + ' tvew.status as status_w, tvew.location, tvew.file_size as file_size_w, tvew.hide' + ' FROM [tv_shows] AS tvs' + ' INNER JOIN [tv_episodes] AS tve ON (tvs.indexer == tve.indexer AND tvs.indexer_id == tve.showid)' + ' INNER JOIN [tv_episodes_watched] AS tvew ON (tve.episode_id == tvew.tvep_id)' + ' WHERE 0 = hide' + ' ORDER BY tvew.date_watched DESC' + '%s' % (' LIMIT %s' % limit, '')['0' == limit]) + + mru_count = {} + t.mru_row_ids = [] + for r in t.results: + r['deleted'] = False + no_file = not helpers.get_size(r['location']) + if no_file or not r['file_size']: # if not filesize, possible file recovered so restore known size + if no_file: + # file no longer available, can be due to upgrade, so use known details + r['deleted'] = True + r['status'] = r['status_w'] + r['file_size'] = r['file_size_w'] + + r['status'], r['quality'] = Quality.splitCompositeStatus(helpers.tryInt(r['status'])) + r['season'], r['episode'] = '%02i' % r['season'], '%02i' % r['episode'] + if r['tvep_id'] not in mru_count: + # depends on SELECT ORDER BY date_watched DESC to determine mru_count + mru_count.update({r['tvep_id']: r['played']}) + t.mru_row_ids += [r['rowid']] + r['mru_count'] = mru_count[r['tvep_id']] + + result_sets = ['results'] + + # restore state of delete dialog + t.last_delete_files = my_db.has_flag(self.flagname_wdf) + t.last_delete_records = my_db.has_flag(self.flagname_wdr) + + elif 'stats' in sickbeard.HISTORY_LAYOUT: + + prov_list = [p.name for p in (sickbeard.providerList + + sickbeard.newznabProviderList + + sickbeard.torrentRssProviderList)] + sql = 'SELECT COUNT(1) as count,' \ + ' MIN(DISTINCT date) as earliest,' \ + ' MAX(DISTINCT date) as latest,' \ + ' provider ' \ + 'FROM ' \ + '(SELECT * FROM history h, tv_shows s' \ + ' WHERE h.showid=s.indexer_id' \ + ' AND h.provider in ("%s")' % '","'.join(prov_list) + \ + ' AND h.action in ("%s")' % '","'.join([str(x) for x in Quality.SNATCHED_ANY]) + \ + ' ORDER BY date DESC%s)' % (' LIMIT %s' % limit, '')['0' == limit] + \ + ' GROUP BY provider' \ + ' ORDER BY count DESC' + t.stat_results = my_db.select(sql) + + t.earliest = 0 + t.latest = 0 + for r in t.stat_results: + if r['latest'] > t.latest or not t.latest: + t.latest = r['latest'] + if r['earliest'] < t.earliest or not t.earliest: + t.earliest = r['earliest'] + + elif 'failures' in sickbeard.HISTORY_LAYOUT: + + t.provider_fail_stats = filter(lambda stat: len(stat['fails']), [{ + 'active': p.is_active(), 'name': p.name, 'prov_id': p.get_id(), 'prov_img': p.image_name(), + 'fails': p.fails.fails_sorted, 'tmr_limit_time': p.tmr_limit_time, + 'next_try': p.get_next_try_time, 'has_limit': getattr(p, 'has_limit', False)} + for p in sickbeard.providerList + sickbeard.newznabProviderList]) + t.provider_fail_stats = sorted([item for item in t.provider_fail_stats], + key=lambda y: y.get('fails')[0].get('timestamp'), + reverse=True) + t.provider_fail_stats = sorted([item for item in t.provider_fail_stats], + key=lambda y: y.get('next_try') or datetime.timedelta(weeks=65535), + reverse=False) + + t.provider_fails = 0 < len([p for p in t.provider_fail_stats if len(p['fails'])]) + + article_match = '^((?:A(?!\s+to)n?)|The)\s+(.*)$' + for rs in [getattr(t, name, []) for name in result_sets]: + for r in rs: + r['name1'] = '' + r['name2'] = r['data_name'] = r['show_name'] + if not sickbeard.SORT_ARTICLE: + try: + r['name1'], r['name2'] = re.findall(article_match, r['show_name'])[0] + r['data_name'] = r['name2'] + except (StandardError, Exception): + pass return t.respond() @@ -4783,6 +5289,271 @@ class History(MainHandler): ui.notifications.message('Removed history entries greater than 30 days old') self.redirect('/history/') + @staticmethod + def update_watched_state_emby(): + + import sickbeard.notifiers.emby as emby + + client = emby.EmbyNotifier() + hosts, keys, message = client.check_config(sickbeard.EMBY_HOST, sickbeard.EMBY_APIKEY) + + if sickbeard.USE_EMBY and hosts: + logger.log('Updating Emby watched episode states', logger.DEBUG) + + rd = sickbeard.ROOT_DIRS.split('|')[1:] + \ + [x.split('=')[0] for x in sickbeard.EMBY_PARENT_MAPS.split(',') if any(x)] + rootpaths = sorted( + ['%s%s' % (ek.ek(os.path.splitdrive, x)[1], os.path.sep) for x in rd], key=len, reverse=True) + rootdirs = sorted([x for x in rd], key=len, reverse=True) + headers = {'Content-type': 'application/json'} + states = {} + idx = 0 + mapped = 0 + mapping = None + maps = [x.split('=') for x in sickbeard.EMBY_PARENT_MAPS.split(',') if any(x)] + for i, cur_host in enumerate(hosts): + base_url = 'http://%s/emby/Users' % cur_host + headers.update({'X-MediaBrowser-Token': keys[i]}) + + users = sickbeard.helpers.getURL(base_url, headers=headers, + params=dict(format='json'), timeout=10, json=True) + + for user_id in [u.get('Id') for u in users if u.get('Id')]: + user_url = '%s/%s' % (base_url, user_id) + user = sickbeard.helpers.getURL(user_url, headers=headers, + params=dict(format='json'), timeout=10, json=True) + + for folder_id in user.get('Policy', {}).get('EnabledFolders') or []: + folder = sickbeard.helpers.getURL('%s/Items/%s' % (user_url, folder_id), headers=headers, + params=dict(format='json'), timeout=10, json=True) + + if 'tvshows' != folder.get('CollectionType', ''): + continue + + items = sickbeard.helpers.getURL('%s/Items' % user_url, headers=headers, + params=dict(SortBy='DatePlayed,SeriesSortName,SortName', + SortOrder='Descending', + IncludeItemTypes='Episode', + Recursive='true', + Fields='Path,UserData', + IsMissing='false', + IsVirtualUnaired='false', + StartIndex='0', Limit='100', + ParentId=folder_id, + Filters='IsPlayed', + format='json'), timeout=10, json=True) + for d in filter(lambda item: 'Episode' == item.get('Type', ''), items.get('Items')): + try: + root_dir_found = False + path_file = d.get('Path') + if not path_file: + continue + for index, p in enumerate(rootpaths): + if p in path_file: + path_file = ek.ek(os.path.join, rootdirs[index], + re.sub('.*?%s' % re.escape(p), '', path_file)) + root_dir_found = True + break + if not root_dir_found: + continue + states[idx] = dict( + path_file=path_file, + media_id=d['Id'], + played=(d.get('UserData', {}).get('PlayedPercentage') or + (d.get('UserData', {}).get('Played') and + d.get('UserData', {}).get('PlayCount') * 100) or 0), + label='%s%s{Emby}' % (user.get('Name', ''), bool(user.get('Name')) and ' ' or ''), + date_watched=sickbeard.sbdatetime.sbdatetime.totimestamp( + dateutil.parser.parse(d.get('UserData', {}).get('LastPlayedDate')))) + + for m in maps: + result, change = helpers.path_mapper(m[0], m[1], states[idx]['path_file']) + if change: + if not mapping: + mapping = (states[idx]['path_file'], result) + mapped += 1 + states[idx]['path_file'] = result + break + + idx += 1 + except(StandardError, Exception): + continue + if mapping: + logger.log('Folder mappings used, the first of %s is [%s] in Emby is [%s] in SickGear' % + (mapped, mapping[0], mapping[1]), logger.DEBUG) + + if states: + # Prune user removed items that are no longer being returned by API + my_db = db.DBConnection(row_type='dict') + media_paths = map(lambda (_, s): ek.ek(os.path.basename, s['path_file']), states.iteritems()) + my_db.select('DELETE FROM tv_episodes_watched WHERE hide=1 AND label LIKE "%%{Emby}" AND %s' % + ' AND '.join(['location NOT LIKE "%%%s"' % x for x in media_paths])) + + MainHandler.update_watched_state(states, False) + + logger.log('Finished updating Emby watched episode states') + + @staticmethod + def update_watched_state_plex(): + + hosts = [x.strip().lower() for x in sickbeard.PLEX_SERVER_HOST.split(',')] + if sickbeard.USE_PLEX and hosts: + logger.log('Updating Plex watched episode states', logger.DEBUG) + + from plex import Plex + import urllib2 + + plex = Plex(dict(username=sickbeard.PLEX_USERNAME, password=sickbeard.PLEX_PASSWORD, + section_filter_path=sickbeard.ROOT_DIRS.split('|')[1:] + + [x.split('=')[0] for x in sickbeard.PLEX_PARENT_MAPS.split(',') if any(x)])) + + states = {} + idx = 0 + played = 0 + mapped = 0 + mapping = None + maps = [x.split('=') for x in sickbeard.PLEX_PARENT_MAPS.split(',') if any(x)] + for cur_host in hosts: + parts = urllib2.splitport(cur_host) + if parts[0]: + plex.plex_host = parts[0] + if None is not parts[1]: + plex.plex_port = parts[1] + + plex.fetch_show_states() + + for k, v in plex.show_states.iteritems(): + if 0 < v.get('played') or 0: + played += 1 + states[idx] = v + states[idx]['label'] = '%s%s{Plex}' % (v['label'], bool(v['label']) and ' ' or '') + + for m in maps: + result, change = helpers.path_mapper(m[0], m[1], states[idx]['path_file']) + if change: + if not mapping: + mapping = (states[idx]['path_file'], result) + mapped += 1 + states[idx]['path_file'] = result + break + + idx += 1 + + logger.log('Fetched %s of %s played for host : %s' % (len(plex.show_states), played, cur_host), + logger.DEBUG) + if mapping: + logger.log('Folder mappings used, the first of %s is [%s] in Plex is [%s] in SickGear' % + (mapped, mapping[0], mapping[1]), logger.DEBUG) + + if states: + # Prune user removed items that are no longer being returned by API + my_db = db.DBConnection(row_type='dict') + media_paths = map(lambda (_, s): ek.ek(os.path.basename, s['path_file']), states.iteritems()) + my_db.select('DELETE FROM tv_episodes_watched WHERE hide=1 AND label LIKE "%%{Plex}" AND %s' % + ' AND '.join(['location NOT LIKE "%%%s"' % x for x in media_paths])) + + MainHandler.update_watched_state(states, False) + + logger.log('Finished updating Plex watched episode states') + + def watched(self, tvew_id=None, files=None, records=None): + + my_db = db.DBConnection(row_type='dict') + + # remember state of dialog + my_db.set_flag(self.flagname_wdf, files) + my_db.set_flag(self.flagname_wdr, records) + + ids = tvew_id.split('|') + if not (ids and any([files, records])): + return + + row_show_ids = {} + for show_detail in ids: + rowid, tvid, shoid = show_detail.split('-') + row_show_ids.update({int(rowid): {int(tvid): int(shoid)}}) + + sql_results = my_db.select( + 'SELECT rowid, tvep_id, label, location' + ' FROM [tv_episodes_watched] WHERE `rowid` in (%s)' % ','.join([str(k) for k in row_show_ids.keys()]) + ) + + h_records = [] + removed = [] + deleted = {} + attempted = [] + refresh = [] + for r in sql_results: + if files and r['location'] not in attempted and 0 < helpers.get_size(r['location'])\ + and ek.ek(os.path.isfile, r['location']): + # locations repeat with watch events but attempt to delete once + attempted += [r['location']] + + try: + if sickbeard.TRASH_REMOVE_SHOW: + ek.ek(send2trash, r['location']) + else: + ek.ek(os.remove, r['location']) + except OSError as e: + logger.log(u'Unable to delete file %s: %s' % (r['location'], str(e.strerror))) + + if not ek.ek(os.path.isfile, r['location']): + logger.log(u'Deleted file %s' % r['location']) + + deleted.update({r['tvep_id']: row_show_ids[r['rowid']]}) + if row_show_ids[r['rowid']] not in refresh: + # schedule a show for one refresh after deleting an arbitrary number of locations + refresh += [row_show_ids[r['rowid']]] + + if records: + if not r['label'].endswith('{Emby}') and not r['label'].endswith('{Plex}'): + r_del = my_db.action('DELETE FROM [tv_episodes_watched] WHERE `rowid` == ?', [r['rowid']]) + if 1 == r_del.rowcount: + h_records += ['%s-%s-%s' % (r['rowid'], k, v) for k, v in row_show_ids[r['rowid']].iteritems()] + else: + r_del = my_db.action('UPDATE [tv_episodes_watched] SET hide=1 WHERE `rowid` == ?', [r['rowid']]) + if 1 == r_del.rowcount: + removed += ['%s-%s-%s' % (r['rowid'], k, v) for k, v in row_show_ids[r['rowid']].iteritems()] + + updating = False + for epid, tvid_shoid_dict in deleted.iteritems(): + sql_results = my_db.select('SELECT season, episode FROM [tv_episodes] WHERE `episode_id` = %s' % epid) + for r in sql_results: + show = helpers.find_show_by_id(sickbeard.showList, tvid_shoid_dict) + ep_obj = show.getEpisode(r['season'], r['episode']) + for n in filter(lambda x: x.name.lower() in ('emby', 'kodi', 'plex'), + notifiers.NotifierFactory().get_enabled()): + if 'PLEX' == n.name: + if updating: + continue + updating = True + n.update_library(show=show, show_name=show.name, ep_obj=ep_obj) + + for tvid_shoid_dict in refresh: + try: + sickbeard.showQueueScheduler.action.refreshShow( + helpers.find_show_by_id(sickbeard.showList, tvid_shoid_dict)) + except (StandardError, Exception): + pass + + if not any([removed, h_records, len(deleted)]): + msg = 'No items removed and no files deleted' + else: + msg = [] + if deleted: + msg += ['%s %s media file%s' % ( + ('Permanently deleted', 'Trashed')[sickbeard.TRASH_REMOVE_SHOW], + len(deleted), helpers.maybe_plural(len(deleted)))] + elif removed: + msg += ['Removed %s watched history item%s' % (len(removed), helpers.maybe_plural(len(removed)))] + else: + msg += ['Deleted %s watched history item%s' % (len(h_records), helpers.maybe_plural(len(h_records)))] + msg = '
'.join(msg) + + ui.notifications.message('History : Watch', msg) + + return json.dumps(dict(success=h_records)) + class Config(MainHandler): @staticmethod @@ -4897,7 +5668,7 @@ class ConfigGeneral(Config): logger.log('Could not change Show Update Scheduler time: %s' % ex(e), logger.ERROR) sickbeard.TRASH_REMOVE_SHOW = config.checkbox_to_value(trash_remove_show) sickbeard.TRASH_ROTATE_LOGS = config.checkbox_to_value(trash_rotate_logs) - if not config.change_LOG_DIR(log_dir, web_log): + if not config.change_log_dir(log_dir, web_log): results += ['Unable to create directory ' + os.path.normpath(log_dir) + ', log directory not changed.'] if indexer_default: sickbeard.INDEXER_DEFAULT = config.to_int(indexer_default) @@ -4907,9 +5678,9 @@ class ConfigGeneral(Config): sickbeard.INDEXER_TIMEOUT = config.to_int(indexer_timeout) # Updates - config.change_VERSION_NOTIFY(config.checkbox_to_value(version_notify)) + config.schedule_version_notify(config.checkbox_to_value(version_notify)) sickbeard.AUTO_UPDATE = config.checkbox_to_value(auto_update) - config.change_UPDATE_FREQUENCY(update_frequency) + config.schedule_update(update_frequency) sickbeard.NOTIFY_ON_UPDATE = config.checkbox_to_value(notify_on_update) # Interface @@ -4958,13 +5729,13 @@ class ConfigGeneral(Config): sickbeard.USE_API = config.checkbox_to_value(use_api) sickbeard.API_KEY = api_key sickbeard.WEB_PORT = config.to_int(web_port) - # sickbeard.WEB_LOG is set in config.change_LOG_DIR() + # sickbeard.WEB_LOG is set in config.change_log_dir() sickbeard.ENABLE_HTTPS = config.checkbox_to_value(enable_https) - if not config.change_HTTPS_CERT(https_cert): + if not config.change_https_cert(https_cert): results += [ 'Unable to create directory ' + os.path.normpath(https_cert) + ', https cert directory not changed.'] - if not config.change_HTTPS_KEY(https_key): + if not config.change_https_key(https_key): results += [ 'Unable to create directory ' + os.path.normpath(https_key) + ', https key directory not changed.'] @@ -4982,7 +5753,7 @@ class ConfigGeneral(Config): sickbeard.PROXY_SETTING = proxy_setting sickbeard.PROXY_INDEXERS = config.checkbox_to_value(proxy_indexers) sickbeard.FILE_LOGGING_PRESET = file_logging_preset - # sickbeard.LOG_DIR is set in config.change_LOG_DIR() + # sickbeard.LOG_DIR is set in config.change_log_dir() logger.log_set_level() @@ -5057,16 +5828,16 @@ class ConfigSearch(Config): results = [] - if not config.change_NZB_DIR(nzb_dir): + if not config.change_nzb_dir(nzb_dir): results += ['Unable to create directory ' + os.path.normpath(nzb_dir) + ', dir not changed.'] - if not config.change_TORRENT_DIR(torrent_dir): + if not config.change_torrent_dir(torrent_dir): results += ['Unable to create directory ' + os.path.normpath(torrent_dir) + ', dir not changed.'] - config.change_RECENTSEARCH_FREQUENCY(recentsearch_frequency) + config.schedule_recentsearch(recentsearch_frequency) old_backlog_frequency = sickbeard.BACKLOG_FREQUENCY - config.change_BACKLOG_FREQUENCY(backlog_frequency) + config.schedule_backlog(backlog_frequency) sickbeard.search_backlog.BacklogSearcher.change_backlog_parts(old_backlog_frequency, sickbeard.BACKLOG_FREQUENCY) sickbeard.BACKLOG_DAYS = config.to_int(backlog_days, default=7) @@ -5085,7 +5856,7 @@ class ConfigSearch(Config): sickbeard.IGNORE_WORDS = ignore_words if ignore_words else '' sickbeard.REQUIRE_WORDS = require_words if require_words else '' - config.change_DOWNLOAD_PROPERS(config.checkbox_to_value(download_propers)) + config.schedule_download_propers(config.checkbox_to_value(download_propers)) sickbeard.PROPERS_WEBDL_ONEGRP = config.checkbox_to_value(propers_webdl_onegrp) sickbeard.SEARCH_UNAIRED = bool(config.checkbox_to_value(search_unaired)) @@ -5156,14 +5927,12 @@ class ConfigPostProcessing(Config): results = [] - if not config.change_TV_DOWNLOAD_DIR(tv_download_dir): + if not config.change_tv_download_dir(tv_download_dir): results += ['Unable to create directory ' + os.path.normpath(tv_download_dir) + ', dir not changed.'] new_val = config.checkbox_to_value(process_automatically) sickbeard.PROCESS_AUTOMATICALLY = new_val - sickbeard.autoPostProcesserScheduler.check_paused() - - config.change_AUTOPOSTPROCESSER_FREQUENCY(autopostprocesser_frequency) + config.schedule_autopostprocesser(autopostprocesser_frequency) if unpack: if self.isRarSupported() != 'not supported': @@ -5720,11 +6489,13 @@ class ConfigNotifications(Config): def save_notifications( self, - use_emby=None, emby_update_library=None, emby_host=None, emby_apikey=None, + use_emby=None, emby_update_library=None, emby_watched_interval=None, emby_parent_maps=None, + emby_host=None, emby_apikey=None, use_kodi=None, kodi_always_on=None, kodi_update_library=None, kodi_update_full=None, - kodi_update_onlyfirst=None, kodi_host=None, kodi_username=None, kodi_password=None, + kodi_update_onlyfirst=None, kodi_parent_maps=None, kodi_host=None, kodi_username=None, kodi_password=None, kodi_notify_onsnatch=None, kodi_notify_ondownload=None, kodi_notify_onsubtitledownload=None, - use_plex=None, plex_update_library=None, plex_username=None, plex_password=None, plex_server_host=None, + use_plex=None, plex_update_library=None, plex_watched_interval=None, plex_parent_maps=None, + plex_username=None, plex_password=None, plex_server_host=None, plex_notify_onsnatch=None, plex_notify_ondownload=None, plex_notify_onsubtitledownload=None, plex_host=None, # use_xbmc=None, xbmc_always_on=None, xbmc_notify_onsnatch=None, xbmc_notify_ondownload=None, # xbmc_notify_onsubtitledownload=None, xbmc_update_onlyfirst=None, @@ -5779,6 +6550,7 @@ class ConfigNotifications(Config): sickbeard.USE_EMBY = config.checkbox_to_value(use_emby) sickbeard.EMBY_UPDATE_LIBRARY = config.checkbox_to_value(emby_update_library) + sickbeard.EMBY_PARENT_MAPS = config.kv_csv(emby_parent_maps) sickbeard.EMBY_HOST = config.clean_hosts(emby_host) keys_changed = False all_keys = [] @@ -5804,6 +6576,7 @@ class ConfigNotifications(Config): sickbeard.KODI_UPDATE_LIBRARY = config.checkbox_to_value(kodi_update_library) sickbeard.KODI_UPDATE_FULL = config.checkbox_to_value(kodi_update_full) sickbeard.KODI_UPDATE_ONLYFIRST = config.checkbox_to_value(kodi_update_onlyfirst) + sickbeard.KODI_PARENT_MAPS = config.kv_csv(kodi_parent_maps) sickbeard.KODI_HOST = config.clean_hosts(kodi_host) sickbeard.KODI_USERNAME = kodi_username if set('*') != set(kodi_password): @@ -5827,11 +6600,14 @@ class ConfigNotifications(Config): sickbeard.PLEX_NOTIFY_ONDOWNLOAD = config.checkbox_to_value(plex_notify_ondownload) sickbeard.PLEX_NOTIFY_ONSUBTITLEDOWNLOAD = config.checkbox_to_value(plex_notify_onsubtitledownload) sickbeard.PLEX_UPDATE_LIBRARY = config.checkbox_to_value(plex_update_library) + sickbeard.PLEX_PARENT_MAPS = config.kv_csv(plex_parent_maps) sickbeard.PLEX_HOST = config.clean_hosts(plex_host) sickbeard.PLEX_SERVER_HOST = config.clean_hosts(plex_server_host) sickbeard.PLEX_USERNAME = plex_username if set('*') != set(plex_password): sickbeard.PLEX_PASSWORD = plex_password + config.schedule_emby_watched(emby_watched_interval) + config.schedule_plex_watched(plex_watched_interval) sickbeard.USE_GROWL = config.checkbox_to_value(use_growl) sickbeard.GROWL_NOTIFY_ONSNATCH = config.checkbox_to_value(growl_notify_onsnatch) @@ -6002,14 +6778,14 @@ class ConfigSubtitles(Config): t.submenu = self.ConfigMenu('Subtitle') return t.respond() - def saveSubtitles(self, use_subtitles=None, subtitles_plugins=None, subtitles_languages=None, subtitles_dir=None, + def saveSubtitles(self, use_subtitles=None, subtitles_languages=None, subtitles_dir=None, service_order=None, subtitles_history=None, subtitles_finder_frequency=None): results = [] if subtitles_finder_frequency == '' or subtitles_finder_frequency is None: subtitles_finder_frequency = 1 - config.change_USE_SUBTITLES(config.checkbox_to_value(use_subtitles)) + config.schedule_subtitles(config.checkbox_to_value(use_subtitles)) sickbeard.SUBTITLES_LANGUAGES = [lang.alpha2 for lang in subtitles.isValidLanguage( subtitles_languages.replace(' ', '').split(','))] if subtitles_languages != '' else '' sickbeard.SUBTITLES_DIR = subtitles_dir @@ -6235,6 +7011,8 @@ class ApiBuilder(MainHandler): t.seasonSQLResults = seasonSQLResults t.episodeSQLResults = episodeSQLResults + t.indexers = sickbeard.indexerApi().all_indexers + t.searchindexers = sickbeard.indexerApi().search_indexers if len(sickbeard.API_KEY) == 32: t.apikey = sickbeard.API_KEY diff --git a/sickbeard/webserveInit.py b/sickbeard/webserveInit.py index 9613082..348de4e 100644 --- a/sickbeard/webserveInit.py +++ b/sickbeard/webserveInit.py @@ -93,6 +93,10 @@ class WebServer(threading.Thread): # javascript (r'%s/js/(.*)' % self.options['web_root'], webserve.BaseStaticFileHandler, {'path': os.path.join(self.options['data_root'], 'js')}), + + (r'%s/kodi/(.*)' % self.options['web_root'], webserve.RepoHandler, + {'path': os.path.join(sickbeard.CACHE_DIR, 'clients', 'kodi'), + 'default_filename': 'index.html'}), ]) # Main Handler diff --git a/tests/name_parser_tests.py b/tests/name_parser_tests.py index cfee716..f1742da 100644 --- a/tests/name_parser_tests.py +++ b/tests/name_parser_tests.py @@ -43,6 +43,13 @@ simple_test_cases = { parser.ParseResult(None, 'Show Name', 1, [2], 'Source.Quality.Etc', 'Group'), }, + 'non_standard_multi_ep': { + 'Show Name - S01E02and03 - My Ep Name': parser.ParseResult(None, 'Show Name', 1, [2, 3], 'My Ep Name'), + 'Show Name - S01E02and03and04 - My Ep Name': parser.ParseResult(None, 'Show Name', 1, [2, 3, 4], 'My Ep Name'), + 'Show Name - S01E02to03 - My Ep Name': parser.ParseResult(None, 'Show Name', 1, [2, 3], 'My Ep Name'), + 'Show Name - S01E02&3&4 - My Ep Name': parser.ParseResult(None, 'Show Name', 1, [2, 3, 4], 'My Ep Name'), + }, + 'fov': { 'Show_Name.1x02.Source_Quality_Etc-Group': parser.ParseResult(None, 'Show Name', 1, [2], 'Source_Quality_Etc', 'Group'), @@ -59,6 +66,11 @@ simple_test_cases = { 'Show.Name.1x02.WEB-DL': parser.ParseResult(None, 'Show Name', 1, [2], 'WEB-DL'), }, + 'fov_non_standard_multi_ep': { + 'Show_Name.1x02and03and04.Source_Quality_Etc-Group': + parser.ParseResult(None, 'Show Name', 1, [2, 3, 4], 'Source_Quality_Etc', 'Group'), + }, + 'standard_repeat': { 'Show.Name.S01E02.S01E03.Source.Quality.Etc-Group': parser.ParseResult(None, 'Show Name', 1, [2, 3], 'Source.Quality.Etc', 'Group'), @@ -429,7 +441,7 @@ class BasicTests(test.SickbeardTestDBCase): try: # self.assertEqual(test_result.which_regex, [section]) self.assertEqual(test_result, result) - except: + except(StandardError, Exception): print('air_by_date:', test_result.is_air_by_date, 'air_date:', test_result.air_date) print('anime:', test_result.is_anime, 'ab_episode_numbers:', test_result.ab_episode_numbers) print(test_result) @@ -444,6 +456,10 @@ class BasicTests(test.SickbeardTestDBCase): np = parser.NameParser(False, testing=True) self._test_names(np, 'standard_repeat') + def test_non_standard_multi_ep_names(self): + np = parser.NameParser(False, testing=True) + self._test_names(np, 'non_standard_multi_ep') + def test_fov_names(self): np = parser.NameParser(False, testing=True) self._test_names(np, 'fov') @@ -452,6 +468,10 @@ class BasicTests(test.SickbeardTestDBCase): np = parser.NameParser(False, testing=True) self._test_names(np, 'fov_repeat') + def test_fov_non_standard_multi_ep_names(self): + np = parser.NameParser(False, testing=True) + self._test_names(np, 'fov_non_standard_multi_ep') + def test_bare_names(self): np = parser.NameParser(False, testing=True) self._test_names(np, 'bare')