text
stringlengths 3
1.05M
|
|---|
import os
import random
from OpenSSL import crypto
from conpaas.core.misc import file_get_contents
from conpaas.core.https import x509
def create_x509_cert(cert_dir, x509_req):
# Load the CA cert
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
file_get_contents(os.path.join(cert_dir, "ca_cert.pem")))
# Load private key
key = crypto.load_privatekey(crypto.FILETYPE_PEM,
file_get_contents(os.path.join(cert_dir, "ca_key.pem")))
# Generate serial number
serial = random.randint(1, 2048)
# Valid for one year starting from now
not_before = 0
not_after = 60 * 60 * 24 * 365
newcert = x509.create_cert(x509_req,
ca_cert, key, serial, not_before, not_after)
return crypto.dump_certificate(crypto.FILETYPE_PEM, newcert)
def generate_certificate(cert_dir, uid, sid, role, email, cn, org, ca_cert=None):
"""Generates a new x509 certificate for a manager from scratch.
Creates a key, a request and then the certificate."""
# Get CA cert
if ca_cert is None:
ca_cert = file_get_contents(os.path.join(cert_dir, "ca_cert.pem"))
# Generate keypair
req_key = x509.gen_rsa_keypair()
# Generate certificate request
x509_req = x509.create_x509_req(req_key, userId=uid, serviceLocator=sid,
O=org, emailAddress=email, CN=cn, role=role)
# Sign the request
certificate = create_x509_cert(cert_dir, x509_req)
return { 'ca_cert': ca_cert,
'key': crypto.dump_privatekey(crypto.FILETYPE_PEM, req_key),
'cert': certificate }
def get_cert_cname(cert_dir):
"""Return the CNAME value of director's certificate"""
cert = crypto.load_certificate(crypto.FILETYPE_PEM,
file_get_contents(os.path.join(cert_dir, "cert.pem")))
subject = cert.get_subject()
return [ el[1] for el in subject.get_components() if el[0] == 'CN' ][0]
|
Date.prototype.format = function (format) {
const date = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S+": this.getMilliseconds(),
};
if (/(y+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (const k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
};
export const formatDate = now => {
const year = now.getYear();
const month = now.getMonth() + 1;
const date = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
};
|
/* =====================================================================
* Project: PULP DSP Library
* Title: plp_mat_fill_stride_i8.c
* Description: 16-bit integer strided matrix fill glue code
*
* $Date: 17. July 2020
* $Revision: V0
*
* Target Processor: PULP cores
* ===================================================================== */
/*
* Copyright (C) 2020 ETH Zurich and Ubiversity of Bologna. All rights reserved.
*
* Author: Tibor Schneider, ETH Zurich
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plp_math.h"
/**
@ingroup groupMatrixStride
*/
/**
@addtogroup MatFillStride
@{
*/
/**
@brief Glue code for filling an MxN strided 8-bit integers matrix
@param[in] M Height of the matrix
@param[in] N Width of the matrix
@param[in] stride Stride of the matrix (elements between each row)
@param[out] pSrc Points to the output matrix
@return none
*/
void plp_mat_fill_stride_i8(
uint32_t M, uint32_t N, uint32_t stride, int8_t value, int8_t *__restrict__ pDst) {
if (rt_cluster_id() == ARCHI_FC_CID) {
plp_mat_fill_stride_i8s_rv32im(M, N, stride, value, pDst);
} else {
plp_mat_fill_stride_i8s_xpulpv2(M, N, stride, value, pDst);
}
}
/**
@} end of MatFillStride group
*/
|
"""Strip empty tags
Improved version of patched_extract()
Status: In Progress
"""
from GDLC import GDLC
from bs4 import BeautifulSoup
# Usage:
def strip_empty_tags(soup:BeautifulSoup):
for item in soup.find_all():
if not item.get_text(strip=True):
item.destroy() # This method to be added to PageElement, see below
return soup
# based on BeautifulSoup extract(), decompose(), smooth() methods:
# import PageElement if it has not been imported already
import sys
if 'PageElement' not in sys.modules:
from bs4 import PageElement
def debug_destroy(self, pos):
if pos == 1:
try:
__self_index = self.parent.index(self)
except:
pass
try:
print('DEBUG 1: self = \n\n', self, '\n\n')
except:
pass
try:
print('DEBUG 2: self.parent.contents[_self_index] = \n\n', self.parent.contents[__self_index], '\n\n')
except:
pass
try:
print('DEBUG 3: self.contents[_self_index-1] = \n\n', self.contents[__self_index-1], '\n\n')
except:
pass
try:
print('DEBUG 4: self.contents[_self_index+1] = \n\n', self.contents[__self_index+1], '\n\n')
except:
pass
try:
print('DEBUG 5: self._last_descendant() = \n\n', self._last_descendant(), '\n\n')
except:
pass
try:
print('DEBUG 6: self._last_descendant().next_element = \n\n', self._last_descendant().next_element, '\n\n')
except:
pass
try:
print('DEBUG 7: self._last_descendant().previous_element = \n\n', self._last_descendant().previous_element, '\n\n')
except:
pass
if pos == 2:
try:
print('DEBUG 8: self.__dict__. = \n\n', self.__dict__.)
except:
pass
if pos == 3:
try:
for i in self.contents[:]:
while i is not None:
n = i.next_element
print('DEBUG 9: self.contents[:].next_element = \n\n', i.next_element, '\n\n')
i = n
except:
pass
return None
def destroy(self, _self_index=None, debug=False):
"""Combines several elements of BeautifulSoup extract(), decompose(), smooth() methods.
Remove this element from the tree and its children.
:param _self_index: The location of this element in its parent's
.contents, if known. Passing this in allows for a performance
optimization.
:return: `self`, no longer part of the tree.
"""
if debug:
debug_destroy(self, 1)
# from extract() method
if self.parent is not None:
if _self_index is None:
_self_index = self.parent.index(self)
del self.parent.contents[_self_index]
# remove nearby parents if empty
# check that nearby parent.contents is empty before deleting:
try:
for i in range(_self_index-1, _self_index+1):
if str(self.parent.contents[i]).strip() == '':
del self.parent.contents[i]
except:
pass
# Find the two elements that would be next to each other if this
# element and children had not been parsed and connect them:
last_child = self._last_descendant()
next_element = last_child.next_element
if (self.previous_element is not None and
self.previous_element is not next_element):
self.previous_element.next_element = next_element
if next_element is not None and next_element is not self.previous_element:
next_element.previous_element = self.previous_element
self.previous_element = None
last_child.next_element = None
self.parent = None
if (self.previous_sibling is not None
and self.previous_sibling is not self.next_sibling):
self.previous_sibling.next_sibling = self.next_sibling
if (self.next_sibling is not None
and self.next_sibling is not self.previous_sibling):
self.next_sibling.previous_sibling = self.previous_sibling
self.previous_sibling = self.next_sibling = None
if debug:
debug_destroy(self, 3)
return self
# attach new method:
PageElement.destroy = destroy
# TESTING GROUND:
>>> dml = '''<html>
... <head>
... <title>TITLE</title>
... </head>
... <body>'LINE 0 AFTER OPENING BODY TAG FOLLOWED BY LINE BREAK'
... 'LINE 1 NO SPACE BEFORE DIV'<div>TEXT1</div>'LINE 1 NO SPACE AFTER DIV'
... 'LINE 2 NO SPACE BEFORE P'<p>TEXT2</p>'LINE 2 NO SPACE AFTER P'
... 'LINE 3 NO SPACE BEFORE DIV'<div><i>TEXT3</i></div> 'LINE 3 DOUBLE SPACE AFTER DIV'# COMMENT
... </body>'LINE 4 AFTER CLOSING BODY TAG'
... </html>'''
>>> dml = '''<html>
... <head>
... <title>TITLE</title>
... </head>
... <body>
... <div>TEXT1</div>
... <p>TEXT2</p>
... <div><i>TEXT3</i></div> # COMMENT
... </body>
... </html>'''
>>> soup = BeautifulSoup(dml, features='lxml')
>>> for tag in soup.find_all('div'):
>>> tag.destroy()
>>> print(soup)
dml = '''<html><body>TEXT_BEFORE <i>ITALIC</i> TEXT_AFTER</body></html>'''
soup = BeautifulSoup(dml, features='lxml')
tags = soup.find_all('i')
for i in tags:
print('parent = ', i.parent)
print('child = ', i.child)
print('descendent = ', i.descendent)
print('next_sibling = ', i.next_sibling)
print('previous_sibling = ', i.previous_sibling)
print('next_element = ', i.next_element)
print('previous_element = ', i.previous_element)
soup = BeautifulSoup(dml, features='lxml')
print('soup = ', soup)
for i in soup.find_all('i'):
print('i = ', i)
p = i.parent
print('i.parent = ', p)
pe = p.previous_element
print('p.previous_element = ', pe)
ne = p.next_element
print('p.next_element = ', ne)
# i.extract()
i.destroy(debug=False)
print('soup = ', soup)
soup.find_all()
def is_surrounded_by_spaces(tag: Tag) -> bool:
"""
True if tag is surrounded by empty spaces, False otherwise.
"""
from bs4 import NavigableString as NS
try:
lhs = tag.previous_element
rhs = tag.next_element
except:
return None
if isinstance(lhs, NS) and isinstance(rhs, NS):
if lhs.endswith(' ') and rhs.endswith(' '):
lhs.replace_with(lhs.rstrip())
return is_surrounded
|
// https://observablehq.com/@tomlarkworthy/viewroutine@304
async function _1(md,FileAttachment){return(
md`# Composing views across time: viewroutine
${await FileAttachment("viewroutine.png").image()}
Sometimes you want to put a sequence of UI steps in a single cell. Using inspiration drawn from Unity and Golang ([_coroutines_](https://docs.unity3d.com/Manual/Coroutines.html) and _goroutines_) checkout the _viewroutine_. A _viewroutine_ leans on Javascript's _async generator functions_ to compose views across time.
~~~
viewroutine(generator: async function*) => viewof
~~~
The import:-
~~~js
import {viewroutine, ask} from '@tomlarkworthy/viewroutine'
~~~
`
)}
function _2(md){return(
md`## What is a view again?
A view
- contains a visual DOM component (viewof foo)
- contains a data component (foo) as the value of the visual component (viewof foo.value)
- Emits _input_ events to signal listeners that the data value has changed
- Like all cells, the viewof cell can be a generator as well and be its own stream
(see also https://observablehq.com/@observablehq/introduction-to-views)
`
)}
function _3(md){return(
md`## What is an async generator?
Async generators
- Have a signature like _async foo*()_
- have intermediate return values in the body with _yield_
- can have a final return value with _return_
- can use _await_ in the body
- can bulk return the results of other generators with _yield*_
(see also https://observablehq.com/@observablehq/introduction-to-generators)
`
)}
function _4(md){return(
md`## Putting it together
The broad idea of a viewroutine, is that an async generator yields a stream of visual components, and we update an overarching span by setting its only child to be those stream of values. Thus, the span becomes a view that doesn't invalidate when the generator yields.
There are a few nice properties with this. You can have variables declared in the closure that are carried between yields. This can often replace the use of an overarching _mutable_ in Observable.
You can compose generators by using the _yield*_ syntax making things compose nicely.
You can on demand and programatically drive the sequence, wait for user input, make choices _etc._ You could probably build an entire app in this way, and it can be decomposed into functional pieces.
One other important aspect of views is programmatic control over when an input event is raised. The viewroutine will emit an event if yielded.
`
)}
function _5(md){return(
md`### Pattern we are trying to fix
We want to avoid stuffing a model into a mutable and asynchronously updating that from a dedicated input cell. It takes up too many cells and the use of mutable has lots of unexpected implications such as not working when imported from other notebooks
`
)}
function _nameOfThing(){return(
undefined
)}
function _newName(Inputs){return(
Inputs.text({
label: "please enter the name of the thing to create",
submit: true,
minlength: 1
})
)}
async function* _sideEffect(md,$0,newName)
{
yield md`<mark>updating`;
await new Promise(r => setTimeout(r, 1000));
$0.value = newName;
yield md`<mark>updated!!!`;
}
function _9(md){return(
md`## The viewroutine`
)}
function _viewroutine(Event){return(
function viewroutine(generator) {
let current;
const holder = Object.defineProperty(
document.createElement("span"),
"value",
{
get: () => current?.value,
set: (v) => (current ? (current.value = v) : null),
enumerable: true
}
);
new Promise(async () => {
const iterator = generator();
const n = await iterator.next();
let { done, value } = n;
while (!done) {
if (value instanceof Event) {
holder.dispatchEvent(value);
} else {
current = value;
if (holder.firstChild) holder.removeChild(holder.firstChild);
if (value) {
holder.appendChild(value);
}
}
({ done, value } = await iterator.next());
}
holder.remove();
});
return holder;
}
)}
function _11(md){return(
md`### Example`
)}
function _12(md){return(
md`_ask_ wraps any input. It yields the passed in input to be its visual representation, but its final return is the value submitted, which ends the routine (allowing an enclosing generator to continue with the sequence)`
)}
function _ask(){return(
async function* ask(input) {
let responder = null;
const response = new Promise(resolve => (responder = resolve));
input.addEventListener('input', () => responder(input.value));
yield input;
return await response;
}
)}
function _14(md){return(
md`Now we can do the same thing without a mutable, even carrying the inputed name in the first step to steps further along.`
)}
function _example1(viewroutine,ask,Inputs,md,htl){return(
viewroutine(async function*() {
let newName = undefined;
while (true) {
newName = yield* ask(
Inputs.text({
label: "please enter the name of the thing to create",
minlength: 1,
value: newName,
submit: true
})
);
yield md`<mark>updating to ${newName}`; // Note we can remember newName
await new Promise(r => setTimeout(r, 1000)); // Mock async action
yield* ask(htl.html`${md`<mark>updated`} ${Inputs.button("Again?")}`);
}
})
)}
function _16(example1){return(
example1
)}
function _17(md){return(
md`## Animation Example with return values
Mixing HTML with SVG and composing animations
`
)}
function _18(choice){return(
choice
)}
function _choice(viewroutine,choose,flashSquare,flashStar){return(
viewroutine(async function*() {
while (true) {
const choice = yield* choose();
if (choice == 'square') yield* flashSquare();
if (choice == 'star') yield* flashStar();
}
})
)}
function _choose(htl,Event){return(
async function* choose() {
let resolve;
yield Object.defineProperty(
htl.html`<button onclick=${() =>
resolve('star')}>click to play star</button>
<button onclick=${() =>
resolve('square')}>click to play square</button>`,
'value',
{
value: 'undecided'
}
);
yield new Event("input", { bubbles: true });
return await new Promise(function(_resolve) {
resolve = _resolve;
});
}
)}
function _flashSquare(html,Event,Promises){return(
async function* flashSquare() {
for (let index = 0; index < 360; index += 5) {
yield Object.defineProperty(
html`<span style="display:inline-block; width:50px;height:50px; background-color: hsl(${index}, 50%, 50%);"></span>`,
'value',
{
value: "square"
}
);
if (index === 0) yield new Event("input", { bubbles: true });
await Promises.delay(10);
}
}
)}
function _flashStar(htl,Event,Promises){return(
async function* flashStar() {
for (let index = 0; index < 360; index += 5) {
yield Object.defineProperty(
htl.svg`<svg height="50" width="50" viewbox="0 0 200 200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:hsl(${index}, 50%, 50%);" /></svg>`,
'value',
{
value: "star"
}
);
if (index === 0) yield new Event("input", { bubbles: true });
await Promises.delay(10);
}
}
)}
export default function define(runtime, observer) {
const main = runtime.module();
const fileAttachments = new Map([["viewroutine.png",new URL("./files/dec489daac2e4a27c49e9ac9241bdba2ecde9687d9d521364238e168fb6567278d156f3d630fe937db02352d6e47556fe14f9ddcb62ecaeb902ac85ea3f83ef9",import.meta.url)]]);
main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
main.variable(observer()).define(["md","FileAttachment"], _1);
main.variable(observer()).define(["md"], _2);
main.variable(observer()).define(["md"], _3);
main.variable(observer()).define(["md"], _4);
main.variable(observer()).define(["md"], _5);
main.define("initial nameOfThing", _nameOfThing);
main.variable(observer("mutable nameOfThing")).define("mutable nameOfThing", ["Mutable", "initial nameOfThing"], (M, _) => new M(_));
main.variable(observer("nameOfThing")).define("nameOfThing", ["mutable nameOfThing"], _ => _.generator);
main.variable(observer("viewof newName")).define("viewof newName", ["Inputs"], _newName);
main.variable(observer("newName")).define("newName", ["Generators", "viewof newName"], (G, _) => G.input(_));
main.variable(observer("sideEffect")).define("sideEffect", ["md","mutable nameOfThing","newName"], _sideEffect);
main.variable(observer()).define(["md"], _9);
main.variable(observer("viewroutine")).define("viewroutine", ["Event"], _viewroutine);
main.variable(observer()).define(["md"], _11);
main.variable(observer()).define(["md"], _12);
main.variable(observer("ask")).define("ask", _ask);
main.variable(observer()).define(["md"], _14);
main.variable(observer("viewof example1")).define("viewof example1", ["viewroutine","ask","Inputs","md","htl"], _example1);
main.variable(observer("example1")).define("example1", ["Generators", "viewof example1"], (G, _) => G.input(_));
main.variable(observer()).define(["example1"], _16);
main.variable(observer()).define(["md"], _17);
main.variable(observer()).define(["choice"], _18);
main.variable(observer("viewof choice")).define("viewof choice", ["viewroutine","choose","flashSquare","flashStar"], _choice);
main.variable(observer("choice")).define("choice", ["Generators", "viewof choice"], (G, _) => G.input(_));
main.variable(observer("choose")).define("choose", ["htl","Event"], _choose);
main.variable(observer("flashSquare")).define("flashSquare", ["html","Event","Promises"], _flashSquare);
main.variable(observer("flashStar")).define("flashStar", ["htl","Event","Promises"], _flashStar);
return main;
}
|
const colors = require("ansi-colors");
const parseCollection = require("./parseCollection");
const parseItem = require("./parseItem");
const choose = require("../../helperFunctions/enquirerPrompts/choose");
const retry = require("../../helperFunctions/retry");
const getPage = require("../../helperFunctions/blockOnPage");
const promisePool = require("../../helperFunctions/promisePool");
const Err = require("../../helperFunctions/err");
const selectFromList = require("../../helperFunctions/enquirerPrompts/selectList");
const articleResolver = async (
id,
finalItemDirectory,
browser,
pendingStage = []
) => {
const url = `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}&l=english`;
let page = await getPage(browser);
await retry(
async () => {
await page.goto(url, { waitUntil: "networkidle2" });
/* istanbul ignore next */
await page.waitForFunction(
() => {
return (
document.querySelector(".breadcrumbs") ||
document.querySelector(".error_ctn")
);
},
{ timeout: 20000 }
);
},
async (e) => {
await page.close();
page = await getPage(browser);
},
async () => {
const options = {
"Ignore this item": async () => {
console.log("IGNORING ITEM");
await page.close();
throw new Err("Unable to load steam page");
},
"Quit Program": async () => {
console.log("EXITING...");
await page.close();
process.exit();
},
};
const message = "Unable to load steam page. Choose one:";
await choose(message, options);
},
() => {}
);
if (await page.$(".error_ctn")) {
await page.close();
throw new Err("No such item found.", "FAIL");
}
/* istanbul ignore next */
const breadcrumbs = await page.$eval(".breadcrumbs", (str) => {
return str.innerText.toLowerCase();
});
const ofCitiesSkylines =
breadcrumbs.includes("cities") && breadcrumbs.includes("skylines");
if (!ofCitiesSkylines) {
await page.close();
throw new Err("Currently only supports mods for Cities: Skylines", "FAIL");
}
const isCollection = !!(await page.$(".collectionChildren"));
if (isCollection) {
const collectionDetails = await parseCollection(page);
console.log(`${colors.green(collectionDetails.title)} collection found`);
let res;
if (__edit) {
res = await selectFromList(
collectionDetails.collectionItems,
"Collection Items"
);
} else {
res = collectionDetails.collectionItems;
}
console.log(
colors.yellow("Grabbing rest of the details"),
`${colors.grey("(this may take a while)")}`
);
await promisePool(
res.map((item) => () => {
return articleResolver(item.id, finalItemDirectory, browser);
}),
8
);
} else {
const itemDetails = await parseItem(page);
if (itemDetails.requirements.length > 0) {
pendingStage.push(id);
//requirements are present
for (requirementId of itemDetails.requirements) {
if (
!finalItemDirectory[requirementId] &&
!pendingStage.includes(requirementId)
) {
try {
await articleResolver(
requirementId,
finalItemDirectory,
browser,
pendingStage
);
} catch (e) {
console.log(e.message);
}
}
}
pendingStage.pop();
}
itemDetails.id = id;
finalItemDirectory[id] = itemDetails;
}
};
module.exports = articleResolver;
|
from sympy.core.symbol import symbols
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \
PermuteDims, ArrayDiagonal
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
X = MatrixSymbol("X", k, k)
Y = MatrixSymbol("Y", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
def test_arrayexpr_convert_matrix_to_array():
expr = M*N
result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
assert convert_matrix_to_array(expr) == result
expr = M*N*M
result = ArrayContraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4))
assert convert_matrix_to_array(expr) == result
expr = Transpose(M)
assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0])
expr = M*Transpose(N)
assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, PermuteDims(N, [1, 0])), (1, 2))
expr = 3*M*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = 3*M + N*M.T*M + 4*k*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Inverse(M)*N
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M**2
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M*(2*N + 3*M)
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Trace(M)
result = ArrayContraction(M, (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)
result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(Trace(M) * M)
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)**2
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M, N)
result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M*N, N*M)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M, 2)
result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M*N, 2)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = M**2
assert isinstance(expr, MatPow)
assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2))
expr = a.T*b
cg = convert_matrix_to_array(expr)
assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2))
|
module.exports = {
HOST: "localhost",
PORT: 27017,
DB: "ticTacToe"
};
|
import numpy as np
import torch
from sklearn.externals import joblib
import cv2
import cpe775.utils.img_utils as utils
from .networks.openface import OpenFace
class Base(object):
def __init__(self, net, model, size, cuda=False):
self.net = net
self.model = model
self.cuda = cuda
self.size = size
if self.model is not None:
self.net.load_state_dict(torch.load(self.model)['state_dict'])
self.net.eval()
if self.cuda:
self.net.cuda()
def __call__(self, x, bgr=True, crop=None):
if bgr and x.shape[-1] == 3:
x = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)
x = cv2.resize(x, (self.size, self.size),
interpolation = cv2.INTER_CUBIC)
if crop is not None:
h, w = x.shape[:2]
th, tw = crop, crop
i = int(round((h - th) / 2.))
j = int(round((w - tw) / 2.))
x = x[i:i+th, j:j+tw, ...]
ndims = 4
if len(x.shape) == 2:
x = x[np.newaxis, ..., np.newaxis]
ndims = 2
elif len(x.shape) == 3: # W, H, C
x = x[np.newaxis, ...]
ndims = 3
# tranpose channel
x = x.transpose((0, 3, 1, 2))
if x.dtype == np.uint8:
x = x/255
x_var = torch.autograd.Variable(torch.from_numpy(x).float(), volatile=True)
if self.cuda:
x_var = x_var.cuda()
y = self.net(x_var).data.cpu().numpy()
if ndims != 4:
return y[0, ...]
return y
class LandmarksDetector(Base):
def __init__(self, net, model, size=256, cuda=False):
self.orig_size = size
super(LandmarksDetector, self).__init__(net, model, size, cuda)
def from_rect(self, image, rect, enlarge_ratio = 1.7, bgr=True, to_gray=True, crop=224):
rect = utils.rect_to_tuple(rect)
bbox = utils.get_bbox(*rect)
large_bbox = utils.enlarge_bbox(bbox, enlarge_ratio)
increased_img, large_bbox, x_extra_start, y_extra_start = utils.increase_img_size(image, large_bbox)
left, top, w, h = large_bbox
cropped_image = increased_img[top:top + h, left:left + w, :]
landmarks = self(cropped_image, bgr, to_gray, crop)
if crop is not None:
# Adjusting the center cropping
th, tw = crop, crop
i = int(round((self.size - th) / 2.))
j = int(round((self.size - tw) / 2.))
landmarks *= [tw, th]
landmarks += [j, i]
else:
landmarks *= [self.size, self.size]
landmarks *= [w/self.size, h/self.size]
landmarks -= [x_extra_start, y_extra_start]
landmarks += [left, top]
return landmarks, rect
def __call__(self, x, bgr=True, to_gray=True, crop=None):
if to_gray:
cvtColor = cv2.COLOR_BGR2GRAY if bgr else cv2.COLOR_RGB2GRAY
x = cv2.cvtColor(x, cvtColor)
y = super(LandmarksDetector, self).__call__(x, bgr, crop)
return y
class FaceEmbedding(Base):
def __init__(self, model, net=OpenFace(), size=96, cuda=False):
super(FaceEmbedding, self).__init__(net, model, size, cuda)
def __call__(self, x, bgr=True):
y = super(FaceEmbedding, self).__call__(x, bgr)
return y
class FaceClassify(object):
def __init__(self, model_path):
self.model, self.le = joblib.load(model_path)
def __call__(self, x):
ndims = 2
if len(x.shape) == 1:
x = x[np.newaxis, :]
ndims = 1
predictions = self.model.predict_proba(x)
if ndims == 1:
predictions = predictions[0, :]
max_idxs = np.argmax(predictions, axis=0)
return self.le.inverse_transform(max_idxs), predictions[..., max_idxs]
|
'use strict';
var gulp = require('gulp');
var rename = require('gulp-rename');
gulp.task('lint', function() {
var jshint = require('gulp-jshint');
gulp.src('./**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('browserify', function() {
var browserify = require('browserify');
var source = require('vinyl-source-stream');
return browserify('./public/javascript/room.js')
.bundle()
.pipe(source('room.bundle.js'))
.pipe(gulp.dest('./public/javascript/'));
});
gulp.task('minify-css', function() {
var minifyCss = require('gulp-minify-css');
return gulp.src(['!./**/*.min.css', 'public/stylesheet/**/*.css'])
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('public/stylesheet'));
});
gulp.task('minify-js', ['browserify'], function() {
var uglify = require('gulp-uglify');
return gulp.src(['!./**/*.min.js', './public/javascript/*.js'])
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./public/javascript/'));
});
gulp.task('start', ['lint', 'browserify'], function() {
var nodemon = require('gulp-nodemon');
nodemon({
script: 'app.js',
ext: 'js',
tasks: ['lint', 'browserify'],
ignore: ['*.bundle.js', '*.min.js'],
env: {'NODE_ENV': 'development'}
});
});
gulp.task('build:development', ['lint', 'browserify']);
gulp.task('build:production', ['minify-css', 'minify-js']);
gulp.task('default', ['start']);
|
(function(d){d['ro']=Object.assign(d['ro']||{},{a:"Nu se poate încărca fișierul:",b:"Bară imagine",c:"Bară tabel",d:"Îngroșat",e:"Cursiv",f:"Bloc citat",g:"Tăiere text cu o linie",h:"Alege titlu",i:"Titlu",j:"Subliniat",k:"Inserează imagine sau fișier",l:"Introdu titlul descriptiv al imaginii",m:"widget imagine",n:"Inserează imagine",o:"Încărcare eșuată",p:"Imagine mărime completă",q:"Imagine laterală",r:"Imagine aliniată la stânga",s:"Imagine aliniată pe centru",t:"Imagine aliniată la dreapta",u:"Link",v:"widget media",w:"Inserează tabel",x:"Antet coloană",y:"Inserează coloană la stânga",z:"Inserează coloană la dreapta",aa:"Șterge coloană",ab:"Coloană",ac:"Rând antet",ad:"Inserează rând dedesubt",ae:"Inserează rând deasupra",af:"Șterge rând",ag:"Rând",ah:"Îmbină celula în sus",ai:"Îmbină celula la dreapta",aj:"Îmbină celula în jos",ak:"Îmbină celula la stânga",al:"Scindează celula pe verticală",am:"Scindează celula pe orizontală",an:"Îmbină celulele",ao:"Inserează media",ap:"URL-ul nu trebuie să fie gol.",aq:"Acest URL media nu este suportat.",ar:"Dimensiune font",as:"Implicită",at:"Foarte mică",au:"Mică",av:"Mare",aw:"Foarte mare",ax:"Încărcare în curs",ay:"Bară widget",az:"Familie font",ba:"Șterge formatare",bb:"Evidențiator galben",bc:"Evidențiator verde",bd:"Evidențiator roz",be:"Evidențiator albastru",bf:"Pix roșu",bg:"Pix verde",bh:"Șterge evidențiere text",bi:"Evidențiere text",bj:"Bară evidențiere text",bk:"Aliniază la stânga",bl:"Aliniază la dreapta",bm:"Aliniază la centru",bn:"Aliniază stânga-dreapta",bo:"Aliniere text",bp:"Bara aliniere text",bq:"Listă numerotată",br:"Listă cu puncte",bs:"Nu se poate obtine URL-ul imaginii redimensionate.",bt:"Selecția imaginii redimensionate eșuată",bu:"Nu se poate insera imaginea la poziția curentă.",bv:"Inserție imagine eșuată",bw:"Schimbă textul alternativ al imaginii",bx:"Salvare",by:"Anulare",bz:"Adaugă URL-ul media in input.",ca:"Sugestie: adaugă URL-ul în conținut pentru a fi adăugat mai rapid.",cb:"Media URL",cc:"Anulare",cd:"Revenire",ce:"Editor de text",cf:"Bară listă opțiuni",cg:"%0 din %1",ch:"Înapoi",ci:"Înainte",cj:"Bară editor",ck:"Show more items",cl:"Text alternativ",cm:"Editor de text, %0",cn:"Negru",co:"Gri slab",cp:"Gri",cq:"Gri deschis",cr:"Alb",cs:"Roșu",ct:"Portocaliu",cu:"Galben",cv:"Verde deschis",cw:"Verde",cx:"Acvamarin",cy:"Turcoaz",cz:"Albastru deschis",da:"Albastru",db:"Violet",dc:"Deschide în tab nou",dd:"Descărcabil",de:"Șterge link",df:"Modifică link",dg:"Deschide link în tab nou",dh:"Acest link nu are niciun URL",di:"Link URL",dj:"Paragraf",dk:"Titlu 1",dl:"Titlu 2",dm:"Titlu 3",dn:"Titlu 4",do:"Titlu 5",dp:"Titlu 6"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
|
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from mixbox.vendor.six import u
from cybox.objects.win_hook_object import WinHook
from cybox.test.objects import ObjectTestCase
from cybox.test.objects.win_handle_test import TestWinHandle
class TestWinHook(ObjectTestCase, unittest.TestCase):
object_type = "WindowsHookObjectType"
klass = WinHook
_full_dict = {
'type': u("Test Hook"),
'handle': TestWinHandle._full_dict,
'hooking_function_name': u("test_function"),
#TODO: add 'hooking_module'
'thread_id': 2,
'xsi:type': object_type,
}
if __name__ == "__main__":
unittest.main()
|
# coding: utf8
import numpy as np
import pandas as pd
import nibabel as nib
from os.path import join
__author__ = "Jorge Samper-Gonzalez"
__copyright__ = "Copyright 2016-2019 The Aramis Lab Team"
__credits__ = ["Jorge Samper-Gonzalez", "Simona Bottani"]
__license__ = "See LICENSE.txt file"
__version__ = "0.1.0"
__maintainer__ = "Jorge Samper-Gonzalez"
__email__ = "jorge.samper-gonzalez@inria.fr"
__status__ = "Development"
def get_caps_t1_list(input_directory, subjects_visits_tsv, group_id, atlas_id):
"""
path to arrive to the list of the file with the statistics on atlas_id
Args:
input_directory:
subjects_visits_tsv:
group_id:
atlas_id:
Returns:
"""
from os.path import join
import pandas as pd
subjects_visits = pd.io.parsers.read_csv(subjects_visits_tsv, sep='\t')
if list(subjects_visits.columns.values) != ['participant_id', 'session_id']:
raise Exception('Subjects and visits file is not in the correct format.')
subjects = list(subjects_visits.participant_id)
sessions = list(subjects_visits.session_id)
image_list = [join(input_directory + '/subjects/' + subjects[i] + '/'
+ sessions[i] + '/t1/spm/dartel/group-' + group_id + '/atlas_statistics/' + subjects[i] + '_'
+ sessions[i]+'_T1w_space-'+atlas_id+'_map-graymatter_statistics.tsv')
for i in range(len(subjects))]
return image_list
def get_caps_pet_list(input_directory, subjects_visits_tsv, group_id, atlas_id):
"""
Args:
input_directory:
subjects_visits_tsv:
group_id:
atlas_id:
Returns:
"""
subjects_visits = pd.io.parsers.read_csv(subjects_visits_tsv, sep='\t')
if list(subjects_visits.columns.values) != ['participant_id', 'session_id']:
raise Exception('Subjects and visits file is not in the correct format.')
subjects = list(subjects_visits.participant_id)
sessions = list(subjects_visits.session_id)
image_list = [join(input_directory, 'analysis-series-default/subjects/' + subjects[i] + '/'
+ sessions[i] + '/pet/atlas_statistics/' + subjects[i] + '_' + sessions[i]
+ '_space-' + atlas_id + '_map-fdgstatistic2.tsv')
for i in range(len(subjects))]
return image_list
def load_data(image_list, subjects):
"""
Args:
image_list:
subjects:
Returns:
"""
subj_average = []
all_vector = np.array([])
read_file = pd.io.parsers.read_csv(image_list[0], sep='\t', usecols=[2], header=0)
read_file = read_file.mean_scalar
data = np.zeros((len(subjects), len(read_file)))
for i in range(len(image_list)):
tsv_file = pd.io.parsers.read_csv(image_list[i], sep='\t', usecols=[2], header=0)
subj_average = tsv_file.mean_scalar
all_vector = np.append(all_vector, subj_average)
data_temp = np.split(all_vector, len(image_list))
for i in range(len(image_list)):
for j in range(len(subj_average)):
data[i][j] = data_temp[i][j]
return data
def features_weights(image_list, dual_coefficients, sv_indices, scaler=None):
"""
Args:
image_list:
dual_coefficients:
sv_indices:
scaler:
Returns:
"""
if len(sv_indices) != len(dual_coefficients):
print("Length dual coefficients: " + str(len(dual_coefficients)))
print("Length indices: " + str(len(sv_indices)))
raise ValueError('The number of support vectors indices and the number of coefficients must be the same.')
if len(image_list) == 0:
raise ValueError('The number of images must be greater than 0.')
sv_images = [image_list[i] for i in sv_indices]
shape = pd.io.parsers.read_csv(sv_images[0], sep='\t', usecols=[2], header=0)
weights = np.zeros(len(shape))
for i in range(len(sv_images)):
subj = pd.io.parsers.read_csv(sv_images[i], sep='\t', usecols=[2], header=0)
subj_data = subj.mean_scalar
weights += dual_coefficients[i] * subj_data
return weights
def weights_to_nifti(weights, atlas, output_filename):
"""
Args:
atlas:
weights:
output_filename:
Returns:
"""
from os.path import join, split, realpath
from clinica.utils.atlas import AtlasAbstract
atlas_path = None
atlas_classes = AtlasAbstract.__subclasses__()
for atlas_class in atlas_classes:
if atlas_class.get_name_atlas() == atlas:
atlas_path = atlas_class.get_atlas_labels()
if not atlas_path:
raise ValueError('Atlas path not found for atlas name ' + atlas)
atlas_image = nib.load(atlas_path)
atlas_data = atlas_image.get_data()
labels = list(set(atlas_data.ravel()))
output_image_weights = np.array(atlas_data, dtype='f')
for i, n in enumerate(labels):
index = np.array(np.where(atlas_data == n))
output_image_weights[index[0, :], index[1, :], index[2, :]] = weights[i]
affine = atlas_image.get_affine()
header = atlas_image.get_header()
output_image = nib.Nifti1Image(output_image_weights, affine, header)
nib.save(output_image, output_filename)
|
import uuid, re
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import validates
from sqlalchemy.schema import FetchedValue
from app.extensions import db
from ....utils.models_mixins import AuditMixin, Base
from ..models.minespace_user_mine import MinespaceUserMine
class MinespaceUser(Base):
__tablename__ = 'minespace_user'
user_id = db.Column(db.Integer, primary_key=True, server_default=FetchedValue())
keycloak_guid = db.Column(UUID(as_uuid=True))
email = db.Column(db.String(100), nullable=False)
deleted_ind = db.Column(db.Boolean, nullable=False, server_default=FetchedValue())
mines = db.relationship('MinespaceUserMine', backref='user', lazy='joined')
def json(self):
return {
'user_id': str(self.user_id),
'keycloak_guid': str(self.keycloak_guid or ''),
'email': self.email,
'mines': [str(x.mine_guid) for x in self.mines]
}
@classmethod
def get_all(cls):
return cls.query.filter_by(deleted_ind=False).all()
@classmethod
def find_by_id(cls, id):
return cls.query.filter_by(user_id=id).filter_by(deleted_ind=False).first()
@classmethod
def find_by_guid(cls, user_guid):
return cls.query.filter_by(keycloak_guid=user_guid).filter_by(deleted_ind=False).first()
@classmethod
def find_by_email(cls, email):
return cls.query.filter_by(email=email).filter_by(deleted_ind=False).first()
@classmethod
def create_minespace_user(cls, email, add_to_session=True):
minespace_user = cls(email=email)
if add_to_session:
minespace_user.save(commit=False)
return minespace_user
@validates('email')
def validate_email(self, key, email):
if not email:
raise AssertionError('email is not provided.')
if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
raise AssertionError('Invalid email format.')
return email
|
from unittest import TestCase
import CalCalc
class CalCalcTestCall(TestCase):
def test_1(self):
"""Test if error is handled for junk without wolfram flag"""
test_str = "some junk"
assert (
CalCalc.calculate(test_str, False)
== test_str
+ " : is not a valid numexpr expression and cannon be evaluated, try with wolfram alpha '-w' flag"
)
def test_2(self):
"""Test if error is handled for junk with wolfram flag"""
test_str = "what the heck is going on here"
assert CalCalc.calculate(test_str, True) == "unreadable input by wolfram, please reformat"
def test_3(self):
"""Test that a simple calculation of 2+2 returns 4"""
test_str = "2+2"
assert CalCalc.calculate(test_str, False) == 4.0
def test_4(self):
"""Check that floating point output works for an answer that returns scientific notation"""
test_str = "mass of the moon in kg"
assert CalCalc.get_wolfram_output_as_float(CalCalc.calculate(test_str, True)) == 7.3459e22
def test_5(self):
"""Check that the floating point output returns results that have a multiplier as string"""
test_str = "millimeters in a meter"
assert CalCalc.get_wolfram_output_as_float(CalCalc.calculate(test_str, True)) == 1.0e3
|
//// [parserClassDeclaration1.ts]
class C extends A extends B {
}
//// [parserClassDeclaration1.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var C = (function (_super) {
__extends(C, _super);
function C() {
return _super.apply(this, arguments) || this;
}
return C;
}(A));
|
import netflix from "./netflix.png";
import whatsapp from "./whatsApp.jpg";
import air from "./airBnd.png";
import admin from "./admin.jpg";
import gmail from "./gmail.png";
import chat from "./chatUi.png";
import amazon from "./amazon.jpg";
import trans from "./translator.png";
import coin from "./bitcoin.jpg";
import eng from './quiz.jpg'
import mosque from './msoque.jpg'
import movies from './movie.jpg'
import slack from './slack.png'
import quiz2 from './quiz-types.jpg'
import UI from './ui.png'
import disney from './disney.jpg'
import robin from './robin.png'
import covid from './covid.jpg'
import social from './chat-ui2.png'
import dis from './discord.png'
import morgen from './morgen.jpg'
import twit from './twitter.png'
import telegram from './telegram.png'
import facebook from './facebook.png'
import spotify from './spotify.png'
import typesQuiz from './quiz-types.jpg'
import cart from './cart.jpg'
import yt from './yt.jpg'
export const PortfolioData = [
{
id: 1,
title: "Whats app clone",
image: whatsapp,
slug: 'whatsApp'
},
{
id: 2,
title: "Airbnd clone",
image: air,
slug: 'airBnd'
},
{
id: 3,
title: "About me",
image: admin,
slug: 'aboutMe'
},
{
id: 4,
title: "Gmail UI",
image: gmail,
slug: 'gmailUi'
},
{
id: 5,
title: "Gmail functional",
image: gmail,
slug: 'gmailFunc'
},
{
id: 6,
title: "Youtube clone-UI",
image: yt,
slug: 'yt'
},
{
id: 7,
title: "Simple chat-UI",
image: chat,
slug: 'simpleChat'
},
{
id: 8,
title: "Amazon clone",
image: amazon,
slug: 'amazon'
},
{
id: 9,
title: "Netflix clone",
image: netflix,
slug: 'netflix'
},
{
id: 10,
title: "Translator",
image: trans,
slug: 'translator'
},
{
id: 11,
title: "Cryptocurrency Admin",
image: coin,
slug: 'bitcoin'
},
{
id: 12,
title: "Learn english with Quiz",
image: eng,
slug: 'english'
},
{
id: 13,
title: "Qorabog Masjid",
image: mosque,
slug: 'mosque'
},
{
id: 14,
title: "Online Movies",
image: movies,
slug: 'movies'
},
{
id: 15,
title: "Slack clone",
image: slack,
slug: 'slack'
},
{
id: 16,
title: "Bozor-uz",
image: coin,
slug: 'bozor'
},
{
id: 17,
title: "Quiz width redux-saga",
image: quiz2,
slug: 'quiz'
},
{
id: 18,
title: "Fully UI",
image: UI,
slug: 'UI'
},
{
id: 19,
title: "Disney clone",
image: disney,
slug: 'disney'
},
{
id: 20,
title: "Robinhood clone",
image: robin,
slug: 'robin'
},
{
id: 21,
title: "Covid tracker",
image: covid,
slug: 'covid'
},
{
id: 22,
title: "Socialize",
image: social,
slug: 'social'
},
{
id: 23,
title: "Discord",
image: dis,
slug: 'discord'
},
{
id: 24,
title: "Morgenshtern songs",
image: morgen,
slug: 'morgen'
},
{
id: 25,
title: "Twitter clone",
image: twit,
slug: 'twitter'
},
{
id: 26,
title: "Telegram clone",
image: telegram
},
{
id: 27,
title: "Facebook clone",
image: facebook
},
{
id: 28,
title: "Spotify clone",
image: spotify
},
{
id: 29,
title: "Typescript quiz",
image: typesQuiz
},
{
id: 30,
title: "Typescript shopping-cart",
image: cart
},
];
|
(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i)) && ! function(a) {
function h(b, c, d) {
'use strict';
function i() {
g && (g.apply(a, arguments), h || (delete c[f], g = null))
}
var f, g = d[0],
h = b === e;
return d[0] = i, f = b.apply(a, d), c[f] = {
args: d,
created: Date.now(),
cb: g,
id: f
}, f
}
function i(b, c, d, f) {
'use strict';
function l() {
h.cb && (h.cb.apply(a, arguments), i || (delete d[f], h.cb = null))
}
var h = d[f];
if (h) {
var i = b === e;
if (c(h.id), !i) {
var j = h.args[1],
k = Date.now() - h.created;
k < 0 && (k = 0), j -= k, j < 0 && (j = 0), h.args[1] = j
}
h.args[0] = l, h.created = Date.now(), h.id = b.apply(a, h.args)
}
}
var b = {}, c = {}, d = a.setTimeout,
e = a.setInterval,
f = a.clearTimeout,
g = a.clearInterval;
a.setTimeout = function() {
return h(d, b, arguments)
}, a.setInterval = function() {
return h(e, c, arguments)
}, a.clearTimeout = function(a) {
var c = b[a];
c && (delete b[a], f(c.id))
}, a.clearInterval = function(a) {
var b = c[a];
b && (delete c[a], g(b.id))
}, a.addEventListener("scroll", function() {
var a;
for (a in b) i(d, f, b, a);
for (a in c) i(e, g, c, a)
})
}(window);
|
import { combineReducers } from "redux";
import ingredientReducer from "./ingredients";
import recipesReducer from "./recipes";
const rootReducer = combineReducers({
recipes: recipesReducer,
ingredients: ingredientReducer
});
export default rootReducer;
|
#include <stdio.h>
#include <3ds.h>
#include <unistd.h>
#include <string.h>
#include "ntr_config.h"
#include "mysvcs.h"
#define CURRENT_PROCESS_HANDLE (0xffff8001)
#define RESULT_ERROR (1)
|
#define SQLITE_ENABLE_FTS5
#define SQLITE_ENABLE_PREUPDATE_HOOK
|
#!/usr/bin/env python3
# Plots loss functions of form |x|**q
import matplotlib.pyplot as pl
import numpy as np
from scipy.stats import t, laplace, norm
x = np.linspace(-4, 4, 100)
pl.title('|x|^0.2')
pl.plot(x, np.absolute(x)**.2)
pl.savefig('lossFunctionFig_01.png')
pl.figure()
pl.title('|x|')
pl.plot(x, np.absolute(x))
pl.savefig('lossFunctionFig_02.png')
pl.figure()
pl.title('|x|^2')
pl.plot(x, np.absolute(x)**2)
pl.savefig('lossFunctionFig_03.png')
pl.show()
|
/*
* Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(e,define){define([],e)}(function(){return function(e){var t=e.kendo||(e.kendo={cultures:{}});t.cultures.cy={name:"cy",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{pattern:["-$n","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"£"}},calendars:{standard:{days:{names:["Dydd Sul","Dydd Llun","Dydd Mawrth","Dydd Mercher","Dydd Iau","Dydd Gwener","Dydd Sadwrn"],namesAbbr:["Sul","Llun","Maw","Mer","Iau","Gwe","Sad"],namesShort:["Su","Ll","Ma","Me","Ia","Gw","Sa"]},months:{names:["Ionawr","Chwefror","Mawrth","Ebrill","Mai","Mehefin","Gorffennaf","Awst","Medi","Hydref","Tachwedd","Rhagfyr"],namesAbbr:["Ion","Chwef","Maw","Ebr","Mai","Meh","Gorff","Awst","Medi","Hyd","Tach","Rhag"]},AM:["am","am","AM"],PM:["pm","pm","PM"],patterns:{d:"dd/MM/yy",D:"d MMMM yyyy",F:"d MMMM yyyy HH:mm:ss",g:"dd/MM/yy HH:mm",G:"dd/MM/yy HH:mm:ss",m:"d MMMM",M:"d MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH:mm",T:"HH:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM yyyy",Y:"MMMM yyyy"},"/":"/",":":":",firstDay:1}}}}(this),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()});
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
import logging
import logging.config
import os
import sys
import warnings
from os.path import dirname, expanduser
from shutil import which
from socketfromfd import fromfd as socket_from_fd
import tornado.ioloop
from PIL import Image
from tornado.httpserver import HTTPServer
from tornado.netutil import bind_unix_socket
from thumbor.config import Config
from thumbor.console import get_server_parameters
from thumbor.context import Context
from thumbor.importer import Importer
from thumbor.signal_handler import setup_signal_handler
def get_as_integer(value):
try:
return int(value)
except (ValueError, TypeError):
return None
def get_config(config_path, use_environment=False):
if use_environment:
Config.allow_environment_variables()
lookup_paths = [os.curdir, expanduser("~"), "/etc/", dirname(__file__)]
return Config.load(config_path, conf_name="thumbor.conf", lookup_paths=lookup_paths)
def configure_log(config, log_level):
if config.THUMBOR_LOG_CONFIG and config.THUMBOR_LOG_CONFIG != "":
logging.config.dictConfig(config.THUMBOR_LOG_CONFIG)
else:
logging.basicConfig(
level=getattr(logging, log_level),
format=config.THUMBOR_LOG_FORMAT,
datefmt=config.THUMBOR_LOG_DATE_FORMAT,
)
def get_importer(config):
importer = Importer(config)
importer.import_modules()
if importer.error_handler_class is not None:
importer.error_handler = importer.error_handler_class(config)
return importer
def validate_config(config, server_parameters):
if server_parameters.security_key is None:
server_parameters.security_key = config.SECURITY_KEY
if not isinstance(server_parameters.security_key, (bytes, str)):
raise RuntimeError(
"No security key was found for this instance of thumbor. "
+ "Please provide one using the conf file or a security key file."
)
if config.ENGINE or config.USE_GIFSICLE_ENGINE:
# Error on Image.open when image pixel count is above MAX_IMAGE_PIXELS
warnings.simplefilter("error", Image.DecompressionBombWarning)
if config.USE_GIFSICLE_ENGINE:
server_parameters.gifsicle_path = which("gifsicle")
if server_parameters.gifsicle_path is None:
raise RuntimeError(
"If using USE_GIFSICLE_ENGINE configuration to True,"
" the `gifsicle` binary must be in the PATH "
"and must be an executable."
)
def get_context(server_parameters, config, importer):
return Context(server=server_parameters, config=config, importer=importer)
def get_application(context):
return context.modules.importer.import_class(context.app_class)(context)
def run_server(application, context):
server = HTTPServer(application, xheaders=True)
if context.server.fd is not None:
fd_number = get_as_integer(context.server.fd)
if fd_number is not None:
# TODO: replace with socket.socket(fileno=fd_number) when we require Python>=3.7
sock = socket_from_fd(fd_number, True)
else:
sock = bind_unix_socket(context.server.fd)
server.add_socket(sock)
logging.debug("thumbor starting at fd %s", context.server.fd)
else:
server.bind(context.server.port, context.server.ip)
logging.debug(
"thumbor starting at %s:%d", context.server.ip, context.server.port
)
server.start(context.server.processes)
return server
def main(arguments=None):
"""Runs thumbor server with the specified arguments."""
if arguments is None:
arguments = sys.argv[1:]
server_parameters = get_server_parameters(arguments)
config = get_config(
server_parameters.config_path, server_parameters.use_environment
)
configure_log(config, server_parameters.log_level.upper())
validate_config(config, server_parameters)
importer = get_importer(config)
with get_context(server_parameters, config, importer) as context:
application = get_application(context)
server = run_server(application, context)
setup_signal_handler(server, config)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main(sys.argv[1:])
|
# common_cli.py는 모든 화면출력과 메뉴선택을 담당하는 곳입니다.
import os
import time
#from pynput.keyboard import Listener, Key
import common_value as val
#by VDoring. 2021.06.19z
#시작화면을 출력하고 메뉴를 선택하게 합니다.
#리턴값: 1,2
def screenMain():
while True:
os.system('mode con cols=40 lines=11') # 타이틀화면 화면 크기 설정
os.system('title MP2 - Title') # 윈도우타이틀 설정
print('\n - -<-< URL-based MusicPlayer 2 >->- - ')
print('\n\n [1] Play')
print('\n [2] Explanation')
print('\n > ',end='')
user_select = input()
if user_select.isdigit(): # 유저 입력값이 숫자로만 이루어진 경우
if int(user_select) == 1: # 유저 입력값이 1일때
return 1
elif int(user_select) == 2: # 유저 입력값이 2일때
return 2
else: # 유저 입력값이 1이나 2가 아닐때
print(' [!] Choose from 1 or 2 [!]')
time.sleep(0.75)
else: # 입력값에 문자가 들어갔을 경우
print(' [!] Please enter a number! [!]')
time.sleep(0.75)
#by VDoring. 2021.06.19
#전체링크 플레이 모드와 즐겨찾기 플레이 모드 메뉴를 출력하고, 그중 하나를 선택하게 합니다.
#리턴값: 1,2
def screenPlaytype():
while True:
os.system('cls') # 화면 지우기
os.system('title MP2 - Set mode....') # 윈도우타이틀 설정
print('\n < Choose play mode.. >')
print('\n\n [1] All')
print('\n [2] Favorite')
print('\n > ',end='')
user_select = input()
if user_select.isdigit(): # 유저 입력값이 숫자로만 이루어진 경우
if int(user_select) == 1: # 유저 입력값이 1일때
return 1
elif int(user_select) == 2: # 유저 입력값이 2일때
return 2
else: # 유저 입력값이 1이나 2가 아닐때
print(' [!] Choose from 1 or 2 [!]')
time.sleep(0.75)
else: # 입력값에 문자가 들어갔을 경우
print(' [!] Please enter a number! [!]')
time.sleep(0.75)
#by VDoring. 2021.06.19
#이 프로그램이 무엇인지, 어떻게 작동하는지 안내하는 텍스트를 출력합니다.
#리턴값: 없음
def screenExplanation():
os.system('mode con cols=130 lines=25') # 설명화면 화면 크기 설정
os.system('title MP2 - Explanation') # 윈도우타이틀 설정
print('\n- - -<-< VDoring\'s URL-based MusicPlayer 2 >->- - --------------------------------------------------------------------------------')
print('\n이 프로그램은 .txt파일에 음악 등의 링크를 저장해 특정 작업을 하시는 분들을 대상으로 빠른 링크 실행을 도와주는 프로그램입니다.')
print('\n\n{사용법}')
print('1. Mlist.txt에 자신이 원하는 인터넷 링크를 넣습니다.')
print('2. Mlist.txt 파일을 저장한 후 해당 프로그램을 실행합니다.')
print('3. 자신이 원하는 재생 모드를 선택합니다.')
print('(자세한 설명은 GitHub을 참조하세요)')
print('\n{참고사항}')
print('1. Mlist.txt에 링크를 넣을때 메모도 같이 하고 싶다면 \'space\'키를 이용해 링크와 구분해야합니다!')
print('\n{프로젝트 링크}')
print('GitHub: https://github.com/VDoring/URL-based-MusicPlayer-2\n\n\n')
os.system('pause')
#by VDoring. 2021.06.19
#전체링크 플레이 모드의 4개의 세부 플레이 타입 메뉴를 출력하고 선택하게 합니다.
#리턴값: 1,2,3,4
def screenPlaytypeAll():
while True:
os.system('mode con cols=42 lines=14') # 화면 지우기
os.system('title MP2 - Set mode..') # 윈도우타이틀 설정
print('\n < Choose \'All\' play mode type.. > ')
print('\n\n [1] from Top to Bottom')
print('\n [2] from Bottom to Top')
print('\n [3] Random Overlap')
print('\n [4] Random No Overlap')
print('\n > ',end='')
user_select = input()
if user_select.isdigit(): # 유저 입력값이 숫자로만 이루어진 경우
if int(user_select) == 1: # 유저 입력값이 1일때
return 1
elif int(user_select) == 2: # 유저 입력값이 2일때
return 2
elif int(user_select) == 3: # 유저 입력값이 3일때
return 3
elif int(user_select) == 4: # 유저 입력값이 4일때
return 4
else: # 유저 입력값이 1,2,3,4가 아닐때
print(' [!] Choose from 1,2,3,4 [!]')
time.sleep(0.75)
else: # 입력값에 문자가 들어갔을 경우
print(' [!] Please enter a number! [!]')
time.sleep(0.75)
#by VDoring. 2021.06.19
#즐겨찾기 링크 플레이 모드의 4개의 세부 플레이 타입 메뉴를 출력하고 선택하게 합니다.
#리턴값: 1,2,3,4
def screenPlaytypeFav():
while True:
os.system('mode con cols=46 lines=14') # 화면 지우기
os.system('title MP2 - Set mode..') # 윈도우타이틀 설정
print('\n < Choose \'Favorite\' play mode type.. > ')
print('\n\n [1] from Top to Bottom')
print('\n [2] from Bottom to Top')
print('\n [3] Random Overlap')
print('\n [4] Random No Overlap')
print('\n > ',end='')
user_select = input()
if user_select.isdigit(): # 유저 입력값이 숫자로만 이루어진 경우
if int(user_select) == 1: # 유저 입력값이 1일때
return 1
elif int(user_select) == 2: # 유저 입력값이 2일때
return 2
elif int(user_select) == 3: # 유저 입력값이 3일때
return 3
elif int(user_select) == 4: # 유저 입력값이 4일때
return 4
else: # 유저 입력값이 1,2,3,4가 아닐때
print(' [!] Choose from 1,2,3,4 [!]')
time.sleep(0.75)
else: # 입력값에 문자가 들어갔을 경우
print(' [!] Please enter a number! [!]')
time.sleep(0.75)
#by VDoring. 2021.06.20
#다음 곡을 재생할지 묻는 텍스트를 출력하고 입력을 기다립니다.
#반환값: True, False
def screenAskNextMusic():
while True:
os.system('mode con cols=40 lines=11') # 화면 지우기
os.system('title Playing..') # 윈도우타이틀 설정
print('\n Move on to the next URL? [%d/%d]'%(val.mlist_current_links_play_count, val.mlist_available_links_count))
print('\n\n [1] Yes')
print('\n [2] No')
print('\n > ',end='')
user_select = input()
if user_select.isdigit():
if int(user_select) == 1: # Yes일때
return True
elif int(user_select) == 2: # No일때
return False
else: # 유저 입력값이 1이나 2가 아닐때
print(' [!] Choose from 1,2 [!]')
time.sleep(0.75)
else: # 입력값에 문자가 들어갔을 경우
print(' [!] Please enter a number! [!]')
time.sleep(0.75)
|
exports.config = {
// ====================
// Runner and framework
// Configuration
// ====================
runner: 'local',
framework: 'jasmine',
jasmineNodeOpts: {
// Updated the timeout to 30 seconds due to possible longer appium calls
// When using XPATH
defaultTimeoutInterval: 90000,
helpers: [require.resolve('@babel/register')],
},
sync: true,
logLevel: 'silent',
deprecationWarnings: true,
bail: 0,
baseUrl: 'http://the-internet.herokuapp.com',
waitforTimeout: 10000,
connectionRetryTimeout: 90000,
connectionRetryCount: 3,
reporters: ['spec'],
// ====================
// Appium Configuration
// ====================
services: [
[
'appium',
{
// For options see
// https://github.com/webdriverio/webdriverio/tree/master/packages/wdio-appium-service
args: {
// For arguments see
// https://github.com/webdriverio/webdriverio/tree/master/packages/wdio-appium-service
},
command: 'appium',
},
],
],
port: 4723,
};
|
#!/usr/bin/env python3
import numpy as np
import csv
import json
import sys
import argparse
import multiprocessing as mp
import glob
import os
from functools import partial
from sofa_print import *
import subprocess
from pwd import getpwuid
import time
def kill_pcm_modules(p_pcm_pcie, p_pcm_memory, p_pcm_numa):
if p_pcm_pcie != None:
p_pcm_pcie.terminate()
os.system('yes|pkill pcm-pcie.x')
print_info("tried killing pcm-pcie.x")
if p_pcm_memory != None:
p_pcm_memory.terminate()
os.system('yes|pkill pcm-memory.x')
print_info("tried killing pcm-memory.x")
if p_pcm_numa != None:
p_pcm_numa.terminate()
os.system('yes|pkill pcm-numa.x')
print_info("tried killing pcm-numa.x")
def sofa_record(command, logdir, cfg):
p_tcpdump = None
p_mpstat = None
p_vmstat = None
p_nvprof = None
p_nvsmi = None
p_nvtopo = None
p_pcm_pcie = None
p_pcm_memory = None
p_pcm_numa = None
print_info('SOFA_COMMAND: %s' % command)
sample_freq = 99
if int(open("/proc/sys/kernel/kptr_restrict").read()) != 0:
print_error(
"/proc/kallsyms permission is restricted, please try the command below:")
print_error("sudo sysctl -w kernel.kptr_restrict=0")
quit()
if int(open("/proc/sys/kernel/perf_event_paranoid").read()) != -1:
print_error('PerfEvent is not avaiable, please try the command below:')
print_error('sudo sysctl -w kernel.perf_event_paranoid=-1')
quit()
if cfg.enable_pcm:
print_info('Test Capability of PCM programs ...')
ret = str(subprocess.check_output(['getcap `which pcm-pcie.x`'], shell=True))
if ret.find('cap_sys_rawio+ep') == -1:
print_error('To read/write MSR in userspace is not avaiable, please try the commands below:')
print_error('sudo modprobe msr')
print_error('sudo setcap cap_sys_rawio=ep `which pcm-pcie.x`')
quit()
ret = str(subprocess.check_output(['getcap `which pcm-memory.x`'], shell=True))
if ret.find('cap_sys_rawio+ep') == -1:
print_error('To read/write MSR in userspace is not avaiable, please try the commands below:')
print_error('sudo modprobe msr')
print_error('sudo setcap cap_sys_rawio=ep `which pcm-memory.x`')
quit()
ret = str(subprocess.check_output(['getcap `which pcm-numa.x`'], shell=True))
if ret.find('cap_sys_rawio+ep') == -1:
print_error('To read/write MSR in userspace is not avaiable, please try the commands below:')
print_error('sudo modprobe msr')
print_error('sudo setcap cap_sys_rawio=ep `which pcm-numa.x`')
quit()
if subprocess.call(['mkdir', '-p', logdir]) != 0:
print_error('Cannot create the directory' + logdir + ',which is needed for sofa logged files.' )
quit()
print_info('Read NMI watchlog status ...')
nmi_output = ""
try:
with open(logdir+"nmi_status.txt", 'w') as f:
p_pcm_pcie = subprocess.Popen(['yes | timeout 3 pcm-pcie.x'], shell=True, stdout=f)
if p_pcm_pcie != None:
p_pcm_pcie.kill()
print_info("tried killing pcm-pcie.x")
os.system('pkill pcm-pcie.x')
with open(logdir+"nmi_status.txt", 'r') as f:
lines = f.readlines()
if len(lines) > 0:
if lines[0].find('Error: NMI watchdog is enabled.') != -1:
print_error('NMI watchdog is enabled., please try the command below:')
print_error('sudo sysctl -w kernel.nmi_watchdog=0')
# output = subprocess.check_output('yes | timeout 3 pcm-pcie.x 2>&1', shell=True)
except subprocess.CalledProcessError as e:
print_warning("There was error while reading NMI status.")
print_info('Clean previous logged files')
subprocess.call('rm %s/perf.data > /dev/null 2> /dev/null' % logdir, shell=True )
subprocess.call('rm %s/sofa.pcap > /dev/null 2> /dev/null' % logdir, shell=True)
subprocess.call('rm %s/gputrace*.nvvp > /dev/null 2> /dev/null' % logdir, shell=True)
subprocess.call('rm %s/gputrace.tmp > /dev/null 2> /dev/null' % logdir, shell=True)
subprocess.call('rm %s/*.csv > /dev/null 2> /dev/null' % logdir, shell=True)
subprocess.call('rm %s/*.txt > /dev/null 2> /dev/null' % logdir, shell=True)
try:
print_info("Prolog of Recording...")
if int(os.system('command -v nvprof')) == 0:
p_nvprof = subprocess.Popen(['nvprof', '--profile-all-processes', '-o', logdir+'/gputrace%p.nvvp'])
print_info('Launching nvprof')
time.sleep(3)
print_info('nvprof is launched')
else:
print_warning('Profile without NVPROF')
if cfg.enable_pcm:
with open(os.devnull, 'w') as FNULL:
delay_pcie = 0.02
p_pcm_pcie = subprocess.Popen(['yes|pcm-pcie.x ' + str(delay_pcie) + ' -csv=sofalog/pcm_pcie.csv -B '], shell=True)
p_pcm_memory = subprocess.Popen(['yes|pcm-memory.x ' + str(delay_pcie) + ' -csv=sofalog/pcm_memory.csv '], shell=True)
p_pcm_numa = subprocess.Popen(['yes|pcm-numa.x ' + str(delay_pcie) + ' -csv=sofalog/pcm_numa.csv '], shell=True)
print_info("Recording...")
if cfg.profile_all_cpus == True:
perf_options = '-a'
else:
perf_options = ''
subprocess.call('cp /proc/kallsyms %s/' % (logdir), shell=True )
subprocess.call('chmod +w %s/kallsyms' % (logdir), shell=True )
# To improve perf timestamp accuracy
print_info("Script path of SOFA: "+cfg.script_path)
subprocess.call('%s/sofa_perf_timebase > %s/perf_timebase.txt' % (cfg.script_path,logdir), shell=True)
subprocess.call('rm %s/*.nvvp' % (logdir), shell=True)
subprocess.call('nvprof --profile-child-processes -o %s/cuhello%%p.nvvp -- perf record -o %s/cuhello.perf.data %s/cuhello' % (logdir,logdir,cfg.script_path), shell=True)
# sofa_time is time base for mpstat, vmstat, nvidia-smi
with open('%s/sofa_time.txt' % logdir, 'w') as logfile:
unix_time = time.time()
logfile.write(str('%.9lf'%unix_time)+'\n')
with open('%s/mpstat.txt' % logdir, 'w') as logfile:
p_mpstat = subprocess.Popen(
['mpstat', '-P', 'ALL', '1', '600'], stdout=logfile)
with open('%s/vmstat.txt' % logdir, 'w') as logfile:
p_vmstat = subprocess.Popen(['vmstat', '-w', '1', '600'], stdout=logfile)
with open(os.devnull, 'w') as FNULL:
p_tcpdump = subprocess.Popen(["tcpdump",
'-i',
'any',
'-v',
'tcp',
'-w',
'%s/sofa.pcap' % logdir],
stderr=FNULL)
if int(os.system('command -v nvidia-smi')) == 0:
with open('%s/nvsmi.txt' % logdir, 'w') as logfile:
p_nvsmi = subprocess.Popen(['nvidia-smi', 'dmon', '-s', 'u'], stdout=logfile)
with open('%s/nvlink_topo.txt' % logdir, 'w') as logfile:
p_nvtopo = subprocess.Popen(['nvidia-smi', 'topo', '-m'], stdout=logfile)
if int(os.system('command -v perf')) == 0:
profile_command = 'perf record -o %s/perf.data -e %s -F %s %s -- %s' % (logdir, cfg.perf_events, sample_freq, perf_options, command)
print_info( profile_command)
subprocess.call(profile_command, shell=True)
print_info("Epilog of Recording...")
if p_tcpdump != None:
p_tcpdump.terminate()
print_info("tried terminating tcpdump")
if p_vmstat != None:
p_vmstat.terminate()
print_info("tried terminating vmstat")
if p_mpstat != None:
p_mpstat.terminate()
print_info("tried terminating mpstat")
if p_nvtopo != None:
p_nvtopo.terminate()
print_info("tried terminating nvidia-smi topo")
if p_nvsmi != None:
p_nvsmi.terminate()
print_info("tried terminating nvidia-smi dmon")
if p_nvprof != None:
p_nvprof.terminate()
print_info("tried terminating nvprof")
if cfg.enable_pcm:
kill_pcm_modules(p_pcm_pcie, p_pcm_memory, p_pcm_numa)
except BaseException:
print("Unexpected error:", sys.exc_info()[0])
if p_tcpdump != None:
p_tcpdump.kill()
print_info("tried killing tcpdump")
if p_vmstat != None:
p_vmstat.kill()
print_info("tried killing vmstat")
if p_mpstat != None:
p_mpstat.kill()
print_info("tried killing mpstat")
if p_nvtopo != None:
p_nvtopo.kill()
print_info("tried killing nvidia-smi topo")
if p_nvsmi != None:
p_nvsmi.kill()
print_info("tried killing nvidia-smi dmon")
if p_nvprof != None:
p_nvprof.kill()
print_info("tried killing nvprof")
if cfg.enable_pcm:
kill_pcm_modules(p_pcm_pcie, p_pcm_memory, p_pcm_numa)
raise
print_info("End of Recording")
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var Rpc = /** @class */ (function () {
function Rpc(host) {
var _this = this;
this.post = function (method, params) { return __awaiter(_this, void 0, void 0, function () {
var data, resp;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = {
jsonrpc: "2.0",
method: method,
params: params,
id: this.id++,
};
return [4 /*yield*/, axios_1.default.post(this.host, data)];
case 1:
resp = _a.sent();
if (resp.data) {
if (resp.data.error) {
if (resp.data.error.code) {
return [2 /*return*/, Promise.reject(resp.data.error.message)];
}
return [2 /*return*/, Promise.reject(resp.data.error)];
}
else {
return [2 /*return*/, Promise.resolve(resp.data.result)];
}
}
return [2 /*return*/];
}
});
}); };
this.host = host;
this.id = 0;
}
return Rpc;
}());
exports.default = Rpc;
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'az', {
copy: 'Köçür',
copyError: 'Avtomatik köçürülməsi mümkün deyil. Ctrl+C basın.',
cut: 'Kəs',
cutError: 'Avtomatik kəsmə mümkün deyil. Ctrl+X basın.',
paste: 'Əlavə et',
pasteNotification: 'Sizin İnternet bələdçisi bu cür mətnin köçürməsi dəstəklənmir. Əlavə etmək üçün %1 basın.'
} );
|
// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
#ifndef __ASP_CAMERA_RPCSTEREOMODEL_H__
#define __ASP_CAMERA_RPCSTEREOMODEL_H__
#include <vw/Stereo/DisparityMap.h>
#include <vw/Stereo/StereoModel.h>
// TODO: Why not just include the file in the .h file?
// forward declaration
namespace vw {
namespace camera {
class CameraModel;
}
}
namespace asp {
/// Derived StereoModel class implementing the RPC camera model.
/// - Using a seperate class allows us to get a speed improvement in ray generation.
class RPCStereoModel: public vw::stereo::StereoModel {
public:
//------------------------------------------------------------------
// Constructors / Destructors
//------------------------------------------------------------------
RPCStereoModel(std::vector<const vw::camera::CameraModel *> const& cameras,
bool least_squares_refine = false,
double angle_tol = 0.0):
vw::stereo::StereoModel(cameras, least_squares_refine, angle_tol){}
RPCStereoModel(vw::camera::CameraModel const* camera_model1,
vw::camera::CameraModel const* camera_model2,
bool least_squares_refine = false,
double angle_tol = 0.0):
vw::stereo::StereoModel(camera_model1, camera_model2, least_squares_refine, angle_tol){}
virtual ~RPCStereoModel() {}
//------------------------------------------------------------------
// Public Methods
//------------------------------------------------------------------
// Note: This is a re-implementation of StereoModel::operator().
virtual vw::Vector3 operator()(std::vector<vw::Vector2> const& pixVec,
vw::Vector3& errorVec ) const;
virtual vw::Vector3 operator()(vw::Vector2 const& pix1,
vw::Vector2 const& pix2,
double& error) const;
};
} // namespace asp
#endif // __ASP_CAMERA_RPCSTEREOMODEL_H__
|
$(document).ready(function(){
var banner = localStorage.getItem('admin-banner');
if(!banner){
$(".current-banner").text( "Select a Banner" );
$(".banner-icon").removeClass("fa-flag").addClass("fa-exclamation-triangle");
$(".current-banner-anchor").addClass("banner-not-set");
}
console.log('selected banner : ' + localStorage.getItem('admin-banner'));
$(".current-banner").append(localStorage.getItem('admin-banner'));
$(".banner-switch").click(function(){
localStorage.setItem('admin-banner-id', $(this).attr('data-banner-id'));
localStorage.setItem('admin-banner', $(this).text());
var banner_id = localStorage.getItem("admin-banner-id");
var banner = localStorage.getItem("admin-banner");
$(".banner-icon").removeClass("fa-exclamation-triangle").addClass("fa-flag");
$(".current-banner-anchor").removeClass("banner-not-set");
console.log('banner_id' + banner_id);
$.ajax({
method : "PATCH",
url : "/admin/banner/" + banner_id ,
data : { "_token" : $('[name="_token"]').val()}
}).done(function( data ){
console.log(data);
$(".navbar-brand").find('span').append( banner );
window.location = '/admin/home';
});
})
});
|
const STATUS_MAP = {
PENDING: 'pending',
FULFILLED: 'fulfilled',
REJECTED: 'rejected',
};
class CustomPromise {
constructor(executor) {
this.status = STATUS_MAP.PENDING;
this.value = undefined;
this.reason = undefined;
this.resolvedCallbacks = [];
this.rejectedCallbacks = [];
const resolve = (value) => {
if (this.status === STATUS_MAP.PENDING) {
this.status = STATUS_MAP.FULFILLED;
this.value = value;
this.resolvedCallbacks.forEach((callback) => {
if (typeof callback === 'function') {
callback(value);
}
});
}
};
const reject = (reason) => {
if (this.status === STATUS_MAP.PENDING) {
this.status = STATUS_MAP.REJECTED;
this.reason = reason;
this.rejectedCallbacks.forEach((callback) => {
if (typeof callback === 'function') {
callback(reason);
}
});
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.status === STATUS_MAP.PENDING) {
this.resolvedCallbacks.push(onFulfilled);
this.rejectedCallbacks.push(onRejected);
}
if (
this.status === STATUS_MAP.FULFILLED &&
typeof onFulfilled === 'function'
) {
onFulfilled(this.value);
}
if (
this.status === STATUS_MAP.REJECTED &&
typeof onRejected === 'function'
) {
onRejected(this.reason);
}
// TODO: promise chain
return this;
}
catch(onRejected) {
return this.then(undefined, onRejected);
}
}
const p = new CustomPromise((resolve, reject) => {
setTimeout(() => {
// resolve(56);
reject('oops');
}, 2000);
});
p.then((value) => {
console.log('then 1', value);
return value + 1;
})
.then((value) => {
console.log('then 2', value);
})
.catch((err) => {
console.error('catch', err);
});
module.exports = CustomPromise;
|
/*
* Copyright (c) 1998,1999,2000
* Traakan, Inc., Los Altos, CA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Project: NDMJOB
* Ident: $Id: $
*
* Description:
*
*/
#include "ndmagents.h"
#ifndef NDMOS_OPTION_NO_CONTROL_AGENT
#define RETERR if (errcnt++ >= errskip) return errcnt;
#define ERROR(S) { if (errbuf) strcpy(errbuf, (S)); RETERR }
/*
* To just check a job:
* rc = ndma_job_audit (job, 0, 0);
* if (rc) { "error" }
*
* To display everything wrong with a job:
* i = n_err = 0;
* do {
* n_err = ndma_job_audit (job, errbuf, i);
* if (n_err) display (errbuf);
* i++;
* } while (i < n_err);
*
* if (n_err) { "error" }
*/
int
ndma_job_audit (struct ndm_job_param *job, char *errbuf, int errskip)
{
int errcnt = 0;
char * audit_what;
switch (job->operation) {
default:
ERROR ("invalid operatiton")
return -1;
case NDM_JOB_OP_BACKUP: audit_what = "DfbBmM"; break;
case NDM_JOB_OP_EXTRACT: audit_what = "DfbBmM"; break;
case NDM_JOB_OP_TOC: audit_what = "DfbBmM"; break;
case NDM_JOB_OP_QUERY_AGENTS: audit_what = ""; break;
case NDM_JOB_OP_INIT_LABELS: audit_what = "TfmM"; break;
case NDM_JOB_OP_LIST_LABELS: audit_what = "TfM"; break;
case NDM_JOB_OP_REMEDY_ROBOT: audit_what = ""; break;
case NDM_JOB_OP_TEST_TAPE: audit_what = "TfM"; break;
case NDM_JOB_OP_TEST_MOVER: audit_what = "TfbM"; break;
case NDM_JOB_OP_TEST_DATA: audit_what = "DB"; break;
case NDM_JOB_OP_REWIND_TAPE: audit_what = "Tf"; break;
case NDM_JOB_OP_EJECT_TAPE: audit_what = "Tf"; break;
case NDM_JOB_OP_MOVE_TAPE: audit_what = "Rr@"; break;
case NDM_JOB_OP_IMPORT_TAPE: audit_what = "Rr@"; break;
case NDM_JOB_OP_EXPORT_TAPE: audit_what = "Rr@"; break;
case NDM_JOB_OP_LOAD_TAPE: audit_what = "Rr@"; break;
case NDM_JOB_OP_UNLOAD_TAPE: audit_what = "Rr"; break;
case NDM_JOB_OP_INIT_ELEM_STATUS: audit_what = "Rr"; break;
}
while (*audit_what) switch (*audit_what++) {
case 'D': /* DATA agent provided */
if (job->data_agent.conn_type == NDMCONN_TYPE_NONE)
ERROR("missing DATA agent")
break;
case 'T': /* TAPE agent provided (use DATA if given) */
if (job->data_agent.conn_type == NDMCONN_TYPE_NONE
&& job->tape_agent.conn_type == NDMCONN_TYPE_NONE)
ERROR("missing TAPE or DATA agent")
break;
case 'R': /* ROBOT agent provided (use TAPE or DATA if given) */
if (job->data_agent.conn_type == NDMCONN_TYPE_NONE
&& job->tape_agent.conn_type == NDMCONN_TYPE_NONE
&& job->robot_agent.conn_type == NDMCONN_TYPE_NONE)
ERROR("missing ROBOT, TAPE or DATA agent")
break;
case 'B': /* Backup type */
if (!job->bu_type)
ERROR("missing bu_type")
break;
case 'b': /* block (record) size */
if (!job->record_size)
ERROR("missing record size")
break;
case 'f': /* tape file */
if (!job->tape_device)
ERROR("missing tape device")
break;
case 'm': /* media entry/ies */
if (job->media_tab.n_media < 1)
ERROR("missing media entry")
break;
case 'M': /* ? */
errcnt += ndma_job_media_audit (job, errbuf, errskip-errcnt);
break;
case 'r': /* robot file/device name */
if (!job->have_robot)
ERROR ("missing robot SCSI address");
break;
case '@': /* from and/or to address */
if (job->operation == NDM_JOB_OP_MOVE_TAPE
|| job->operation == NDM_JOB_OP_EXPORT_TAPE
|| job->operation == NDM_JOB_OP_LOAD_TAPE) {
if (!job->from_addr_given)
ERROR ("missing 'from' slot address");
}
if (job->operation == NDM_JOB_OP_MOVE_TAPE
|| job->operation == NDM_JOB_OP_IMPORT_TAPE) {
if (!job->to_addr_given)
ERROR ("missing 'to' slot address");
}
break;
default:
ERROR ("INTERNAL BOTCH")
return -2;
}
if (job->robot_agent.conn_type != NDMCONN_TYPE_NONE
&& !job->have_robot
&& job->operation != NDM_JOB_OP_QUERY_AGENTS) {
ERROR ("robot agent, but no robot")
}
return errcnt;
}
int
ndma_job_media_audit (struct ndm_job_param *job, char *errbuf, int errskip)
{
struct ndm_media_table *mtab = &job->media_tab;
int n_media = mtab->n_media;
struct ndmmedia * me;
struct ndmmedia * me2;
int errcnt = 0;
if (job->have_robot) {
for (me = mtab->head; me; me = me->next) {
if (!me->valid_slot) {
if (errbuf) {
sprintf (errbuf,
"media #%d missing slot address",
me->index);
}
RETERR
continue;
}
for (me2 = me->next; me2; me2 = me2->next) {
if (! me2->valid_slot)
continue;
if (me->slot_addr == me2->slot_addr) {
if (errbuf) {
sprintf (errbuf,
"media #%d dup slot addr w/ #%d",
me->index, me2->index);
}
RETERR
}
}
}
} else {
if (n_media > 1) {
ERROR ("no robot, too many media")
}
for (me = mtab->head; me; me = me->next) {
if (me->valid_slot) {
if (errbuf) {
sprintf (errbuf,
"media #%d slot address, but no robot",
me->index);
}
RETERR
}
}
}
if (job->operation == NDM_JOB_OP_INIT_LABELS) {
for (me = mtab->head; me; me = me->next) {
if (! me->valid_label) {
if (errbuf) {
sprintf (errbuf,
"media #%d missing label",
me->index);
}
RETERR
}
}
}
return 0;
}
void
ndma_job_auto_adjust (struct ndm_job_param *job)
{
struct ndmmedia * me;
if (job->media_tab.n_media == 0
&& !job->have_robot
&& job->operation != NDM_JOB_OP_INIT_LABELS) {
/* synthesize one media table entry */
me = ndma_store_media (&job->media_tab, 0);
if (me) {
/* As this is a fake media entry set valid_slot to 0 */
me->valid_slot = 0;
}
}
}
#endif /* !NDMOS_OPTION_NO_CONTROL_AGENT */
|
// i18n tables
var i18nTableEn = {
"introduction" : "Rediscover your town with the alternative routes of MoodWalkR !",
"itinerary" : " ITINERARY",
"loop" : " LOOP ROUTE",
"length" : "Shortest path",
"cost_activity" : "Shopping and activities",
"cost_nature" : "Nature",
"cost_culture" : "Culture",
"start" : "Start",
"startContent" : "Type the address of your starting point, e.g. '8 Grande Rue Nazareth, Toulouse'.",
"startCircular" : "Loop around this address",
"startCircularShort" : "Loop around this point",
"startCircularContent" : "Type the address that will be your start and destination, e.g. '8 Grande Rue Nazareth, Toulouse'.<br>By default, a 1-hour loop will be displayed.",
"destination" : "Destination",
"destinationContent" : "Type the address of your destination, e.g. '1 Rue des Cuves Saint-Sernin, Toulouse'.",
"compute" : "Compute",
"km" : "km",
"min" : "min",
"distance" : "distance",
"time" : "time",
"tour_step1" : "Welcome !<br />You can follow this introduction to discover MoodWalkr.<br />During this guided tour, you don't have to write in the text fields or click on the map: simply click on Next each time.",
"tour_step2" : "You can choose whether you want to walk between two locations, or walk a loop around a given place.<br />We will begin with an itinerary.",
"tour_step3" : "You can type the address of your starting point, e.g. '8 Grande Rue Nazareth, Toulouse'. Then, click on the search button on the right, or press the 'Enter' key.",
"tour_step4" : "Type the address of your destination. You will also be able to set the starting and destination points by <b>right-clicking</b> on the map.",
"tour_step5" : "The computed walking routes are now displayed on the map for 4 different profiles. We will choose the culture profile by clicking on the violet button.",
"tour_step6" : "Only the chosen route is now displayed. Markers appear along: they indicate interesting places related to the profile you have chosen. You will be able to click on them to get more information.",
"tour_step7" : "We will continue with a loop route.",
"tour_step8" : "As previously, you can type an address or right-click on the map.",
"tour_step9" : "By default, a 1-hour walking loop will be displayed. You can choose your profile by clicking on the buttons. We will choose the Nature profile in this tour.",
"tour_step10" : "Select how long you want to walk and click on Compute. We will choose 90 minutes.<br />The loop route is randomly chosen: if the one displayed doesn't suit you, simply click on Compute to get another one.",
"tour_step11" : "We are done, let's play with MoodWalkr !<br />You will be able to follow the guide again by clicking on the \"?\" icon at the bottom of the screen."
};
var i18nTableFr = {
"introduction" : "Redécouvrez votre ville grâce aux itinéraires alternatifs de MoodWalkR !",
"itinerary" : " ITINÉRAIRE",
"loop" : " BOUCLE",
"length" : "Au plus court",
"cost_activity" : "Courses et lieux d'activité",
"cost_nature" : "Nature",
"cost_culture" : "Culture" ,
"start" : "Point de départ",
"startContent" : "Tapez l'adresse de votre point de départ, par exemple '8 Grande Rue Nazareth, Toulouse'.",
"startCircular" : "Boucle autour de cette adresse",
"startCircularShort" : "Boucle autour de ce point",
"startCircularContent" : "Tapez l'adresse qui sera votre départ et votre arrivée, par exemple '8 Grande Rue Nazareth, Toulouse'.<br>Par défaut, une boucle d'une heure sera affichée.",
"destination" : "Destination",
"destinationContent" : "Tapez l'adresse de votre point d'arrivée, par exemple '1 Rue des Cuves Saint-Sernin, Toulouse'.",
"compute" : "Calculer",
"km" : "km",
"min" : "min",
"distance" : "distance",
"time" : "temps",
"tour_step1" : "Bienvenue !<br />Vous pouvez suivre ce guide pour découvrir MoodWalkR.<br />Pendant cette introduction, vous n'avez pas à écrire de texte ou à cliquer sur la carte : cliquez simplement sur \"Next\" à chaque étape.",
"tour_step2" : "Vous pouvez choisir si vous voulez marcher entre deux lieux, ou faire une boucle autour d'un point.<br />Nous allons commencer par un itinéraire.",
"tour_step3" : "Vous pouvez entrer l'adresse de votre point de départ, par exemple '8 Grande Rue Nazareth, Toulouse'. Ensuite, cliquez sur le bouton de recherche à droite, ou appuyez sur la touche Entrée de votre clavier.",
"tour_step4" : "Entrez l'adresse de votre destination. Vous pourrez également choisir les points de départ et d'arrivée par un <b>clic droit</b> sur la carte.",
"tour_step5" : "Les itinéraires calculés sont maintenant affichés sur la carte pour les 4 profils différents. Nous allons choisir le profil Culture en cliquant sur le bouton violet.",
"tour_step6" : "Seul l'itinéraire choisi est maintenant affiché. Des marqueurs sont affichés autour : ils indiquent les lieux intéressants pour le profil que vous avez choisi. Vous pourrez cliquer dessus pour obtenir plus d'informations.",
"tour_step7" : "Nous allons continuer avec une boucle.",
"tour_step8" : "Comme précédemment, vous pouvez entrer une adresse ou faire un clic droit sur la carte.",
"tour_step9" : "Par défaut, une boucle d'une heure est affichée. Vous pouvez choisir votre profil en cliquant sur les boutons. Nous allons choisir le profil Nature.",
"tour_step10" : "Sélectionnez la durée pendant laquelle vous souhaitez marcher et cliquez sur le bouton Calculer. Nous allons choisir 90 minutes.<br />L'itinéraire circulaire est choisi au hasard : si celui afiché ne vous plaît pas, cliquez simplement sur Calculer pour en générer un autre.",
"tour_step11" : "Cette introduction est terminée, amusez-vous avec MoodWalkR !<br />Vous pouvez revoir ce guide en cliquant sur l'icône \"?\" en bas de l'écran."
};
|
import { useDispatch } from 'react-redux';
import { deleteAnnotation as deleteAnnotationAction } from 'actions/pdfTextAnnotation';
const useDeleteAnnotation = () => {
const dispatch = useDispatch();
const deleteAnnotation = id => {
if (window.confirm('Are you sure?')) {
dispatch(deleteAnnotationAction(id));
}
};
return { deleteAnnotation };
};
export default useDeleteAnnotation;
|
# coding: utf-8
"""
Thola
REST API for Thola. For more information look at our Github : https://github.com/inexio/thola # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import thola_client
from thola_client.models.identify_request import IdentifyRequest # noqa: E501
from thola_client.rest import ApiException
class TestIdentifyRequest(unittest.TestCase):
"""IdentifyRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testIdentifyRequest(self):
"""Test IdentifyRequest"""
# FIXME: construct object with mandatory attributes with example values
# model = thola_client.models.identify_request.IdentifyRequest() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
const Koa = require('koa');
const db = require('./db');
const { router } = require('./router');
const app = new Koa();
const port = process.env.MONOTONE_PORT || 3030;
app.use(router);
db.createTable()
.then(() => db.seedTable())
.then(() => {
app.listen(port);
});
|
#ifndef FILAKEY_H
#define FILAKEY_H
#include <iostream>
using namespace std;
class FilaKey {
private:
struct Node {
string value;
Node* next = 0;
};
Node* first;
Node* last;
public:
FilaKey();
bool insert(string val);
bool popFirst(string *val);
int hasValue(string val);
int length();
void popAll();
};
#endif // FILAKEY_H
|
'use strict'
const { post, put } = require('./api');
const util = require('./utils')
module.exports = async (req, code, config) => {
const instance = {
name: `${req.elementKey}-${Date.now()}`,
tags: [
req.elementKey // tag instances w/ element key to filter out non-relevant instances when retrieving all instances for a data source
],
element:{
key: req.elementKey
},
providerData: {
code: code
},
configuration: util.buildConfiguration(config.properties, req.authData.configuration),
}
if (req.uniqueName) { instance.name = req.uniqueName }
if (req.authData.realmId) { instance.providerData.realmId = req.authData.realmId }
if (req.instanceId) {
return await put(`instances/${req.instanceId}`, instance, {
userSecret: req.authData.userSecret,
orgSecret: req.authData.orgSecret
})
} else {
return await post('instances', instance, {
userSecret: req.authData.userSecret,
orgSecret: req.authData.orgSecret
})
}
}
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from libscampi.core.fields import UserModelChoiceField
from libscampi.contrib.cms.newsengine.models import ArticleTranslation, Story, Publish
class ArticleTranslationForm(forms.ModelForm):
headline = forms.CharField(label = _('Headline'), widget = forms.TextInput(attrs={'size': 100}))
sub_headline = forms.CharField(label = _('Tagline'), widget = forms.TextInput(attrs={'size': 100}))
synopsis = forms.CharField(
widget = forms.Textarea(attrs={'cols': 80, 'rows': 10}),
required = False,
help_text = _("Article Synopsis, markup(down) allowed: see <a href='http://daringfireball.net/projects/markdown/syntax'>Markdown Syntax</a> for help")
)
body = forms.CharField(
widget = forms.Textarea(attrs={'cols': 80, 'rows': 30}),
help_text = _("Article body, markup(down) allowed: see <a href='http://daringfireball.net/projects/markdown/syntax'>Markdown Syntax</a> for help")
)
class Meta:
model = ArticleTranslation
fields = ('language', 'headline', 'sub_headline', 'synopsis', 'body')
class StoryForm(forms.ModelForm):
author = UserModelChoiceField(User.objects.all().order_by('first_name', 'last_name', 'username'))
class Meta:
model = Story
class PublishForm(forms.ModelForm):
class Meta:
model = Publish
def clean(self):
cleaned_data = super(PublishForm, self).clean()
if "story" in cleaned_data and "category" in cleaned_data:
story = cleaned_data['story']
category = cleaned_data['category']
else:
raise forms.ValidationError("Story & Type required.")
check = Publish.objects.filter(story=story, category=category)
if self.instance:
check = check.exclude(pk=self.instance.pk)
if check.exists():
raise forms.ValidationError("Story is already published as: {0:>s}".format(category.title))
return cleaned_data
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
def doit(node):
if node:
vals.append(str(node.val))
doit(node.left)
doit(node.right)
else:
vals.append('#')
vals = []
doit(root)
return ','.join(vals)
def deserialize(self, data):
def doit():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = doit()
node.right = doit()
return node
vals = iter(data.split(','))
return doit()
|
# Adopted from PyTorch Lightning Bolts.
# !/usr/bin/env python
import os
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
try:
import builtins
except ImportError:
import __builtin__ as builtins
# https://packaging.python.org/guides/single-sourcing-package-version/
# http://blog.ionelmc.ro/2014/05/25/python-packaging/
PATH_ROOT = os.path.dirname(__file__)
def load_requirements(path_dir=PATH_ROOT, file_name='requirements.txt', comment_char='#'):
with open(os.path.join(path_dir, file_name), 'r', encoding="utf-8", errors="ignore") as file:
lines = [ln.strip() for ln in file.readlines()]
reqs = []
for ln in lines:
if comment_char in ln: # filer all comments
ln = ln[:ln.index(comment_char)].strip()
if ln.startswith('http'): # skip directly installed dependencies
continue
if ln: # if requirement is not empty
reqs.append(ln)
return reqs
def load_long_description():
# url = os.path.join("https://github.com/Quick-AI/quickvision", 'raw', , 'docs')
text = open('README.md', encoding='utf-8', errors="ignore").read()
# replace relative repository path to absolute link to the release
# text = text.replace('](docs', f']({url}')
# SVG images are not readable on PyPI, so replace them with PNG
text = text.replace('.svg', '.png')
return text
# https://packaging.python.org/discussions/install-requires-vs-requirements /
setup(
name='quickvision',
version="0.2.1",
description="Computer Vision models and training",
author="Aditya Oke",
author_email="okeaditya315@gmail.com",
# url=pl_bolts.__homepage__,
download_url="https://github.com/Quick-AI/quickvision",
license="apache2",
packages=find_packages(exclude=['tests', 'docs']),
long_description=load_long_description(),
long_description_content_type='text/markdown',
include_package_data=True,
zip_safe=False,
keywords=['Deep Learning', 'PyTorch'],
python_requires='>=3.6',
setup_requires=[],
install_requires=load_requirements(),
project_urls={
"Bug Tracker": "https://github.com/Quick-AI/quickvision/issues",
"Documentation": "https://quick-ai.github.io/quickvision/",
"Source Code": "https://github.com/Quick-AI/quickvision",
},
classifiers=[
'Environment :: Console',
'Natural Language :: English',
# How mature is this project? Common values are
# 3 - Alpha, 4 - Beta, 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Image Recognition',
'Topic :: Scientific/Engineering :: Information Analysis',
# Pick your license as you wish
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)
|
/**
******************************************************************************
* @file joystick.c
* @author WILLIAM TUNG-MAO Wu
* @date 1-May-2014
* @brief Joystick initialisation and control
******************************************************************************
*/
#include "netduinoplus2.h"
#include "stm32f4xx_conf.h"
#include "debug_printf.h"
#include "nrf24l01plus.h"
#include "joystick.h"
//#define DEBUG 1
/**
* @brief Initialise joystick to be on Pins A0-2
* @param None
* @retval None
*/
void joystick_init(void){
joystick_init_X();
joystick_init_Y();
joystick_init_interrupt();
}
/**
* @brief Initialise joystick-X read on pin A0 using ADC1
* @param None
* @retval None
*/
void joystick_init_X(void) {
//A0 with ADC1 for joystick X-axis
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
ADC_CommonInitTypeDef ADC_CommonInitStructure;
/* Configure A0 as analog input */
GPIO_InitStructure.GPIO_Pin = NP2_A0_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(NP2_A0_GPIO_PORT, &GPIO_InitStructure);
/* Enable clock for ADC 1 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
/* ADC Common Init */
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
/* ADC Specific Init for 12Bit resolution and continuous sampling */
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = 0;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC1, &ADC_InitStructure);
/* Configure ADC1 to connect to the NP2 A0 channel */
ADC_RegularChannelConfig(ADC1, NP2_A0_ADC_CHAN, 1, ADC_SampleTime_3Cycles);
/* Enable ADC1 */
ADC_Cmd(ADC1, ENABLE);
}
/**
* @brief Initialise joystick-Y read on pin A1 using ADC2
* @param None
* @retval None
*/
void joystick_init_Y(void) {
//A1 with ADC2 for joystick Y-axis
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
ADC_CommonInitTypeDef ADC_CommonInitStructure;
/* Configure A1 as analog input */
GPIO_InitStructure.GPIO_Pin = NP2_A1_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(NP2_A1_GPIO_PORT, &GPIO_InitStructure);
/* Enable clock for ADC 2 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC2, ENABLE);
/* ADC Common Init */
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
/* ADC Specific Init for 12Bit resolution and continuous sampling */
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = 0;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC2, &ADC_InitStructure);
/* Configure ADC2 to connect to the NP2 A1 channel */
ADC_RegularChannelConfig(ADC2, NP2_A1_ADC_CHAN, 1, ADC_SampleTime_3Cycles);
/* Enable ADC2 */
ADC_Cmd(ADC2, ENABLE);
}
/**
* @brief Initialise joystick-interrupt read on pin A2
* @param None
* @retval None
*/
void joystick_init_interrupt(void){
//Configure for interrupt on pin A2
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
RCC_AHB1PeriphClockCmd(NP2_A2_GPIO_CLK, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_InitStructure.GPIO_Pin = NP2_A2_PIN;
GPIO_Init(NP2_A2_GPIO_PORT, &GPIO_InitStructure);
SYSCFG_EXTILineConfig(NP2_A2_EXTI_PORT, NP2_A2_EXTI_SOURCE);
EXTI_InitStructure.EXTI_Line = NP2_A2_EXTI_LINE;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = NP2_A2_EXTI_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
/**
* @brief Read the joystick-X value on Pin A0
* @param None
* @retval None
*/
int read_joystick_X(void){
//Middle Value 1985
unsigned int adc_value;
ADC_SoftwareStartConv(ADC1); //Perform ADC conversions
/* Wait for ADC conversion to finish by polling the ADC Over Flag. */
while ((ADC_GetFlagStatus(ADC1, ADC_FLAG_OVR) != RESET) && (ADC_GetFlagStatus(ADC1, ADC_FLAG_OVR) != RESET));
/* Extract ADC conversion values */
adc_value = ADC_GetConversionValue(ADC1);
#ifdef DEBUG
/* Print ADC conversion values */
debug_printf("ADC [X] Value: %d \n\r", adc_value);
#endif
ADC_ClearFlag(ADC1, ADC_FLAG_OVR);
return adc_value;
}
/**
* @brief Read the joystick-Y value on Pin A1
* @param None
* @retval None
*/
int read_joystick_Y(void){
//Middle Value 2300
unsigned int adc_value;
ADC_SoftwareStartConv(ADC2); //Perform ADC conversions
/* Wait for ADC conversion to finish by polling the ADC Over Flag. */
while ((ADC_GetFlagStatus(ADC2, ADC_FLAG_OVR) != RESET) && (ADC_GetFlagStatus(ADC2, ADC_FLAG_OVR) != RESET));
/* Extract ADC conversion values */
adc_value = ADC_GetConversionValue(ADC2);
#ifdef DEBUG
/* Print ADC conversion values */
debug_printf("ADC [Y] Value: %d \n\r", adc_value);
#endif
ADC_ClearFlag(ADC2, ADC_FLAG_OVR);
return adc_value;
}
|
"""
Django settings for djangoconnectiondashboard project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse_lazy
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)
)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# # SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = ''
#
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'teams',
'pages',
'base',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'djangoconnectiondashboard.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'djangoconnectiondashboard.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'ROC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = 'bootstrap3'
LOGIN_REDIRECT_URL = reverse_lazy('home')
def get_env_var(key):
try:
return os.environ[key]
except KeyError:
raise ImproperlyConfigured(
'Environment variable {key} required.'.format(key=key)
)
|
window.JitsiMeetJS=window.JitsiMeetJS||{},window.JitsiMeetJS.app=window.JitsiMeetJS.app||{},window.JitsiMeetJS.app.effects=function(t){var e={};function n(r){if(e[r])return e[r].exports;var a=e[r]={i:r,l:!1,exports:{}};return t[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)n.d(r,a,function(e){return t[e]}.bind(null,a));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/libs/",n(n.s=13)}([function(t,e,n){"use strict";n.r(e),function(t,r,a,o){n.d(e,"AdadeltaOptimizer",(function(){return _f})),n.d(e,"AdagradOptimizer",(function(){return Ff})),n.d(e,"AdamOptimizer",(function(){return Mf})),n.d(e,"AdamaxOptimizer",(function(){return Bf})),n.d(e,"DataStorage",(function(){return pa})),n.d(e,"ENV",(function(){return d})),n.d(e,"Environment",(function(){return l})),n.d(e,"KernelBackend",(function(){return fa})),n.d(e,"MomentumOptimizer",(function(){return Lf})),n.d(e,"Optimizer",(function(){return Df})),n.d(e,"RMSPropOptimizer",(function(){return Vf})),n.d(e,"Rank",(function(){return Ct})),n.d(e,"Reduction",(function(){return Dl})),n.d(e,"SGDOptimizer",(function(){return Pf})),n.d(e,"Tensor",(function(){return wt})),n.d(e,"TensorBuffer",(function(){return gt})),n.d(e,"Variable",(function(){return Rt})),n.d(e,"abs",(function(){return As})),n.d(e,"acos",(function(){return Os})),n.d(e,"acosh",(function(){return Ds})),n.d(e,"add",(function(){return Au})),n.d(e,"addN",(function(){return Ou})),n.d(e,"addStrict",(function(){return Du})),n.d(e,"all",(function(){return $c})),n.d(e,"any",(function(){return Qc})),n.d(e,"argMax",(function(){return Jc})),n.d(e,"argMin",(function(){return Zc})),n.d(e,"asin",(function(){return _s})),n.d(e,"asinh",(function(){return Fs})),n.d(e,"atan",(function(){return Ms})),n.d(e,"atan2",(function(){return _u})),n.d(e,"atanh",(function(){return Bs})),n.d(e,"avgPool",(function(){return Wc})),n.d(e,"avgPool3d",(function(){return jc})),n.d(e,"backend",(function(){return cn})),n.d(e,"backend_util",(function(){return Da})),n.d(e,"basicLSTMCell",(function(){return vl})),n.d(e,"batchNorm",(function(){return bu})),n.d(e,"batchNorm2d",(function(){return wu})),n.d(e,"batchNorm3d",(function(){return Cu})),n.d(e,"batchNorm4d",(function(){return Eu})),n.d(e,"batchNormalization",(function(){return xu})),n.d(e,"batchNormalization2d",(function(){return vu})),n.d(e,"batchNormalization3d",(function(){return gu})),n.d(e,"batchNormalization4d",(function(){return yu})),n.d(e,"batchToSpaceND",(function(){return dr})),n.d(e,"booleanMaskAsync",(function(){return hc})),n.d(e,"broadcastTo",(function(){return hr})),n.d(e,"browser",(function(){return wf})),n.d(e,"buffer",(function(){return pr})),n.d(e,"cast",(function(){return mr})),n.d(e,"ceil",(function(){return Ps})),n.d(e,"clipByValue",(function(){return Ls})),n.d(e,"clone",(function(){return vr})),n.d(e,"complex",(function(){return Rn})),n.d(e,"concat",(function(){return Kn})),n.d(e,"concat1d",(function(){return Xn})),n.d(e,"concat2d",(function(){return Yn})),n.d(e,"concat3d",(function(){return $n})),n.d(e,"concat4d",(function(){return Qn})),n.d(e,"conv1d",(function(){return yc})),n.d(e,"conv2d",(function(){return xc})),n.d(e,"conv2dTranspose",(function(){return Rc})),n.d(e,"conv3d",(function(){return bc})),n.d(e,"conv3dTranspose",(function(){return Tc})),n.d(e,"cos",(function(){return Vs})),n.d(e,"cosh",(function(){return Ws})),n.d(e,"cumsum",(function(){return gr})),n.d(e,"customGrad",(function(){return sa})),n.d(e,"deprecationWarn",(function(){return qe})),n.d(e,"depthToSpace",(function(){return yr})),n.d(e,"depthwiseConv2d",(function(){return Ec})),n.d(e,"diag",(function(){return kl})),n.d(e,"disableDeprecationWarnings",(function(){return He})),n.d(e,"dispose",(function(){return Je})),n.d(e,"disposeVariables",(function(){return Ke})),n.d(e,"div",(function(){return Fu})),n.d(e,"divNoNan",(function(){return Mu})),n.d(e,"divStrict",(function(){return Bu})),n.d(e,"dot",(function(){return Ac})),n.d(e,"dropout",(function(){return Al})),n.d(e,"elu",(function(){return sl})),n.d(e,"enableDebugMode",(function(){return Ge})),n.d(e,"enableProdMode",(function(){return je})),n.d(e,"engine",(function(){return Xe})),n.d(e,"env",(function(){return f})),n.d(e,"equal",(function(){return Ju})),n.d(e,"equalStrict",(function(){return Zu})),n.d(e,"erf",(function(){return zs})),n.d(e,"exp",(function(){return Us})),n.d(e,"expandDims",(function(){return xr})),n.d(e,"expm1",(function(){return js})),n.d(e,"eye",(function(){return br})),n.d(e,"fft",(function(){return Cl})),n.d(e,"fill",(function(){return Un})),n.d(e,"findBackend",(function(){return on})),n.d(e,"findBackendFactory",(function(){return sn})),n.d(e,"floor",(function(){return Gs})),n.d(e,"floorDiv",(function(){return Pu})),n.d(e,"frame",(function(){return Ml})),n.d(e,"fused",(function(){return hp})),n.d(e,"gather",(function(){return fc})),n.d(e,"gatherND",(function(){return Tl})),n.d(e,"getBackend",(function(){return rn})),n.d(e,"getGradient",(function(){return g})),n.d(e,"getKernel",(function(){return v})),n.d(e,"getKernelsForBackend",(function(){return y})),n.d(e,"grad",(function(){return na})),n.d(e,"grads",(function(){return ra})),n.d(e,"greater",(function(){return tc})),n.d(e,"greaterEqual",(function(){return ec})),n.d(e,"greaterEqualStrict",(function(){return nc})),n.d(e,"greaterStrict",(function(){return rc})),n.d(e,"hammingWindow",(function(){return Fl})),n.d(e,"hannWindow",(function(){return _l})),n.d(e,"ifft",(function(){return El})),n.d(e,"imag",(function(){return kn})),n.d(e,"image",(function(){return ip})),n.d(e,"inTopKAsync",(function(){return Ll})),n.d(e,"io",(function(){return gf})),n.d(e,"irfft",(function(){return Nl})),n.d(e,"isFinite",(function(){return nu})),n.d(e,"isInf",(function(){return eu})),n.d(e,"isNaN",(function(){return tu})),n.d(e,"keep",(function(){return Ze})),n.d(e,"leakyRelu",(function(){return ul})),n.d(e,"less",(function(){return ac})),n.d(e,"lessEqual",(function(){return oc})),n.d(e,"lessEqualStrict",(function(){return ic})),n.d(e,"lessStrict",(function(){return sc})),n.d(e,"linalg",(function(){return Zl})),n.d(e,"linspace",(function(){return jn})),n.d(e,"localResponseNormalization",(function(){return hl})),n.d(e,"log",(function(){return Hs})),n.d(e,"log1p",(function(){return qs})),n.d(e,"logSigmoid",(function(){return Ks})),n.d(e,"logSoftmax",(function(){return la})),n.d(e,"logSumExp",(function(){return tl})),n.d(e,"logicalAnd",(function(){return Su})),n.d(e,"logicalNot",(function(){return Nu})),n.d(e,"logicalOr",(function(){return Iu})),n.d(e,"logicalXor",(function(){return Ru})),n.d(e,"losses",(function(){return Xl})),n.d(e,"matMul",(function(){return kc})),n.d(e,"math",(function(){return xf})),n.d(e,"max",(function(){return el})),n.d(e,"maxPool",(function(){return Vc})),n.d(e,"maxPool3d",(function(){return Uc})),n.d(e,"maximum",(function(){return Lu})),n.d(e,"maximumStrict",(function(){return Vu})),n.d(e,"mean",(function(){return nl})),n.d(e,"memory",(function(){return Ye})),n.d(e,"min",(function(){return rl})),n.d(e,"minimum",(function(){return Wu})),n.d(e,"minimumStrict",(function(){return zu})),n.d(e,"mod",(function(){return Uu})),n.d(e,"modStrict",(function(){return ju})),n.d(e,"moments",(function(){return al})),n.d(e,"movingAverage",(function(){return yl})),n.d(e,"mul",(function(){return Gu})),n.d(e,"mulStrict",(function(){return Hu})),n.d(e,"multiRNNCell",(function(){return gl})),n.d(e,"multinomial",(function(){return wr})),n.d(e,"neg",(function(){return Xs})),n.d(e,"nextFrame",(function(){return jf})),n.d(e,"norm",(function(){return ml})),n.d(e,"notEqual",(function(){return uc})),n.d(e,"notEqualStrict",(function(){return cc})),n.d(e,"oneHot",(function(){return Cr})),n.d(e,"ones",(function(){return Wn})),n.d(e,"onesLike",(function(){return Hn})),n.d(e,"op",(function(){return In})),n.d(e,"outerProduct",(function(){return Oc})),n.d(e,"pad",(function(){return Er})),n.d(e,"pad1d",(function(){return Sr})),n.d(e,"pad2d",(function(){return Nr})),n.d(e,"pad3d",(function(){return Ir})),n.d(e,"pad4d",(function(){return Rr})),n.d(e,"pool",(function(){return zc})),n.d(e,"pow",(function(){return qu})),n.d(e,"powStrict",(function(){return Ku})),n.d(e,"prelu",(function(){return cl})),n.d(e,"print",(function(){return fr})),n.d(e,"prod",(function(){return il})),n.d(e,"profile",(function(){return $e})),n.d(e,"rand",(function(){return Tr})),n.d(e,"randomGamma",(function(){return Ar})),n.d(e,"randomNormal",(function(){return kr})),n.d(e,"randomUniform",(function(){return Or})),n.d(e,"range",(function(){return Gn})),n.d(e,"ready",(function(){return nn})),n.d(e,"real",(function(){return Tn})),n.d(e,"reciprocal",(function(){return Ys})),n.d(e,"registerBackend",(function(){return un})),n.d(e,"registerGradient",(function(){return b})),n.d(e,"registerKernel",(function(){return x})),n.d(e,"relu",(function(){return ll})),n.d(e,"relu6",(function(){return pl})),n.d(e,"removeBackend",(function(){return an})),n.d(e,"reshape",(function(){return Dr})),n.d(e,"reverse",(function(){return Dc})),n.d(e,"reverse1d",(function(){return _c})),n.d(e,"reverse2d",(function(){return Fc})),n.d(e,"reverse3d",(function(){return Mc})),n.d(e,"reverse4d",(function(){return Bc})),n.d(e,"rfft",(function(){return Sl})),n.d(e,"round",(function(){return $s})),n.d(e,"rsqrt",(function(){return Qs})),n.d(e,"scalar",(function(){return Dn})),n.d(e,"scatterND",(function(){return wl})),n.d(e,"selu",(function(){return fl})),n.d(e,"separableConv2d",(function(){return Ic})),n.d(e,"serialization",(function(){return Nf})),n.d(e,"setBackend",(function(){return en})),n.d(e,"setPlatform",(function(){return ln})),n.d(e,"setdiff1dAsync",(function(){return Vr})),n.d(e,"sigmoid",(function(){return Js})),n.d(e,"sign",(function(){return Zs})),n.d(e,"signal",(function(){return Pl})),n.d(e,"sin",(function(){return ru})),n.d(e,"sinh",(function(){return au})),n.d(e,"slice",(function(){return Gc})),n.d(e,"slice1d",(function(){return Hc})),n.d(e,"slice2d",(function(){return qc})),n.d(e,"slice3d",(function(){return Kc})),n.d(e,"slice4d",(function(){return Xc})),n.d(e,"slice_util",(function(){return ea})),n.d(e,"softmax",(function(){return ca})),n.d(e,"softplus",(function(){return ou})),n.d(e,"spaceToBatchND",(function(){return _r})),n.d(e,"sparseToDense",(function(){return Rl})),n.d(e,"spectral",(function(){return Il})),n.d(e,"split",(function(){return Jn})),n.d(e,"sqrt",(function(){return iu})),n.d(e,"square",(function(){return ks})),n.d(e,"squaredDifference",(function(){return Xu})),n.d(e,"squaredDifferenceStrict",(function(){return Yu})),n.d(e,"squeeze",(function(){return Fr})),n.d(e,"stack",(function(){return Mr})),n.d(e,"step",(function(){return su})),n.d(e,"stft",(function(){return Bl})),n.d(e,"stridedSlice",(function(){return xl})),n.d(e,"sub",(function(){return $u})),n.d(e,"subStrict",(function(){return Qu})),n.d(e,"sum",(function(){return ol})),n.d(e,"tan",(function(){return uu})),n.d(e,"tanh",(function(){return cu})),n.d(e,"tensor",(function(){return An})),n.d(e,"tensor1d",(function(){return _n})),n.d(e,"tensor2d",(function(){return Fn})),n.d(e,"tensor3d",(function(){return Mn})),n.d(e,"tensor4d",(function(){return Bn})),n.d(e,"tensor5d",(function(){return Pn})),n.d(e,"tensor6d",(function(){return Ln})),n.d(e,"tensor_util",(function(){return Mt})),n.d(e,"test_util",(function(){return kf})),n.d(e,"tidy",(function(){return Qe})),n.d(e,"tile",(function(){return Br})),n.d(e,"time",(function(){return tn})),n.d(e,"topk",(function(){return bl})),n.d(e,"train",(function(){return zf})),n.d(e,"transpose",(function(){return dl})),n.d(e,"truncatedNormal",(function(){return Pr})),n.d(e,"unregisterGradient",(function(){return C})),n.d(e,"unregisterKernel",(function(){return w})),n.d(e,"unsortedSegmentSum",(function(){return dc})),n.d(e,"unstack",(function(){return Lr})),n.d(e,"util",(function(){return pt})),n.d(e,"valueAndGrad",(function(){return aa})),n.d(e,"valueAndGrads",(function(){return oa})),n.d(e,"variable",(function(){return Vn})),n.d(e,"variableGrads",(function(){return ia})),n.d(e,"version_core",(function(){return Af})),n.d(e,"webgl",(function(){return Of})),n.d(e,"where",(function(){return Tu})),n.d(e,"whereAsync",(function(){return ku})),n.d(e,"zeros",(function(){return zn})),n.d(e,"zerosLike",(function(){return qn}));
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function s(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function u(t,e,n,r){return new(n||(n=Promise))((function(a,o){function i(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(i,s)}u((r=r.apply(t,e||[])).next())}))}function c(t,e){var n,r,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=e.call(t,i)}catch(t){o=[6,t],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var l=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},t.prototype.get=function(t){return t in this.flags||(this.flags[t]=this.evaluateFlag(t)),this.flags[t]},t.prototype.getNumber=function(t){return this.get(t)},t.prototype.getBool=function(t){return this.get(t)},t.prototype.getFlags=function(){return this.flags},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},t.prototype.setFlags=function(t){this.flags=Object.assign({},t)},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return p(n,e[0],e[1]),e.join("=")})),n);"tfjsflags"in r&&r.tfjsflags.split(",").forEach((function(e){var n=e.split(":"),r=n[0],a=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,a)}))}},t}();function p(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function f(){return d}var d=null,h=new Map,m=new Map;function v(t,e){var n=E(t,e);return h.get(n)}function g(t){return m.get(t)}function y(t){for(var e=h.entries(),n=[];;){var r=e.next(),a=r.done,o=r.value;if(a)break;var i=o[0],s=o[1];i.split("_")[0]===t&&n.push(s)}return n}function x(t){var e=t.kernelName,n=t.backendName,r=E(e,n);if(h.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");h.set(r,t)}function b(t){var e=t.kernelName;m.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),m.set(e,t)}function w(t,e){var n=E(t,e);if(!h.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");h.delete(n)}function C(t){if(!m.has(t))throw new Error("The gradient '"+t+"' for backend is not registered");m.delete(t)}function E(t,e){return e+"_"+t}function S(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function N(t,e,n){return Math.max(t,Math.min(e,n))}function I(t){return t%2==0?t:t+1}function R(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function T(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function k(t,e,n){void 0===n&&(n=""),T(_(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function A(t){T(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function O(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||K(t)&&!n)for(var r=0;r<t.length;++r)O(t[r],e,n);else e.push(t);return e}function D(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function _(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function F(t){return t%1==0}function M(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function B(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function P(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function L(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise((function(r,a){var o=0,i=function(){if(t())r();else{o++;var s=e(o);null!=n&&o>=n?a():setTimeout(i,s)}};i()}))}function V(t,e){for(var n=1,r=-1,a=0;a<t.length;++a)if(t[a]>=0)n*=t[a];else if(-1===t[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(t[a]<0)throw Error("Shapes can not be < 0. Found "+t[a]+" at dim "+a);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o}function W(t,e){var n=e.length;return T((t=null==t?e.map((function(t,e){return e})):[].concat(t)).every((function(t){return t>=-n&&t<n})),(function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t})),T(t.every((function(t){return F(t)})),(function(){return"All values in axis param must be integers but got axis "+t})),t.map((function(t){return t<0?n+t:t}))}function z(t,e){for(var n=[],r=[],a=null!=e&&Array.isArray(e)&&0===e.length,o=null==e||a?null:W(e,t).sort(),i=0,s=0;s<t.length;++s){if(null!=o){if(o[i]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==o[i]||o[i]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),o[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function U(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function j(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function G(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function H(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function q(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function K(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function X(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function Y(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function $(t){return"string"==typeof t||t instanceof String}function Q(t){return"boolean"==typeof t}function J(t){return"number"==typeof t}function Z(t){return Array.isArray(t)?Z(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":J(t)?"float32":$(t)?"string":Q(t)?"bool":"float32"}function tt(t){return!!(t&&t.constructor&&t.call&&t.apply)}function et(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function nt(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function rt(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=O(t)),n&&G(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),a=0;a<r.length;++a)0!==Math.round(t[a])&&(r[a]=1);return r}throw new Error("Unknown data type "+e)}function at(t,e){if(0===t.length)return e[0];var n=t.reduce((function(t,e){return t*e}));if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var a=new Array;if(1===n.length)for(var o=n[0],i=0;i<o;i++)a[i]=r[e+i];else{o=n[0];var s=n.slice(1),u=s.reduce((function(t,e){return t*e}));for(i=0;i<o;i++)a[i]=t(e+i*u,s,r)}return a}(0,t,e)}function ot(t,e){for(var n=it(t,e),r=0;r<n.length;r++)n[r]=1;return n}function it(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function st(){return f().platform.now()}function ut(t){t.forEach((function(e){T(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function ct(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",f().platform.encode(t,e)}function lt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",f().platform.decode(t,e)}var pt=Object.freeze({shuffle:S,clamp:N,nearestLargerEven:I,sum:R,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var a=Number(t[r])-Number(e[r]);n+=a*a}return n},assert:T,assertShapesMatch:k,assertNonNull:A,flatten:O,sizeFromShape:D,isScalarShape:function(t){return 0===t.length},arraysEqual:_,isInt:F,tanh:M,sizeToSquarishShape:B,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return S(e),e},rightPad:P,repeatedTry:L,inferFromImplicitShape:V,parseAxisParam:W,squeezeShape:z,getTypedArrayFromDType:U,getArrayFromDType:j,checkConversionForErrors:G,isValidDtype:H,hasEncodingLoss:q,isTypedArray:K,bytesPerElement:X,bytesFromStringArray:Y,isString:$,isBoolean:Q,isNumber:J,inferDtype:Z,isFunction:tt,nearestDivisor:et,computeStrides:nt,toTypedArray:rt,toNestedArray:at,makeOnesTypedArray:ot,makeZerosTypedArray:it,now:st,assertNonNegativeIntegerDimensions:ut,fetch:function(t,e){return f().platform.fetch(t,e)},encodeString:ct,decodeString:lt}),ft=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new dt)}return t.prototype.profileKernel=function(t,e,n){var r,a=this,o=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var a=t[r];if(isNaN(a)||!isFinite(a))return console.warn("Found "+a+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),o.then((function(o){var i="";null!=o.getExtraProfileInfo&&(i=o.getExtraProfileInfo()),a.logger.logKernelProfile(t,n,r,o.kernelMs,e,i)}))}))})),r},t}(),dt=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,a,o){var i=P(r+"ms",9),s=P(t,25),u=e.rank,c=e.size,l=P(e.shape.toString(),14),p="";for(var f in a){var d=a[f].shape||e.shape,h=d.length;p+=f+": "+h+"D "+(h>0?d:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+p+"\t%c"+o,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();function ht(t,e,n){return P(Array.isArray(t)?parseFloat(t[0].toFixed(7))+" + "+parseFloat(t[1].toFixed(7))+"j":$(t)?"'"+t+"'":"bool"===n?mt(t):parseFloat(t.toFixed(7)).toString(),e)}function mt(t){return 0===t?"false":"true"}function vt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var gt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=D(t),null!=n){var a=n.length;T(a===this.size,(function(){return"Length of values '"+a+"' does not match the size inferred by the shape '"+r.size+"'."}))}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||j(e,this.size),this.strides=nt(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),T(n.length===this.rank,(function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"}));var a=this.locToIndex(n);this.values[a]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,a=t;r<a.length;r++){var o=a[r];if(o<0||o>=this.shape[n]){var i="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return yt().makeTensor(this.values,this.shape,this.dtype)},t}(),yt=null,xt=null,bt=null,wt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=D(t),this.strides=nt(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),T(1===this.size,(function(){return"The array must have only 1 element."})),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,a){return this.throwIfDisposed(),this.reshape([t,e,n,r,a])},t.prototype.asType=function(t){return this.throwIfDisposed(),xt.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,xt.buffer(this.shape,this.dtype,t)]}}))}))},t.prototype.bufferSync=function(){return xt.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,at(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return at(this.shape,this.dataSync())},t.prototype.data=function(){return u(this,void 0,void 0,(function(){var t,e;return c(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=yt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map((function(t){return lt(t)}))]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,t]}}))}))},t.prototype.dataSync=function(){this.throwIfDisposed();var t=yt().readSync(this.dataId);if("string"===this.dtype)try{return t.map((function(t){return lt(t)}))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},t.prototype.bytes=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,yt().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)]}}))}))},t.prototype.dispose=function(){this.isDisposed||(yt().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),xt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),xt.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),xt.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),xt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),xt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),xt.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),xt.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),function(t,e,n,r){var a=nt(e),o=function(t,e,n,r){var a=D(e),o=r[r.length-1],i=new Array(o).fill(0),s=e.length,u="complex64"===n?vt(t):t;if(s>1)for(var c=0;c<a/o;c++)for(var l=c*o,p=0;p<o;p++)i[p]=Math.max(i[p],ht(u[l+p],0,n).length);return i}(t,e,n,a),i=e.length,s=function t(e,n,r,a,o,i){void 0===i&&(i=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c)return"complex64"===r?[ht(vt(e)[0],0,r)]:"bool"===r?[mt(e[0])]:[e[0].toString()];if(1===c){if(u>20){var l=3*s,p=Array.from(e.slice(0,l)),f=Array.from(e.slice((u-3)*s,u*s));return"complex64"===r&&(p=vt(p),f=vt(f)),["["+p.map((function(t,e){return ht(t,o[e],r)})).join(", ")+", ..., "+f.map((function(t,e){return ht(t,o[u-3+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?vt(e):Array.from(e)).map((function(t,e){return ht(t,o[e],r)})).join(", ")+"]"]}var d=n.slice(1),h=a.slice(1),m=a[0]*s,v=[];if(u>20){for(var g=0;g<3;g++){var y=(x=g*m)+m;v.push.apply(v,t(e.slice(x,y),d,r,h,o,!1))}for(v.push("..."),g=u-3;g<u;g++)y=(x=g*m)+m,v.push.apply(v,t(e.slice(x,y),d,r,h,o,g===u-1))}else for(g=0;g<u;g++){var x;y=(x=g*m)+m,v.push.apply(v,t(e.slice(x,y),d,r,h,o,g===u-1))}var b=2===c?",":"";for(v[0]="["+v[0]+b,g=1;g<v.length-1;g++)v[g]=" "+v[g]+b;var w=",\n";for(g=2;g<c;g++)w+="\n";return v[v.length-1]=" "+v[v.length-1]+"]"+(i?"":w),v}(t,e,n,a,o),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+i),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map((function(t){return" "+t})).join("\n")),u.join("\n")}(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),xt.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),xt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),xt.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),xt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),xt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),xt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),xt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),xt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),xt.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),xt.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,a){return void 0===n&&(n=.001),bt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,a,r,n)},t.prototype.batchNorm=function(t,e,n,r,a){return void 0===a&&(a=.001),this.throwIfDisposed(),xt.batchNorm(this,t,e,n,r,a)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),xt.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),xt.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),xt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),xt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),xt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),xt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),xt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),xt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),xt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),xt.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),xt.div(this,t)},t.prototype.divNoNan=function(t){return this.throwIfDisposed(),xt.divNoNan(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),xt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),xt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),xt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),xt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),xt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),xt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),xt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),xt.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),xt.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),xt.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),xt.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),xt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),xt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),xt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),xt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),xt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),xt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),xt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),xt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),xt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),xt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),xt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),xt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),xt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),xt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),xt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),xt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),xt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),xt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),xt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),xt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),xt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),xt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),xt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),xt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),xt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),xt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),xt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),xt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),xt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),xt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),xt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),xt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),xt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),xt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),xt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),xt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),xt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),xt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),xt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),xt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),xt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),xt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),xt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),xt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),xt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),xt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),xt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),xt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),xt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),xt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),xt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),xt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),xt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),xt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),xt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),xt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),xt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),xt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),xt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),xt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,a,o){return void 0===r&&(r="NWC"),void 0===a&&(a=1),this.throwIfDisposed(),xt.conv1d(this,t,e,n,r,a,o)},t.prototype.conv2d=function(t,e,n,r,a,o){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),xt.conv2d(this,t,e,n,r,a,o)},t.prototype.conv2dTranspose=function(t,e,n,r,a){return this.throwIfDisposed(),xt.conv2dTranspose(this,t,e,n,r,a)},t.prototype.depthwiseConv2D=function(t,e,n,r,a,o){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),xt.depthwiseConv2d(this,t,e,n,r,a,o)},t.prototype.separableConv2d=function(t,e,n,r,a,o){return void 0===a&&(a=[1,1]),void 0===o&&(o="NHWC"),this.throwIfDisposed(),xt.separableConv2d(this,t,e,n,r,a,o)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),xt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),xt.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),xt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,a){return this.throwIfDisposed(),xt.pool(this,t,e,n,r,a)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),yt().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),xt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),xt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),xt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),xt.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,a,o,i,s){return void 0===r&&(r=0),void 0===a&&(a=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),xt.stridedSlice(this,t,e,n,r,a,o,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),xt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),xt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),xt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),xt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),xt.spectral.irfft(this)},t}();Object.defineProperty(wt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var Ct,Et,St,Nt,It,Rt=function(t){function e(e,n,r,a){var o=t.call(this,e.shape,e.dtype,e.dataId,a)||this;return o.trainable=n,o.name=r,o}return s(e,t),e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!_(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");yt().disposeTensor(this),this.dataId=t.dataId,yt().incRef(this,null)},e.prototype.dispose=function(){yt().disposeVariable(this),this.isDisposedInternal=!0},e}(wt);Object.defineProperty(Rt,Symbol.hasInstance,{value:function(t){return t instanceof wt&&null!=t.assign&&t.assign instanceof Function}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(Ct||(Ct={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(Et||(Et={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(St||(St={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(Nt||(Nt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(It||(It={}));var Tt={float32:Nt,int32:Et,bool:St,complex64:It};function kt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return Tt[t][e]}function At(t){return kt(t,"int32")}function Ot(t,e){if(t.dtype===e.dtype)return[t,e];var n=kt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Dt(t,e){T(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function _t(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof wt)n.push(e);else if(a=e,Array.isArray(a)||"object"==typeof a){var a,o=e;for(var i in o){var s=o[i];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}var Ft,Mt=Object.freeze({makeTypesMatch:Ot,assertTypesMatch:Dt,isTensorInList:function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1},getTensorsInContainer:_t}),Bt=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),Pt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Bt}return t.prototype.ready=function(){return u(this,void 0,void 0,(function(){var t,e,n;return c(this,(function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then((function(){}))];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}}))}))},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory)},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},t.prototype.setBackend=function(t){return u(this,void 0,void 0,(function(){var e,n,r;return c(this,(function(a){switch(a.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=a.sent(),[3,3];case 2:r=n,a.label=3;case 3:if(!r)return[2,!1];a.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new ft(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;y(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;y(t).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])}))},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var a=++this.pendingBackendInitId,o=r.then((function(n){return!(a<e.pendingBackendInitId||(e.registry[t]=n,e.pendingBackendInit=null,0))})).catch((function(n){return!(a<e.pendingBackendInitId||(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),1))}));return this.pendingBackendInit=o,{success:o,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority}))},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),a=r.success,o=r.asyncInit;if(o||a)return{name:n,asyncInit:o}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,a=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,a,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},t.prototype.tidy=function(t,e){var n,r=this,a=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");a=t}return this.scopedRun((function(){return r.startScope(a)}),(function(){return r.endScope(n)}),(function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n}))},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(function(t){return{x:function(){return t.toFloat()}}}),[]),e},t.prototype.runKernel=function(t,e,n,r,a){return this.runKernelFunc(null,e,null,t,n,r,a)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),a=0;n.forEach((function(t){a+="complex64"===t.dtype?3:1}));var o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-e-a-o;if(i>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,a,o,i){var s,u=this;void 0===o&&(o=[]),void 0===i&&(i=[]);var c=[],l=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var p,f=function(t){l&&(c=t.map((function(t){return u.keep(u.clone(t))})))},d=this.state.numBytes,h=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,g=v(r,this.backendName);return p=null!=g?function(){var t=u.backend.numDataIds();m=g.kernelFunc({inputs:e,attrs:a,backend:u.backend});var n=Array.isArray(m)?m:[m];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)})),c=s.filter((function(t,e){return i[e]}));return f((o||[]).slice().concat(c)),s}:function(){var e=u.backend.numDataIds();m=u.tidy((function(){return t(u.backend,f)}));var n=Array.isArray(m)?m:[m];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n},this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return p()})):p()})),l&&this.addTapeNode(r,e,s,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-h,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(m)?s:s[0]},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var a=t;"string"===n&&$(t[0])&&(a=t.map((function(t){return ct(t)})));var o=r.write(a,e,n),i=new wt(e,n,o,this.nextTensorId());if(this.incRef(i,r),"string"===n){var s=this.state.tensorInfo.get(o),u=Y(a);this.state.numBytes+=u-s.bytes,s.bytes=u}return i},t.prototype.makeTensorFromDataId=function(t,e,n,r){var a=new wt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(a,r),a},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var a=new Rt(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*X(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Rt||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return u(this,void 0,void 0,(function(){var e,n;return c(this,(function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(t){return t.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n,r,a){var o=this,i={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:a},s=g(t);null!=s&&(r=s.gradFunc),null!=r&&(i.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],a=it(r.size,r.dtype);return o.makeTensor(a,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],a)}),this.state.activeTape.push(i)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=_t(t),r=new Set(n.map((function(t){return t.id}))),a=0;a<this.state.activeScope.track.length;a++){var o=this.state.activeScope.track[a];o.kept||r.has(o.id)||o.dispose()}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(t){t.kept||t.scopeId!==i.id||e.track(t)}))},t.prototype.gradients=function(t,e,n,r){var a=this;if(void 0===r&&(r=!1),T(e.length>0,(function(){return"gradients() received an empty list of xs."})),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var o=this.scopedRun((function(){return a.startTape()}),(function(){return a.endTape()}),(function(){return a.tidy("forward",t)}));T(o instanceof wt,(function(){return"The result y returned by f() must be a tensor."}));var i=function(t,e,n){for(var r={},a={},o=0;o<e.length;o++)r[e[o].id]=!0;for(o=0;o<t.length;o++){var i=(h=t[o]).inputs;for(var s in i){for(var u=i[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){h.outputs.forEach((function(t){return r[t.id]=!0})),c=!0,a[h.id]=!0;break}if(c)break}}var p={};p[n.id]=!0;var f={};for(o=t.length-1;o>=0;o--)for(i=(h=t[o]).inputs,l=0;l<h.outputs.length;l++)if(p[h.outputs[l].id]){for(var s in i)p[i[s].id]=!0,f[h.id]=!0;break}var d=[];for(o=0;o<t.length;o++){var h;if(a[(h=t[o]).id]&&f[h.id]){var m={};for(var s in h.inputs){var v=h.inputs[s];r[v.id]&&(m[s]=v)}var g=Object.assign({},h);g.inputs=m,g.outputs=h.outputs,d.push(g)}}return d}(this.state.activeTape,e,o);if(!r&&0===i.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(function(){var t,r,s={};s[o.id]=null==n?(r=ot(D(t=o.shape),"float32"),Lt.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var a=e[r],o=[];if(a.outputs.forEach((function(e){var n=t[e.id];null!=n?o.push(n):o.push(null)})),null==a.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+a.kernelName+".");var i=a.gradient(o),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n((function(){return i[e]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var o=a.inputs[e];if(!_(r.shape,o.shape))throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+o.shape+"'");if(null==t[o.id])t[o.id]=r;else{var s=t[o.id];t[o.id]=s.add(r),s.dispose()}};for(var u in a.inputs)s(u)},a=e.length-1;a>=0;a--)r(a)}(s,i,(function(t){return a.tidy(t)}));var u=e.map((function(t){return s[t.id]}));return 0===a.state.gradientDepth&&(a.state.activeTape.forEach((function(t){for(var e=0,n=t.saved;e<n.length;e++)n[e].dispose()})),a.state.activeTape=null),{value:o,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return T(tt(t),(function(){return"The f passed in customGrad(f) must be a function."})),function(){for(var n,r=[],a=0;a<arguments.length;a++)r[a]=arguments[a];T(r.every((function(t){return t instanceof wt})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var o={};return r.forEach((function(t,e){o[e]=t})),e.runKernelFunc((function(e,a){return T((n=t.apply(void 0,r.concat([a]))).value instanceof wt,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),T(tt(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),o,(function(t,e){var a=n.gradFunc(t,e),o=Array.isArray(a)?a:[a];T(o.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),T(o.every((function(t){return t instanceof wt})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var i={};return o.forEach((function(t,e){i[e]=function(){return t}})),i}))}},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},t.prototype.time=function(t){return u(this,void 0,void 0,(function(){var e,n;return c(this,(function(r){switch(r.label){case 0:return e=st(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=st()-e,[2,n]}}))}))},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Bt,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}(),Lt=function(){var e=function(){if(null==Ft){var e=void 0;if("undefined"!=typeof window)e=window;else if(void 0!==t)e=t;else if(void 0!==r)e=r;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Ft=e}return Ft}();if(null==e._tfengine){var n=new l(e);e._tfengine=new Pt(n)}return function(t){d=t}(e._tfengine.ENV),yt=function(){return e._tfengine},e._tfengine}();function Vt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Wt=f();Wt.registerFlag("DEBUG",(function(){return!1}),(function(t){t&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Wt.registerFlag("IS_BROWSER",(function(){return Vt()})),Wt.registerFlag("IS_NODE",(function(){return void 0!==r&&void 0!==r.versions&&void 0!==r.versions.node})),Wt.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Wt.registerFlag("PROD",(function(){return!1})),Wt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Wt.getBool("DEBUG")})),Wt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Wt.registerFlag("IS_TEST",(function(){return!1}));var zt,Ut,jt,Gt={},Ht={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function qt(t,e){Gt[t]=e}function Kt(t){t in Gt||(Gt[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=function(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(t);return e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Gt[t]}),!1),1===t?e.getContext("webgl",Ht)||e.getContext("experimental-webgl",Ht):e.getContext("webgl2",Ht)}(t));var e=Gt[t];return e.isContextLost()?(delete Gt[t],Kt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Gt[t])}function Xt(t,e){return[e,t]}function Yt(t){var e=D(t);return B(Math.ceil(e/4))}function $t(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Qt(t,e){var n,r,a,o,i,s,u,c,l,p=t;return 2===f().getNumber("WEBGL_VERSION")?(n=p.R32F,r=p.R16F,a=p.RGBA16F,o=p.RGBA32F,i=p.RED,s=4,u=1,c=p.HALF_FLOAT,l=p.FLOAT):(n=t.RGBA,r=t.RGBA,a=t.RGBA,o=p.RGBA,i=t.RGBA,s=4,u=4,c=null!=e?e.HALF_FLOAT_OES:null,l=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c,textureTypeFloat:l}}function Jt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+te(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(zt||(zt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Ut||(Ut={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(jt||(jt={}));function Zt(t){return!!(f().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||5.96e-8<Math.abs(t)&&Math.abs(t)<65504)}function te(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function ee(t,e,n){return Se(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function ne(t,e,n){var r=Se(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function re(t,e,n){var r=Se(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=ie.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],a=t.split("\n"),o=a.length.toString().length+2,i=a.map((function(t,e){return P((e+1).toString(),o)+t})),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var c=i.slice(0,r-1),l=i.slice(r-1,r),p=i.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+P(l[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var ae,oe,ie=/ERROR: [0-9]+:([0-9]+):/g;function se(t,e){return Se(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function ue(t,e,n){if(Jt(t,e,(function(){return t.linkProgram(n)})),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function ce(t,e,n){if(Jt(t,e,(function(){return t.validateProgram(n)})),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function le(t,e,n){var r=Se(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function pe(t,e,n){var r=Se(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function fe(t,e){return Se(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function de(t,e){var n=f().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function he(t,e){return Se(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function me(t,e,n,r,a,o,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,a)})),Jt(t,e,(function(){return t.vertexAttribPointer(u,o,t.FLOAT,!1,i,s)})),Jt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function ve(t,e,n,r){Ne(t,r),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function ge(t,e,n,r){return Se(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function ye(t,e,n){return t.getUniformLocation(e,n)}function xe(t,e,n,r,a,o){Jt(t,e,(function(){return ve(t,e,r,o)})),Jt(t,e,(function(){return t.uniform1i(a,o)}))}function be(t,e,n,r){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function we(t,e,n){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ee(t,e))}function Ee(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function Se(t,e,n,r){var a=Jt(t,e,(function(){return n()}));if(null==a)throw new Error(r);return a}function Ne(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Ie(t,e){return void 0===e&&(e=2),D(t.slice(0,t.length-e))}function Re(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Te(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ie(t)].concat(Re(t))),e}function ke(t,e){var n;void 0===e&&(e=!1);var r=f().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map((function(e,n){return n>=t.length-2?I(t[n]):t[n]}))).length&&(t=[2,t[0]])),2!==t.length){var a=z(t);t=a.newShape}var o=D(t);if(t.length<=1&&o<=r)return[1,o];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var i=Ie(t),s=2,u=2;return t.length&&(s=(n=Re(t))[0],u=n[1]),B(o=i*(s/2)*(u/2)).map((function(t){return 2*t}))}return B(o)}function Ae(t){return t%2==0}function Oe(t,e){if(_(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(Ae(n)&&Ae(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Ae(t[0])&&Ae(e[0])}function De(t){if(null==ae){var e=Kt(t);ae=e.getParameter(e.MAX_TEXTURE_SIZE)}return ae}function _e(t){if(null==oe){var e=Kt(t);oe=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,oe)}function Fe(t){if(0===t)return 0;var e=Kt(t);return Me(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Me(e,"EXT_disjoint_timer_query")?1:0}function Me(t,e){return null!=t.getExtension(e)}function Be(t){try{if(null!=Kt(t))return!0}catch(t){return!1}return!1}function Pe(t){if(0===t)return!1;var e=Kt(t);if(1===t){if(!Me(e,"OES_texture_float"))return!1}else if(!Me(e,"EXT_color_buffer_float"))return!1;return Ve(e)}function Le(t){if(0===t)return!1;var e=Kt(t);if(1!==t){if(Me(e,"EXT_color_buffer_float"))return Ve(e);if(Me(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Qt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var a=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,a),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(a),o}(e,n)}return!1}return!!Me(e,"OES_texture_float")&&!!Me(e,"WEBGL_color_buffer_float")&&Ve(e)}function Ve(t){var e=Qt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),a}function We(t){return 2===t&&null!=Kt(t).fenceSync}var ze=Object.freeze({callAndCheck:Jt,canBeRepresented:Zt,getWebGLErrorMessage:te,getExtensionOrThrow:ee,createVertexShader:ne,createFragmentShader:re,createProgram:se,linkProgram:ue,validateProgram:ce,createStaticVertexBuffer:le,createStaticIndexBuffer:pe,getNumChannels:function(){return 2===f().getNumber("WEBGL_VERSION")?1:4},createTexture:fe,validateTextureSize:de,createFramebuffer:he,bindVertexBufferToProgramAttribute:me,bindTextureUnit:ve,unbindTextureUnit:function(t,e,n){Ne(t,n),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:ge,getProgramUniformLocation:ye,bindTextureToProgramUniformSampler:xe,bindCanvasToFramebuffer:function(t,e){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Jt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Jt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:be,unbindColorTextureFromFramebuffer:we,validateFramebuffer:Ce,getFramebufferErrorMessage:Ee,getBatchDim:Ie,getRowsCols:Re,getShapeAs3D:Te,getTextureShapeFromLogicalShape:ke,isReshapeFree:Oe,getWebGLMaxTextureSize:De,resetMaxTextureSize:function(){ae=null},resetMaxTexturesInShader:function(){oe=null},getMaxTexturesInShader:_e,getWebGLDisjointQueryTimerVersion:Fe,hasExtension:Me,isWebGLVersionEnabled:Be,isCapableOfRenderingToFloatTexture:Pe,isDownloadFloatTextureEnabled:Le,isWebGLFenceEnabled:We}),Ue=f();function je(){f().set("PROD",!0)}function Ge(){f().set("DEBUG",!0)}function He(){f().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function qe(t){f().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ke(){Lt.disposeVariables()}function Xe(){return Lt}function Ye(){return Lt.memory()}function $e(t){return Lt.profile(t)}function Qe(t,e){return Lt.tidy(t,e)}function Je(t){_t(t).forEach((function(t){return t.dispose()}))}function Ze(t){return Lt.keep(t)}function tn(t){return Lt.time(t)}function en(t){return Lt.setBackend(t)}function nn(){return Lt.ready()}function rn(){return Lt.backendName}function an(t){Lt.removeBackend(t)}function on(t){return Lt.findBackend(t)}function sn(t){return Lt.findBackendFactory(t)}function un(t,e,n){return void 0===n&&(n=1),Lt.registerBackend(t,e,n)}function cn(){return Lt.backend}function ln(t,e){f().setPlatform(t,e)}function pn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];f().getBool("IS_TEST")||console.warn.apply(console,t)}function fn(t,e){var n=t;if(K(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||K(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&f().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||K(e)){T(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),T(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var a=n.slice(1),o=0;o<e.length;++o)t(e[o],a,r.concat(o))}else T(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}))}(t,r,[]),r}function dn(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function hn(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof wt)return dn(r,t.dtype,e,n),t;var a=Z(t);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),dn(r,a,e,n),null==t||!K(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var o=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+o+"'")}var i=fn(t,a);K(t)||Array.isArray(t)||(t=[t]);var s="string"!==a?rt(t,a,f().getBool("DEBUG")):O(t,[],!0);return Lt.makeTensor(s,i,a)}function mn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map((function(t,r){return hn(t,e+"["+r+"]",n)}),r)}function vn(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function gn(t,e,n){for(var r=t.length+e.length,a=[],o=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?a.push(t[o++]):a.push(e[i++]);return a}function yn(t,e){for(var n=[],r=t.length,a=0;a<r;a++)-1===e.indexOf(a)&&n.push(t[a]);return[n,e.map((function(e){return t[e]}))]}function xn(t,e){return gn(t,e.map((function(t){return 1})),e)}function bn(t,e,n){T(vn(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function wn(t,e){if(vn(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach((function(t){return n.push(t)})),n}function Cn(t){return t.map((function(t,e){return[e,t]})).sort((function(t,e){return t[1]-e[1]})).map((function(t){return t[0]}))}function En(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function Sn(t,e){var n=t[0].length;t.forEach((function(t,e){T(t.length===n,(function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"}))})),T(e>=0&&e<n,(function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."}));var r=t[0];t.forEach((function(t,a){for(var o=0;o<n;o++)T(o===e||t[o]===r[o],(function(){return"Error in concat"+n+"D: Shape of tensors["+a+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+a+"."}))}))}function Nn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function In(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var a=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Lt.startScope(n);try{var a=r.apply(void 0,t);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Lt.endScope(a),a}catch(t){throw Lt.endScope(null),t}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}Ue.registerFlag("HAS_WEBGL",(function(){return Ue.getNumber("WEBGL_VERSION")>0})),Ue.registerFlag("WEBGL_VERSION",(function(){return Be(2)?2:Be(1)?1:0})),Ue.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Ue.get("WEBGL_VERSION")})),Ue.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Ue.registerFlag("WEBGL_PACK",(function(){return Ue.getBool("HAS_WEBGL")})),Ue.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_CLIP",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_REDUCE",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_CONV_IM2COL",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return De(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return _e(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=Ue.getNumber("WEBGL_VERSION");return 0===t?0:Fe(t)})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Pe(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Ue.getBool("WEBGL_FORCE_F16_TEXTURES")&&Ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Le(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return We(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),bt=qe;var Rn=In({complex_:function(t,e){var n=hn(t,"real","complex"),r=hn(e,"imag","complex");return k(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Lt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),Tn=In({real_:function(t){var e=hn(t,"input","real");return Lt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),kn=In({imag_:function(t){var e=hn(t,"input","imag");return Lt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function An(t,e,n){return On(t,e,fn(t,n),n)}function On(t,e,n,r){if(null==r&&(r=Z(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!K(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){ut(e);var a=D(e),o=D(n);T(a===o,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+a+" values but has "+o}));for(var i=0;i<n.length;++i){var s=n[i],u=i!==n.length-1||s!==D(e.slice(i));T(n[i]===e[i]||!u,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return K(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?rt(t,r,f().getBool("DEBUG")):O(t,[],!0),Lt.makeTensor(t,e,r)}function Dn(t,e){if((K(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&K(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return On(t,[],[],e)}function _n(t,e){A(t);var n=fn(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return On(t,null,n,e)}function Fn(t,e,n){if(A(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=fn(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return On(t,e,r,n)}function Mn(t,e,n){if(A(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=fn(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return On(t,e,r,n)}function Bn(t,e,n){if(A(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=fn(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return On(t,e,r,n)}function Pn(t,e,n){if(A(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=fn(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return On(t,e,r,n)}function Ln(t,e,n){if(A(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=fn(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return On(t,e=e||r,r,n)}function Vn(t,e,n,r){return void 0===e&&(e=!0),Lt.makeVariable(t,e,n,r)}function Wn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Wn(t,"float32"),r=zn(t,"float32");return Rn(n,r)}var a=ot(D(t),e);return Lt.makeTensor(a,t,e)}function zn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=zn(t,"float32"),r=zn(t,"float32");return Rn(n,r)}var a=it(D(t),e);return Lt.makeTensor(a,t,e)}function Un(t,e,n){return Lt.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function jn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Lt.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})}function Gn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return zn([0],r);var a=it(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),a[0]=t;for(var o=1;o<a.length;o++)a[o]=a[o-1]+n;return _n(a,r)}var Hn=In({onesLike_:function(t){var e=hn(t,"x","onesLike");if("complex64"===e.dtype){var n=Hn(Tn(e)),r=qn(kn(e));return Rn(n,r)}return Lt.runKernelFunc((function(t){return t.onesLike(e)}),{$x:e},(function(t,e){return{$x:function(){return qn(t)}}}))}}),qn=In({zerosLike_:function(t){var e=hn(t,"x","zerosLike");return Lt.runKernelFunc((function(t){return t.zerosLike(e)}),{$x:e},(function(t,e){return{$x:function(){return qn(t)}}}))}}),Kn=In({concat_:function(t,e){void 0===e&&(e=0),T(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=mn(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")})),e=W(e,n[0].shape)[0];var r=Nn(n.map((function(t){return t.shape})),e);if(0===D(r))return An([],r);if(1===(n=n.filter((function(t){return t.size>0}))).length)return n[0];var a=n.map((function(t){return t.shape}));Sn(a,e);var o=n,i={axis:e};return Lt.runKernelFunc((function(t){return t.concat(n,e)}),o,(function(t){var n=a.map((function(t){return t[e]}));return Jn(t,n,e).map((function(t){return function(){return t}}))}),"Concat",i)}}),Xn=In({concat1d_:function(t){return Kn(t,0)}}),Yn=In({concat2d_:function(t,e){return Kn(t,e)}}),$n=In({concat3d_:function(t,e){return Kn(t,e)}}),Qn=In({concat4d_:function(t,e){return Kn(t,e)}}),Jn=In({split_:function(t,e,n){void 0===n&&(n=0);var r,a=hn(t,"x","split");return n=W(n,a.shape)[0],"number"==typeof e?(T(a.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(a.shape[n]/e)):(T(a.shape[n]===e.reduce((function(t,e){return t+e})),(function(){return"The sum of sizes must match the size of the axis dimension."})),r=e),Lt.runKernelFunc((function(t){return t.split(a,r,n)}),{$x:a},(function(t){return{$x:function(){return Kn(t,n)}}}))}});function Zn(t,e){return t(e={exports:{}},e.exports),e.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t||"undefined"!=typeof self&&self;var tr=Zn((function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function a(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function o(t,e){var n=new r(t),o=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,o&&("object"==typeof o&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.alea=o}(0,t)})),er=Zn((function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function a(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function o(t,e){var n=new r(t),o=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,o&&("object"==typeof o&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.xor128=o}(0,t)})),nr=Zn((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function a(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function o(t,e){var n=new r(t),o=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,o&&("object"==typeof o&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.xorwow=o}(0,t)})),rr=Zn((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,a=e.i;return t=r[a],n=(t^=t>>>7)^t<<24,n^=(t=r[a+1&7])^t>>>10,n^=(t=r[a+3&7])^t>>>3,n^=(t=r[a+4&7])^t<<7,t=r[a+7&7],n^=(t^=t<<13)^t<<9,r[a]=n,e.i=a+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function a(t,e){return e.x=t.x.slice(),e.i=t.i,e}function o(t,e){null==t&&(t=+new Date);var n=new r(t),o=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,o&&(o.x&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.xorshift7=o}(0,t)})),ar=Zn((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,a=e.X,o=e.i;return e.w=r=r+1640531527|0,n=a[o+34&127],t=a[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=a[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,a,o,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),a=0,o=-32;o<u;++o)e&&(r^=e.charCodeAt((o+32)%e.length)),0===o&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(i=i+1640531527|0,a=0==(n=s[127&o]^=r+i)?a+1:0);for(a>=128&&(s[127&(e&&e.length||0)]=-1),a=127,o=512;o>0;--o)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;t.w=i,t.X=s,t.i=a}(e,t)}function a(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function o(t,e){null==t&&(t=+new Date);var n=new r(t),o=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,o&&(o.X&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.xor4096=o}(0,t)})),or=Zn((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,a=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^a,e.a=a-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function a(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function o(t,e){var n=new r(t),o=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,o&&("object"==typeof o&&a(o,n),i.state=function(){return a(n,{})}),i}e&&e.exports?e.exports=o:this.tychei=o}(0,t)})),ir=Zn((function(t){!function(e,r){var a,o=this,i=256,s="random",u=r.pow(i,6),c=r.pow(2,52),l=2*c,p=255;function f(t,n,p){var f=[],g=m(function t(e,n){var r,a=[],o=typeof e;if(n&&"object"==o)for(r in e)try{a.push(t(e[r],n-1))}catch(t){}return a.length?a:"string"==o?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,v(e)]:null==t?function(){try{var t;return a&&(t=a.randomBytes)?t=t(i):(t=new Uint8Array(i),(o.crypto||o.msCrypto).getRandomValues(t)),v(t)}catch(t){var n=o.navigator,r=n&&n.plugins;return[+new Date,o,r,o.screen,v(e)]}}():t,3),f),y=new d(f),x=function(){for(var t=y.g(6),e=u,n=0;t<c;)t=(t+n)*i,e*=i,n=y.g(1);for(;t>=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|y.g(4)},x.quick=function(){return y.g(4)/4294967296},x.double=x,m(v(y.S),e),(n.pass||p||function(t,e,n,a){return a&&(a.S&&h(a,y),t.state=function(){return h(y,{})}),n?(r[s]=t,e):t})(x,g,"global"in n?n.global:this==r,n.state)}function d(t){var e,n=t.length,r=this,a=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);a<i;)s[a]=a++;for(a=0;a<i;a++)s[a]=s[o=p&o+t[a%n]+(e=s[a])],s[o]=e;(r.g=function(t){for(var e,n=0,a=r.i,o=r.j,s=r.S;t--;)e=s[a=p&a+1],n=n*i+s[p&(s[a]=s[o=p&o+e])+(s[o]=e)];return r.i=a,r.j=o,n})(i)}function h(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function m(t,e){for(var n,r=t+"",a=0;a<r.length;)e[p&a]=p&(n^=19*e[p&a])+r.charCodeAt(a++);return v(e)}function v(t){return String.fromCharCode.apply(0,t)}if(r.seedrandom=f,m(r.random(),e),t.exports){t.exports=f;try{a=n(10)}catch(t){}}}([],Math)}));ir.alea=tr,ir.xor128=er,ir.xorwow=nr,ir.xorshift7=rr,ir.xor4096=ar,ir.tychei=or;var sr=ir.alea,ur=function(){function t(t,e,n,r,a){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var o=a||Math.random();this.random=sr(o.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var a=void 0,o=void 0,i=void 0;do{i=(a=2*this.random()-1)*a+(o=2*this.random()-1)*o}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),cr=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var a=r||Math.random();this.randu=sr(a.toString()),this.randn=new ur(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,a,o;;){do{r=this.randn.nextValue(),o=1+this.c*r}while(o<=0);if(o*=o*o,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-o+Math.log(o)),(a=this.randu())<e||Math.log(a)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),lr=function(){function t(t,e,n,r){var a=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==a.dtype||"float32"===a.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=sr(r)}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}();function pr(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",ut(t),new gt(t,e,n)}function fr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var dr=In({batchToSpaceND_:function(t,e,n){var r=hn(t,"x","batchToSpaceND"),a=e.reduce((function(t,e){return t*e}));return T(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),T(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),T(r.shape[0]%a==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+a})),Lt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),hr=In({broadcastTo_:function(t,e){var n=hn(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.length<n.rank)throw new Error("broadcastTo(): shape.length="+e.length+" < input.rank="+n.rank+".");if(e.length>n.rank){for(var a=n.shape.slice();a.length<e.length;)a.unshift(1);n=n.reshape(a)}for(var o=Array.from(e),i=e.length-1;i>=0;i--)if(n.shape[i]===e[i])o[i]=1;else if(1!==n.shape[i])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var s=o.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));return 0===s.length?n.clone():Lt.runKernelFunc((function(t){return t.tile(n,o)}),{input:n},(function(t){return{input:function(){return t.sum(s,!0)}}}))}}),mr=In({cast_:function(t,e){var n=hn(t,"x","cast");if(!H(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var r={dtype:e};return Lt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),vr=In({clone_:function(t){var e=hn(t,"x","clone",null);return Lt.runKernelFunc((function(){return Lt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{$x:e},(function(t){return{$x:function(){return t.toFloat()}}}))}}),gr=In({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=hn(t,"x","cumsum"),o=wn([e|=0],a.rank),i=a;null!=o&&(i=a.transpose(o));var s=En(1,a.rank)[0],u=Lt.runKernelFunc((function(t){return t.cumsum(i,s,n,r)}),{permutedX:i},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=o&&(u=u.transpose(o)),u}}),yr=In({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=hn(t,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return T(a*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape})),T(o*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape})),T(i%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape})),Lt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),xr=In({expandDims_:function(t,e){void 0===e&&(e=0);var n=hn(t,"x","expandDims",null);T(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(T(-(n.rank+1)<=e,(function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"})),e=n.rank+e+1),r.splice(e,0,1),Dr(n,r)}}),br=In({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var a=pr([t,e],r),o=t<=e?t:e,i=0;i<o;++i)a.set(1,i,i);var s=a.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return Br(xr(s,0),[n[0],1,1]);if(2===n.length)return Br(xr(xr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return Br(xr(xr(xr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),wr=In({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var a=hn(t,"logits","multinomial"),o=a.size,i=a.rank;if(o<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?a.as2D(1,-1):a,u=Lt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===i?u.as1D():u}}),Cr=In({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var a=hn(t,"indices","oneHot","int32"),o=a.shape.concat([e]);return a=a.flatten(),Lt.runKernelFunc((function(t){return t.oneHot(a,e,n,r)}),{$indices:a},(function(t){return{$indices:function(){return zn(a.shape,"float32")}}})).reshape(o)}}),Er=In({pad_:function(t,e,n){void 0===n&&(n=0);var r=hn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a={paddings:e,constantValue:n};return Lt.runKernelFunc((function(t){return t.pad(r,e,n)}),{x:r},(function(t){var n=e.map((function(t){return t[0]}));return{x:function(){return t.slice(n,r.shape)}}}),"PadV2",a)}}),Sr=In({pad1d_:function(t,e,n){return void 0===n&&(n=0),T(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),Er(t,[e],n)}}),Nr=In({pad2d_:function(t,e,n){return void 0===n&&(n=0),T(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Er(t,e,n)}}),Ir=In({pad3d_:function(t,e,n){return void 0===n&&(n=0),T(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Er(t,e,n)}}),Rr=In({pad4d_:function(t,e,n){return void 0===n&&(n=0),T(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Er(t,e,n)}}),Tr=In({rand_:function(t,e,n){var r=D(t),a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);a=new Uint8Array(r)}for(var o=0;o<r;o++)a[o]=e();return Lt.makeTensor(a,t,n)}}),kr=In({randomNormal_:function(t,e,n,r,a){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new ur(e,n,r,!1,a),i=pr(t,r),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),Ar=In({randomGamma_:function(t,e,n,r,a){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var o=new cr(e,n,r,a),i=pr(t,r),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),Or=In({randomUniform_:function(t,e,n,r,a){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var o=pr(t,r),i=new lr(e,n,null,a),s=0;s<o.values.length;s++)o.values[s]=i.nextValue();return o.toTensor()}}),Dr=In({reshape_:function(t,e){var n=hn(t,"x","reshape",null);e=V(e,n.size),T(n.size===D(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Lt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),_r=In({spaceToBatchND_:function(t,e,n){var r=hn(t,"x","spaceToBatchND");return T(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),T(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),T(r.shape.reduce((function(t,r,a){return a>0&&a<=e.length?t&&(r+n[a-1][0]+n[a-1][1])%e[a-1]==0:t}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()})),Lt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),Fr=In({squeeze_:function(t,e){var n=hn(t,"x","squeeze");return Dr(n,z(n.shape,e).newShape)}}),Mr=In({stack_:function(t,e){void 0===e&&(e=0);var n=mn(t,"tensors","stack");if(T(n.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),1===n.length)return n[0].expandDims(e);var r=n[0].rank,a=n[0].shape,o=n[0].dtype;T(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){k(a,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){T(o===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var i=n.map((function(t){return t.expandDims(e)}));return Kn(i,e)}}),Br=In({tile_:function(t,e){var n=hn(t,"x","tile",null);T(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],a={reps:e};return Lt.runKernelFunc((function(t,r){var a=t.tile(n,e);return r([n]),a}),{x:n},(function(t,n){var r=n[0];return{x:function(){var n=qn(r);if(1===r.rank)for(var a=0;a<e[0];++a)n=n.add(t.slice([a*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(a=0;a<e[0];++a)for(var o=0;o<e[1];++o)n=n.add(t.slice([a*r.shape[0],o*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(a=0;a<e[0];++a)for(o=0;o<e[1];++o)for(var i=0;i<e[2];++i)n=n.add(t.slice([a*r.shape[0],o*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(a=0;a<e[0];++a)for(o=0;o<e[1];++o)for(i=0;i<e[2];++i)for(var s=0;s<e[3];++s)n=n.add(t.slice([a*r.shape[0],o*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),"Tile",a,r)}}),Pr=In({truncatedNormal_:function(t,e,n,r,a){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new ur(e,n,r,!0,a),i=pr(t,r),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),Lr=In({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=hn(t,"x","unstack");T(e>=-n.shape.length&&e<n.shape.length,(function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"})),e<0&&(e+=n.shape.length);var r={axis:e};return Lt.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return Mr(t,e)}}}),"Unpack",r)}}),Vr=function(t,e){return u(this,void 0,void 0,(function(){var n,r,a,o,i,s,u,l,p,f;return c(this,(function(c){switch(c.label){case 0:return n=hn(t,"x","setdiff1d"),r=hn(e,"y","setdiff1d"),T(n.dtype===r.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."})),T(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),T(1===r.rank,(function(){return"y should be 1D tensor, but got y ("+r.shape+")."})),[4,n.data()];case 1:return a=c.sent(),[4,r.data()];case 2:for(o=c.sent(),i=new Set(o),s=0,p=0;p<a.length;p++)i.has(a[p])||s++;for(u=new gt([s],n.dtype),l=new gt([s],"int32"),p=0,f=0;p<a.length;p++)i.has(a[p])||(u.values[f]=a[p],l.values[f]=p,f++);return[2,[u.toTensor(),l.toTensor()]]}}))}))};function Wr(t,e,n,r){void 0===r&&(r=!0);var a=[];if(r)(a=a.concat(e.slice(0))).push(t[0]/n),a=a.concat(t.slice(1));else{a=a.concat(t[0]);for(var o=e.length,i=0;i<o;++i)a=a.concat([t[i+1]/e[i],e[i]]);a=a.concat(t.slice(o+1))}return a}function zr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var a=e+1;a<t;++a)a<=2*e?(r.push(a),r.push(a-(e+1))):r.push(a)}else{var o=[],i=[];for(a=1;a<t;++a)a>=2*e+1||a%2==1?i.push(a):o.push(a);r.push.apply(r,o),r.push(0),r.push.apply(r,i)}return r}function Ur(t,e,n,r){void 0===r&&(r=!0);var a=[];r?a.push(t[0]/n):a.push(t[0]*n);for(var o=1;o<t.length;++o)o<=e.length?r?a.push(e[o-1]*t[o]):a.push(t[o]/e[o-1]):a.push(t[o]);return a}function jr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function Gr(t,e,n){for(var r=t.slice(0,1),a=0;a<n;++a)r.push(t[a+1]-e[a][0]-e[a][1]);return r}function Hr(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],a=1,o=0;o<n.length-1;++o)a*=n[o];var i=t.shape,s=n.slice();s.pop();var u=1;for(o=r;o<t.rank;++o)u*=i[o],s.push(i[o]);var c=nt(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,a,u,c]}function qr(t){return t<=30?t:et(t,Math.floor(Math.sqrt(t)))}function Kr(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,a=n.length,o=1,i=r;i<a;++i)o*=n[i];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:o,strides:nt(n.slice(0,r)).concat([1]),outputSize:D(n)}}function Xr(t,e,n){T(t.rank===e.length,(function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."})),T(t.rank===n.length,(function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."}));for(var r=function(r){T(e[r]+n[r]<=t.shape[r],(function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"}))},a=0;a<t.rank;++a)r(a)}function Yr(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function $r(t,e,n){for(var r=[],a=0;a<t.length;a++)r[a]=Math.ceil((e[a]-t[a])/n[a]);return r}function Qr(t,e,n,r,a){var o=e[a],i=n[a]||1;(t&1<<a||null==o)&&(o=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[a];return o<0&&(o+=s),N(0,o,s-1)}function Jr(t,e,n,r,a){var o=e[a],i=n[a]||1;(t&1<<a||null==o)&&(o=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[a];return o<0&&(o+=s),i>0?N(0,o,s):N(-1,o,s-1)}function Zr(t,e,n){for(var r=n.length,a=0;a<n.length;a++)if(n[a]>1){r=a;break}for(a=r+1;a<n.length;a++)if(e[a]>0||n[a]!==t[a])return!1;return!0}function ta(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}var ea=Object.freeze({assertParamsValid:Xr,maskToAxes:Yr,computeOutShape:$r,startForAxis:Qr,stopForAxis:Jr,isSliceContinous:Zr,computeFlatOffset:ta});function na(t){return T(tt(t),(function(){return"The f passed in grad(f) must be a function"})),function(e,n){var r=hn(e,"x","tf.grad",null),a=null!=n?hn(n,"dy","tf.grad"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t(r)}),[r],a),n=e.value,o=e.grads;return null!=a&&k(n.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ua(o),o[0]}))}}function ra(t){return T(tt(t),(function(){return"The f passed in grads(f) must be a function"})),function(e,n){T(Array.isArray(e),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=mn(e,"args","tf.grads",null),a=null!=n?hn(n,"dy","tf.grads"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t.apply(void 0,r)}),r,a),n=e.value,o=e.grads;return null!=a&&k(n.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ua(o),o}))}}function aa(t){return T(tt(t),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(e,n){T(e instanceof wt,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),T(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=Lt.gradients((function(){return t(e)}),[e],n),a=r.grads,o=r.value;return ua(a),{grad:a[0],value:o}}}function oa(t){return T(tt(t),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(e,n){T(Array.isArray(e)&&e.every((function(t){return t instanceof wt})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),T(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=Lt.gradients((function(){return t.apply(void 0,e)}),e,n);return null!=n&&k(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ua(r.grads),r}}function ia(t,e){T(tt(t),(function(){return"The f passed in variableGrads(f) must be a function"})),T(null==e||Array.isArray(e)&&e.every((function(t){return t instanceof Rt})),(function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}));var n=null!=e;if(!n)for(var r in e=[],Lt.registeredVariables)e.push(Lt.registeredVariables[r]);var a=n?e.filter((function(t){return!t.trainable})):null,o=e.length;T((e=e.filter((function(t){return t.trainable}))).length>0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+o+" variables is trainable."}));var i=Lt.gradients(t,e,null,!0),s=i.value,u=i.grads;T(u.some((function(t){return null!=t})),(function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."})),T(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var c={};return e.forEach((function(t,e){null!=u[e]&&(c[t.name]=u[e])})),null!=a&&a.forEach((function(t){return c[t.name]=null})),{value:s,grads:c}}function sa(t){return Lt.customGrad(t)}function ua(t){if(t.filter((function(t){return null==t})).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var ca=In({softmax_:function(t,e){void 0===e&&(e=-1);var n=hn(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return sa((function(t,n){var r=t.logSumExp([e],!0),a=t.toFloat().sub(r).exp();return n([a]),{value:a,gradFunc:function(t,n){var r=n[0],a=t.mul(r);return a.sub(a.sum([e],!0).mul(r))}}}))(n)}}),la=In({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=hn(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return sa((function(t,n){var r=t.max(e,!0),a=t.sub(r),o=a.toFloat().sub(a.exp().sum(e,!0).log());return n([o]),{value:o,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),pa=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),fa=function(){function t(){}return t.prototype.time=function(t){return da("time")},t.prototype.read=function(t){return da("read")},t.prototype.readSync=function(t){return da("readSync")},t.prototype.numDataIds=function(){return da("numDataIds")},t.prototype.disposeData=function(t){return da("disposeData")},t.prototype.write=function(t,e,n){return da("write")},t.prototype.move=function(t,e,n,r){return da("move")},t.prototype.memory=function(){return da("memory")},t.prototype.floatPrecision=function(){return da("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return da("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,da("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return da("slice")},t.prototype.stridedSlice=function(t,e,n,r){return da("stridedSlice")},t.prototype.unstack=function(t,e){return da("unstack")},t.prototype.reverse=function(t,e){return da("reverse")},t.prototype.concat=function(t,e){return da("concat")},t.prototype.neg=function(t){return da("neg")},t.prototype.add=function(t,e){return da("add")},t.prototype.addN=function(t){return da("addN")},t.prototype.subtract=function(t,e){return da("subtract")},t.prototype.multiply=function(t,e){return da("multiply")},t.prototype.realDivide=function(t,e){return da("realDivide")},t.prototype.floorDiv=function(t,e){return da("floorDiv")},t.prototype.sum=function(t,e){return da("sum")},t.prototype.prod=function(t,e){return da("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return da("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return da("argMin")},t.prototype.argMax=function(t,e){return da("argMax")},t.prototype.equal=function(t,e){return da("equal")},t.prototype.notEqual=function(t,e){return da("notEqual")},t.prototype.less=function(t,e){return da("less")},t.prototype.lessEqual=function(t,e){return da("lessEqual")},t.prototype.greater=function(t,e){return da("greater")},t.prototype.greaterEqual=function(t,e){return da("greaterEqual")},t.prototype.logicalNot=function(t){return da("logicalNot")},t.prototype.logicalAnd=function(t,e){return da("logicalAnd")},t.prototype.logicalOr=function(t,e){return da("logicalOr")},t.prototype.where=function(t){return da("where")},t.prototype.select=function(t,e,n){return da("select")},t.prototype.topk=function(t,e,n){return da("topk")},t.prototype.min=function(t,e){return da("min")},t.prototype.minimum=function(t,e){return da("minimum")},t.prototype.mod=function(t,e){return da("mod")},t.prototype.max=function(t,e){return da("max")},t.prototype.maximum=function(t,e){return da("maximum")},t.prototype.all=function(t,e){return da("all")},t.prototype.any=function(t,e){return da("any")},t.prototype.squaredDifference=function(t,e){return da("squaredDifference")},t.prototype.ceil=function(t){return da("ceil")},t.prototype.floor=function(t){return da("floor")},t.prototype.round=function(t){return da("round")},t.prototype.sign=function(t){return da("sign")},t.prototype.isNaN=function(t){return da("isNaN")},t.prototype.isInf=function(t){return da("isInf")},t.prototype.isFinite=function(t){return da("isFinite")},t.prototype.pow=function(t,e){return da("pow")},t.prototype.exp=function(t){return da("exp")},t.prototype.expm1=function(t){return da("expm1")},t.prototype.log=function(t){return da("log")},t.prototype.log1p=function(t){return da("log1p")},t.prototype.sqrt=function(t){return da("sqrt")},t.prototype.rsqrt=function(t){return da("rsqrt")},t.prototype.square=function(t){return da("square")},t.prototype.reciprocal=function(t){return da("reciprocal")},t.prototype.relu=function(t){return da("relu")},t.prototype.relu6=function(t){return da("relu6")},t.prototype.prelu=function(t,e){return da("prelu")},t.prototype.elu=function(t){return da("elu")},t.prototype.eluDer=function(t,e){return da("eluDer")},t.prototype.selu=function(t){return da("selu")},t.prototype.int=function(t){return da("int")},t.prototype.clip=function(t,e,n){return da("clip")},t.prototype.abs=function(t){return da("abs")},t.prototype.complexAbs=function(t){return da("complexAbs")},t.prototype.sigmoid=function(t){return da("sigmoid")},t.prototype.softplus=function(t){return da("softplus")},t.prototype.sin=function(t){return da("sin")},t.prototype.cos=function(t){return da("cos")},t.prototype.tan=function(t){return da("tan")},t.prototype.asin=function(t){return da("asin")},t.prototype.acos=function(t){return da("acos")},t.prototype.atan=function(t){return da("atan")},t.prototype.atan2=function(t,e){return da("atan2")},t.prototype.sinh=function(t){return da("sinh")},t.prototype.cosh=function(t){return da("cosh")},t.prototype.tanh=function(t){return da("tanh")},t.prototype.asinh=function(t){return da("asinh")},t.prototype.acosh=function(t){return da("acosh")},t.prototype.atanh=function(t){return da("atanh")},t.prototype.erf=function(t){return da("erf")},t.prototype.step=function(t,e){return da("step")},t.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,da("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return da("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return da("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return da("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,da("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return da("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return da("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return da("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return da("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return da("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return da("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return da("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return da("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return da("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return da("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return da("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return da("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return da("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return da("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return da("reshape")},t.prototype.cast=function(t,e){return da("cast")},t.prototype.tile=function(t,e){return da("tile")},t.prototype.pad=function(t,e,n){return da("pad")},t.prototype.transpose=function(t,e){return da("transpose")},t.prototype.gather=function(t,e,n){return da("gather")},t.prototype.gatherND=function(t,e){return da("gatherND")},t.prototype.scatterND=function(t,e,n){return da("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return da("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return da("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return da("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return da("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return da("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return da("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,a,o){return da("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,a){return da("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,a,o,i){return da("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return da("multinomial")},t.prototype.oneHot=function(t,e,n,r){return da("oneHot")},t.prototype.cumsum=function(t,e,n,r){return da("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,a){return da("nonMaxSuppression")},t.prototype.fft=function(t){return da("fft")},t.prototype.ifft=function(t){return da("ifft")},t.prototype.complex=function(t,e){return da("complex")},t.prototype.real=function(t){return da("real")},t.prototype.imag=function(t){return da("imag")},t.prototype.cropAndResize=function(t,e,n,r,a,o){return da("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return da("depthToSpace")},t.prototype.split=function(t,e,n){return da("split")},t.prototype.sparseToDense=function(t,e,n,r){return da("sparseToDense")},t.prototype.diag=function(t){return da("diag")},t.prototype.fill=function(t,e,n){return da("fill")},t.prototype.onesLike=function(t){return da("onesLike")},t.prototype.zerosLike=function(t){return da("zerosLike")},t.prototype.linspace=function(t,e,n){return da("linspace")},t.prototype.dispose=function(){return da("dispose")},t}();function da(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function ha(t,e){for(var n=t.length,r=[],a=0;a<n;a++){var o=n-1-a,i=t[o]||1;(e[e.length-1-a]||1)>1&&1===i&&r.unshift(o)}return r}function ma(t,e){for(var n=[],r=0;r<e.length;r++){var a=t[t.length-r-1],o=e.length-r-1,i=e[o];(null==a||1===a&&i>1)&&n.unshift(o)}return n}function va(t,e){for(var n=[],r=Math.max(t.length,e.length),a=0;a<r;a++){var o=t[t.length-a-1];null==o&&(o=1);var i=e[e.length-a-1];if(null==i&&(i=1),1===o)n.unshift(i);else if(1===i)n.unshift(o);else{if(o!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(o)}}return n}function ga(t,e,n,r,a,o,i){void 0===i&&(i="channelsLast");var s,u=Ca(e),c=u[0],l=u[1];if("channelsLast"===i)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[c,l,t[1],t[1]]}return xa(t,s,n,r,a,o,!1,i)}function ya(t,e,n,r,a,o,i){void 0===i&&(i="NDHWC");var s,u,c=Ea(e),l=c[0],p=c[1],f=c[2];if("NDHWC"===i)u="channelsLast",s=[l,p,f,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,p,f,t[1],t[1]]}return ba(t,s,n,r,a,!1,u,o)}function xa(t,e,n,r,a,o,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],p=u[2],f=u[3];if("channelsLast"===s)c=t[0],l=t[1],p=t[2],f=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],f=t[1],l=t[2],p=t[3]}var d,h=e[0],m=e[1],v=e[3],g=Ca(n),y=g[0],x=g[1],b=Ca(r),w=b[0],C=b[1],E=Sa(h,w),S=Sa(m,C),N=function(t,e,n,r,a,o,i,s){var u,c,l;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var p=function(t,e,n,r,a){null==r&&(r=wa(t,e,n));var o=t[1],i=Na((t[0]-e+2*r)/n+1,a);T(F(i),(function(){return"The output # of rows ("+i+") must be an integer. Change the stride and/or zero pad parameters"}));var s=Na((o-e+2*r)/n+1,a);return T(F(s),(function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"})),[i,s]}([e,n],o,r,t,s);c=p[0],l=p[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/a);var f=Math.max(0,(c-1)*r+o-e),d=Math.max(0,(l-1)*a+i-n),h=Math.floor(f/2),m=f-h,v=Math.floor(d/2);u={top:h,bottom:m,left:v,right:d-v,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-o+1)/r),l=Math.ceil((n-i+1)/a)}return{padInfo:u,outHeight:c,outWidth:l}}(a,l,p,y,x,E,S,o),I=N.padInfo,R=N.outHeight,k=N.outWidth,A=i?v*f:v;return"channelsFirst"===s?d=[c,A,R,k]:"channelsLast"===s&&(d=[c,R,k,A]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:p,inChannels:f,outHeight:R,outWidth:k,outChannels:A,padInfo:I,strideHeight:y,strideWidth:x,filterHeight:h,filterWidth:m,effectiveFilterHeight:E,effectiveFilterWidth:S,dilationHeight:w,dilationWidth:C,inShape:t,outShape:d,filterShape:e}}function ba(t,e,n,r,a,o,i,s){void 0===o&&(o=!1),void 0===i&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],p=u[2],f=u[3],d=u[4];if("channelsLast"===i)c=t[0],l=t[1],p=t[2],f=t[3],d=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);c=t[0],d=t[1],l=t[2],p=t[3],f=t[4]}var h,m=e[0],v=e[1],g=e[2],y=e[4],x=Ea(n),b=x[0],w=x[1],C=x[2],E=Ea(r),S=E[0],N=E[1],I=E[2],R=Sa(m,S),k=Sa(v,N),A=Sa(g,I),O=function(t,e,n,r,a,o,i,s,u,c,l){var p,f,d,h;if("number"==typeof t){p={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var m=function(t,e,n,r,a,o){null==a&&(a=wa(t,e,r));var i=t[1],s=t[2],u=Na((t[0]-e+2*a)/r+1,o);T(F(u),(function(){return"The output # of depths ("+u+") must be an integer. Change the stride and/or zero pad parameters"}));var c=Na((i-e+2*a)/r+1,o);T(F(c),(function(){return"The output # of rows ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var l=Na((s-e+2*a)/r+1,o);return T(F(l),(function(){return"The output # of columns ("+l+") must be an integer. Change the stride and/or zero pad parameters"})),[u,c,l,1]}([e,n,r,1],s,0,a,t,l);f=m[0],d=m[1],h=m[2]}else if("same"===t){var v=((f=Math.ceil(e/a))-1)*a+s-e,g=((d=Math.ceil(n/o))-1)*o+u-n,y=((h=Math.ceil(r/i))-1)*i+c-r,x=Math.floor(v/2),b=v-x,w=Math.floor(g/2),C=g-w,E=Math.floor(y/2);p={top:w,bottom:C,left:E,right:y-E,front:x,back:b,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},f=Math.ceil((e-s+1)/a),d=Math.ceil((n-u+1)/o),h=Math.ceil((r-c+1)/i)}return{padInfo:p,outDepth:f,outHeight:d,outWidth:h}}(a,l,p,f,b,w,C,R,k,A,s),D=O.padInfo,_=O.outDepth,M=O.outHeight,B=O.outWidth,P=o?y*d:y;return"channelsFirst"===i?h=[c,P,_,M,B]:"channelsLast"===i&&(h=[c,_,M,B,P]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:p,inWidth:f,inChannels:d,outDepth:_,outHeight:M,outWidth:B,outChannels:P,padInfo:D,strideDepth:b,strideHeight:w,strideWidth:C,filterDepth:m,filterHeight:v,filterWidth:g,effectiveFilterDepth:R,effectiveFilterHeight:k,effectiveFilterWidth:A,dilationDepth:S,dilationHeight:N,dilationWidth:I,inShape:t,outShape:h,filterShape:e}}function wa(t,e,n,r){void 0===r&&(r=1);var a=Sa(e,r);return Math.floor((t[0]*(n-1)-n+a)/2)}function Ca(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function Ea(t){return"number"==typeof t?[t,t,t]:t}function Sa(t,e){return e<=1?t:t+(t-1)*(e-1)}function Na(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function Ia(t){var e=Ca(t),n=e[0],r=e[1],a=e[2];return 1===n&&1===r&&1===a}function Ra(t,e){return Ia(t)||Ia(e)}function Ta(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function ka(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=zn(t.shape),a=t.toFloat(),o=n.complex(a,r);return r.dispose(),a.dispose(),o}if(!q(t.dtype,e))return Lt.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var i=n.real(t);return o=i.cast(e),i.dispose(),o}if("int32"===e)return n.int(t);if("bool"===e){var s=Dn(0,t.dtype);return o=n.notEqual(t,s),s.dispose(),o}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Aa(t,e){return Lt.makeTensorFromDataId(t.dataId,e,t.dtype)}function Oa(t,e,n){var r=(e-t)/(n-1),a=it(n,"float32");a[0]=t;for(var o=1;o<a.length;o++)a[o]=a[o-1]+r;return _n(a,"float32")}var Da=Object.freeze({castTensor:ka,reshapeTensor:Aa,linspaceImpl:Oa,upcastType:kt,axesAreInnerMostDims:vn,combineLocations:gn,computeOutAndReduceShapes:yn,expandShapeToKeepDim:xn,assertAxesAreInnerMostDims:bn,getAxesPermutation:wn,getUndoAxesPermutation:Cn,getInnerMostAxes:En,getBroadcastDims:ha,getReductionAxes:ma,assertAndGetBroadcastShape:va,assertParamsConsistent:Sn,computeOutShape:Nn,computePool2DInfo:ga,computePool3DInfo:ya,computeConv2DInfo:xa,computeConv3DInfo:ba,computeDefaultPad:wa,tupleValuesAreOne:Ia,eitherStridesOrDilationsAreOne:Ra,convertConv2DDataFormat:Ta});function _a(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function Fa(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Ma(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Ba(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Pa(t,e,n){var r=function(t,e,n){return function(t,e,n){for(var r=0,a=t.length,o=0,i=!1;r<a;){var s=n(e,t[o=r+(a-r>>>1)]);s>0?r=o+1:(a=o,i=!s)}return i?r:-r-1}(t,e,n||La)}(t,e,n),a=r<0?-(r+1):r;t.splice(a,0,e)}function La(t,e){return t>e?1:t<e?-1:0}function Va(t,e,n,r,a){return za(t,e,n,r,a,0).selectedIndices}function Wa(t,e,n,r,a,o){var i=za(t,e,n,r,a,o,!0);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function za(t,e,n,r,a,o,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1);for(var u=Array.from(e).map((function(t,e){return{score:t,boxIndex:e,suppressBeginIndex:0}})).filter((function(t){return t.score>a})).sort(Ga),c=o>0?-.5/o:0,l=[],p=[];l.length<n&&u.length>0;){var f=u.pop(),d=f.score,h=f.boxIndex,m=f.suppressBeginIndex;if(d<a)break;for(var v=!1,g=l.length-1;g>=m;--g){var y=Ua(t,h,l[g]);if(y>=r){v=!0;break}if(f.score=f.score*ja(r,c,y),f.score<=a)break}f.suppressBeginIndex=l.length,v||(f.score===d?(l.push(h),p.push(f.score)):f.score>a&&Pa(u,f,Ga))}var x=l.length;return s&&(l.fill(0,x),p.fill(0,x)),{selectedIndices:_n(l,"int32"),selectedScores:_n(p,"float32"),numValidOutputs:Dn(x,"int32")}}function Ua(t,e,n){var r=t.subarray(4*e,4*e+4),a=t.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(a[0],a[2]),l=Math.min(a[1],a[3]),p=Math.max(a[0],a[2]),f=Math.max(a[1],a[3]),d=(s-o)*(u-i),h=(p-c)*(f-l);if(d<=0||h<=0)return 0;var m=Math.max(o,c),v=Math.max(i,l),g=Math.min(s,p),y=Math.min(u,f),x=Math.max(g-m,0)*Math.max(y-v,0);return x/(d+h-x)}function ja(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Ga(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function Ha(t,e,n){var r=new Array(t.rank).fill(0),a=t.shape.slice();return e.map((function(e){a[n]=e;var o=t.slice(r,a);return r[n]+=e,o}))}function qa(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var a=pr(n,t.dtype);for(r=0;r<a.values.length;++r){for(var o=a.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=o[s]%t.shape[s];var u=t.locToIndex(i);a.values[r]=t.values[u]}return a.toTensor()}function Ka(t,e,n,r,a){for(var o=e[e.length-1],i=[t.length/o,o],s=i[0],u=i[1],c=U(n,s*r),l=U("int32",s*r),p=0;p<s;p++){for(var f=p*u,d=t.subarray(f,f+u),h=[],m=0;m<d.length;m++)h.push({value:d[m],index:m});h.sort((function(t,e){return e.value-t.value}));var v=p*r,g=c.subarray(v,v+r),y=l.subarray(v,v+r);for(m=0;m<r;m++)g[m]=h[m].value,y[m]=h[m].index}var x=e.slice();return x[x.length-1]=r,[An(c,x,n),An(l,x,"int32")]}function Xa(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var a=pr(t,"int32"),o=pr([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=a.indexToLoc(n[r]),s=r*t.length;o.values.set(i,s)}return o.toTensor()}var Ya=function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((function(t,e){return"T"+e}));var n=[];this.variableNames.forEach((function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();")}));var r=this.variableNames.map((function(t){return"v"+t})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n float result = "+r+";\n setOutput(result);\n }\n "},$a=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((function(t,e){return"T"+e}));var n=[];this.variableNames.forEach((function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")}));var r=this.variableNames.map((function(t){return"v"+t})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n vec4 result = "+r+";\n setOutput(result);\n }\n "},Qa=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,a=t.batchSize,o=t.inSize,i=Math.ceil(o/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,i];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function Ja(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function Za(t,e){return 1===e?[t]:Ja(t,e)}function to(){var t,e,n,r,a,o,i,s,u,c;return 2===f().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",a="texture",o="outputColor",i="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",u="",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",a="texture2D",o="gl_FragColor",i="",s="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:a,output:o,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function eo(t,e,n){void 0===n&&(n="index");var r=nt(e);return r.map((function(e,a){return"int "+t[a]+" = "+n+" / "+e+"; "+(a===r.length-1?"int "+t[a+1]+" = "+n+" - "+t[a]+" * "+e:"index -= "+t[a]+" * "+e)+";"})).join("")}function no(t){var e=nt(t).map((function(t){return t.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var ro="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function ao(t,e,n,r){var a=[];t.forEach((function(t){var e=D(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?a.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(a.push("uniform sampler2D "+t.name+";"),a.push("uniform int offset"+t.name+";"))}));var o,i,s=a.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n,r,a;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=to(),"\n vec4 "+r+"() {\n return "+a.texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=to();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+a[0]+", "+a[1]+", index);\n return "+o.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t.shapeInfo.texShape,o=a[0],i=a[1],s=to();if(null!=a&&_(e,a))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+o+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=e.shapeInfo.texShape,i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===n[0]){var s=fo(e,n.slice(1));return"\n "+t(s)+"\n vec4 "+a+"(int b, int row, int col) {\n return "+a+"("+ho(["b","row","col"],[1,2])+");\n }\n "}var u=i[0],c=i[1],l=Math.ceil(n[2]/2);return"\n vec4 "+a+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+u+", "+c+", "+l*Math.ceil(n[1]/2)+", "+l+", b, row, col);\n return "+to().texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=t.shapeInfo.texShape,i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=i[0],u=i[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),p="int b, int row, int col",f="b * "+l+" + (row / 2) * "+c+" + (col / 2)",d=2;d<n-1;d++)p="int b"+d+", "+p,f="b"+d+" * "+(l*=e[n-d-1])+" + "+f;return"\n vec4 "+a+"("+p+") {\n int index = "+f+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+to().texture2D+"("+r+", uv);\n }\n "}(e)}}(t):function t(e){var n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,a=r[0],o=r[1];if(1===a&&1===o)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=t.shapeInfo.texShape;return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+i[0]+", "+i[1]+", "+co(e)+");\n return sampleTexture("+e+", uv);\n }\n "}(e);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n float "+n+"(int index) {\n "+lo(t)+"\n }\n ";var r=t.shapeInfo.texShape,a=r[0],o=r[1];if(1===o&&1===a)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=co(e);return 1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+a+".0);\n return sampleTexture("+e+", uv);\n }\n ":1===a?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+i+") + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+a+", "+o+", index + "+i+");\n return sampleTexture("+e+", uv);\n }\n "}(e);case 2:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=e.shapeInfo.texShape;if(null!=o&&_(n,o)){var i=o[0];return"\n float "+a+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o[1]+".0, "+i+".0);\n return sampleTexture("+r+", uv);\n }\n "}var s=z(n),u=s.newShape,c=s.keptDims,l=u;if(l.length<n.length){var p=fo(e,l);return"\n "+t(p)+"\n float "+a+"(int row, int col) {\n return "+a+"("+ho(["row","col"],c)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+a+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+n[1]+", 1)));\n "+lo(e)+"\n }\n ";var f=o[0],d=o[1],h=co(r);return 1===d?"\n float "+a+"(int row, int col) {\n float index = dot(vec3(row, col, "+h+"), vec3("+n[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+f+".0);\n return sampleTexture("+r+", uv);\n }\n ":1===f?"\n float "+a+"(int row, int col) {\n float index = dot(vec3(row, col, "+h+"), vec3("+n[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+d+".0, 0.5);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+a+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+n[1]+" + col + "+h+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+r+", uv);\n }\n"}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=n[1]*n[2],i=n[2],s=z(n),u=s.newShape,c=s.keptDims,l=u;if(l.length<n.length){var p=fo(e,l);return"\n "+t(p)+"\n float "+a+"(int row, int col, int depth) {\n return "+a+"("+ho(["row","col","depth"],c)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+a+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+o+", "+i+", 1)));\n "+lo(e)+"\n }\n ";var f=e.shapeInfo.texShape,d=f[0],h=f[1],m=e.shapeInfo.flatOffset;return h===o&&null==m?"\n float "+a+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+i+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+h+".0, "+d+".0);\n return sampleTexture("+r+", uv);\n }\n ":h===i&&null==m?"\n float "+a+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+n[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+h+".0, "+d+".0);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+a+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+o+" + col * "+i+" + depth + "+co(r)+";\n vec2 uv = uvFromFlat("+d+", "+h+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);case 4:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=n[3],i=n[2]*o,s=n[1]*i,u=z(n),c=u.newShape,l=u.keptDims;if(c.length<n.length){var p=fo(e,c);return"\n "+t(p)+"\n float "+a+"(int row, int col, int depth, int depth2) {\n return "+a+"("+ho(["row","col","depth","depth2"],l)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+a+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+s+", "+i+", "+o+", 1)));\n "+lo(e)+"\n }\n ";var f=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],m=d[1];return m===s&&null==f?"\n float "+a+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+i+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+h+".0);\n return sampleTexture("+r+", uv);\n }\n ":m===o&&null==f?"\n float "+a+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+n[1]*n[2]+", "+n[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+h+".0);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+a+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+i+" +\n depth * "+o+" + depth2;\n vec2 uv = uvFromFlat("+h+", "+m+", index + "+co(r)+");\n return sampleTexture("+r+", uv);\n }\n "}(e);case 5:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=n[4],i=n[3]*o,s=n[2]*i,u=n[1]*s,c=z(n),l=c.newShape,p=c.keptDims;if(l.length<n.length){var f=fo(e,l);return"\n "+t(f)+"\n float "+a+"(int row, int col, int depth, int depth2, int depth3) {\n return "+a+"("+ho(["row","col","depth","depth2","depth3"],p)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+a+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+u+", "+s+", "+i+", "+o+")) +\n depth3;\n "+lo(e)+"\n }\n ";var d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,m=h[0],v=h[1];return v===u&&null==d?"\n float "+a+"(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+s+", "+i+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+m+".0);\n return sampleTexture("+r+", uv);\n }\n ":v===o&&null==d?"\n float "+a+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+n[1]*n[2]*n[3]+",\n "+n[2]*n[3]+", "+n[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+m+".0);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+a+"(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+u+" + col * "+s+" + depth * "+i+" +\n depth2 * "+o+" + depth3 + "+co(r)+";\n vec2 uv = uvFromFlat("+m+", "+v+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);case 6:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),o=z(n),i=o.newShape,s=o.keptDims;if(i.length<n.length){var u=fo(e,i);return"\n "+t(u)+"\n float "+a+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+a+"("+ho(["row","col","depth","depth2","depth3","depth4"],s)+");\n }\n "}var c=n[5],l=n[4]*c,p=n[3]*l,f=n[2]*p,d=n[1]*f;if(e.shapeInfo.isUniform)return"\n float "+a+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4("+d+", "+f+", "+p+", "+l+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+c+", 1)));\n "+lo(e)+"\n }\n ";var h=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,v=m[0],g=m[1];return g===d&&null==h?"\n float "+a+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+f+", "+p+", "+l+", "+c+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+v+".0);\n return sampleTexture("+r+", uv);\n }\n ":g===c&&null==h?"\n float "+a+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+n[1]*n[2]*n[3]*n[4]+",\n "+n[2]*n[3]*n[4]+",\n "+n[3]*n[4]+",\n "+n[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+v+".0);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+a+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+d+" + col * "+f+" + depth * "+p+" +\n depth2 * "+l+" + depth3 * "+c+" + depth4 + "+co(r)+";\n vec2 uv = uvFromFlat("+v+", "+g+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);default:throw new Error(n.length+"-D input sampling is not yet supported")}}(t);var a=t.shapeInfo.logicalShape,o=e.logicalShape;return a.length<=o.length&&(r+=n?function(t,e){var n,r=t.name,a=r.charAt(0).toUpperCase()+r.slice(1),o="get"+a+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=ha(t.shapeInfo.logicalShape,e.logicalShape),c=po(s),l=s-i,p=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map((function(t){return"coords."+p[t+l]+" = 0;"})).join("\n");var f;f=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+p[e+l]})).join(", ");var d="return outputValue;",h=1===D(t.shapeInfo.logicalShape),m=1===D(e.logicalShape);if(1!==i||h||m){if(h&&!m)d=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var v=i-2,g=i-1;u.indexOf(v)>-1&&u.indexOf(g)>-1?d="return vec4(outputValue.x);":u.indexOf(v)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+o+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+a+"("+f+");\n "+d+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",o=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&_(i,o))return"\n float "+a+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c=po(u),l=ha(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,f=["x","y","z","w","u","v"];return"\n float "+a+"() {\n "+c+" coords = getOutputCoords();\n "+(0===s?"":u<2&&l.length>=1?"coords = 0;":l.map((function(t){return"coords."+f[t+p]+" = 0;"})).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+f[e+p]})).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)})).join("\n"),c=e.texShape,l=to(),p=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(l),f=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+oo+"\n "+io+"\n "+so+"\n "}(l);return e.isPacked?(o=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(_(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],i=(o=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+a[0]+", "+a[1]+"));\n int index = resTexRC.x * "+a[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+o+");\n int c = imod(index, "+o+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),a=r*Math.ceil(t[t.length-2]/2),o=a,i="",s="b, r, c",u=2;u<t.length-1;u++)i="\n int b"+u+" = index / "+(o*=t[t.length-u-1])+";\n index -= b"+u+" * "+o+";\n "+i,s="b"+u+", "+s;return"\n ivec"+t.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+i+"\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec"+t.length+"("+s+");\n }\n "}(t,e)}var n,r,a,o,i}(e.logicalShape,c),i=function(t){return"\n void setOutput(vec4 val) {\n "+t.output+" = val;\n }\n "}(l)):(o=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){return 1===e[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ":1===e[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n return resTexRC.x * "+e[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){return _(t,e)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ":1===t[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===t[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n int r = index / "+t[1]+";\n int c = index - r * "+t[1]+";\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=e,r=eo(["r","c","d"],t),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n "+r+"\n return ivec3(r, c, d);\n }\n ";case 4:return function(t,e){var n=eo(["r","c","d","d2"],t);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(t,e);case 5:return function(t,e){var n=eo(["r","c","d","d2","d3"],t);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n "+e[1]+"));\n\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(t,e);case 6:return function(t,e){var n=eo(["r","c","d","d2","d3","d4"],t);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,c),i=function(t){return"\n void setOutput(float val) {\n "+t.output+" = vec4(val, 0, 0, 0);\n }\n "}(l)),r&&(f+=uo),[f,p,i,s,o,u,n].join("\n")}var oo="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",io="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",so="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",uo="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function co(t){return"offset"+t}function lo(t){var e=t.name,n=D(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n for (int i = 0; i < "+n+"; i++) {\n if (i == index) {\n return "+e+"[i];\n }\n }\n "}function po(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function fo(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function ho(t,e){return e.map((function(e){return t[e]})).join(", ")}var mo=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,T(t.length>2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var a=t[t.length-1],o=Math.ceil(a/e);this.outputShape=t.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=po(c),p=Za("coords",c);if(1===o){var f=po(s=c+1);i="\n "+f+" sourceLocR = "+f+"("+p.join()+", 0);\n ++"+p[c-1]+";\n "+f+" sourceLocG = "+f+"("+p.join()+", 0);\n ++"+p[c-2]+";\n "+f+" sourceLocA = "+f+"("+p.join()+", 0);\n --"+p[c-1]+";\n "+f+" sourceLocB = "+f+"("+p.join()+", 0);\n --"+p[c-2]+";"}else s=c,i="\n "+l+" sourceLocR = coords;\n ++"+p[c-1]+";\n "+l+" sourceLocG = coords;\n ++"+p[c-2]+";\n "+l+" sourceLocA = coords;\n --"+p[c-1]+";\n "+l+" sourceLocB = coords;\n --"+p[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),h="."+d[s-1],m=d.map((function(t){return"int "+t})),v=Za("sourceLocR",s-1).concat("inIdx.r"),g=Za("sourceLocG",s-1).concat("inIdx.g"),y=Za("sourceLocB",s-1).concat("inIdx.b"),x=Za("sourceLocA",s-1).concat("inIdx.a"),b="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+")));",C="vec4(\n getAChannel("+v.join()+"),\n hasNextCol ? getAChannel("+g.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",E=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+E+"\n void main() {\n "+l+" coords = getOutputCoords();\n bool hasNextCol = "+p[c-1]+" < "+(u[c-1]-1)+";\n bool hasNextRow = "+p[c-2]+" < "+(u[c-2]-1)+";\n "+i+"\n ivec4 srcIdx = ivec4(sourceLocR"+h+", sourceLocG"+h+",\n sourceLocB"+h+", sourceLocA"+h+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+b+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},vo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,o=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},go=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,o=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,p=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=l-1-t.padInfo.front,h=p-1-t.padInfo.top,m=f-1-t.padInfo.left,v=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+d+", "+h+", "+m+");\n const float avgMultiplier = float("+v+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+a+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+f+";\n wC += "+c+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},yo=function(t,e,n,r,a,o){this.outputShape=[],this.variableNames=["x","mean","variance"],va(t,e),va(t,n);var i="0.0";null!=r&&(va(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=a&&(va(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},xo=function(t,e,n,r,a,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],va(t,e),va(t,n);var i="vec4(0.0)";null!=r&&(va(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=a&&(va(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+i+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},bo=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=va(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},wo="return a + b;",Co="return a - b;",Eo="return a * b;",So="return (a < 0.) ? b * a : a;",No=function(t,e,n){this.variableNames=["A","B"],this.outputShape=va(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Io="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Ro=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=va(e,n);var a=this.outputShape.length,o="";if(r)if(0===a||1===D(this.outputShape))o="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(o="\n "+po(a)+" coords = getOutputCoords();\n ",1===a)o+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=Za("coords",a);o+="\n bool nextRowOutOfBounds =\n ("+i[a-2]+" + 1) >= "+this.outputShape[a-2]+";\n bool nextColOutOfBounds =\n ("+i[a-1]+" + 1) >= "+this.outputShape[a-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+o+"\n\n setOutput(result);\n }\n "},To=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),ko=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ao=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},Oo=function(t){this.outputShape=[],this.outputShape=Nn(t,1),this.variableNames=t.map((function(t,e){return"T"+e}));var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var a=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+a+"));")}var o=e.length,i=e[e.length-1];r.push("else setOutput(getT"+o+"(yR, yC-"+i+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},Do=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Nn(t,e);var n=this.outputShape,r=n.length,a=po(r),o=Za("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map((function(t,e){return"T"+e}));var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var c=i[e],l=i.slice(-2),p=i.join(),f="if ("+c+" < "+s[0]+") {\n return getChannel(\n getT0("+p+"), vec2("+l.join()+"));\n }";for(u=1;u<s.length;u++){var d=s[u-1];f+="\n if ("+c+" < "+s[u]+" && "+c+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+_o(i,c,d)+"),\n vec2("+_o(l,c,d)+"));\n }"}var h=s.length,m=s[s.length-1];f+="\n return getChannel(\n getT"+h+"("+_o(i,c,m)+"),\n vec2("+_o(l,c,m)+"));",this.userCode="\n float getValue("+i.map((function(t){return"int "+t}))+") {\n "+f+"\n }\n\n void main() {\n "+a+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+o+"), 0., 0., 0.);\n\n "+o[r-1]+" = "+o[r-1]+" + 1;\n if ("+o[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+o+");\n }\n\n "+o[r-2]+" = "+o[r-2]+" + 1;\n if ("+o[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+o+");\n }\n\n "+o[r-1]+" = "+o[r-1]+" - 1;\n if ("+o[r-2]+" < "+n[r-2]+" &&\n "+o[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+o+");\n }\n setOutput(result);\n }\n "};function _o(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var Fo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,o="channelsLast"===t.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+o+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Mo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,o="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=o?1:2,c=o?2:3,l=o?3:1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+l+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+c+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n if ("+o+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Bo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.padInfo.front,o=t.padInfo.top,i=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+a+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+o+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Po=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,o=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,c=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+c+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+a+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Lo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,o=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Vo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,o=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Wo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,o=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4,h="channelsLast"===t.dataFormat,m=h?1:2,v=h?2:3,g=h?3:1,y="",x="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",x="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+a+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+g+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+v+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+c+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+h+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===d)+") {\n\n if ("+h+") {\n dotProd +=\n getX(batch, xR, xC, "+f+") *\n getW(wR, wC, "+f+", d2);\n } else {\n dotProd +=\n getX(batch, "+f+", xR, xC) *\n getW(wR, wC, "+f+", d2);\n }\n\n } else if ("+(2===d)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2)\n );\n\n if ("+h+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===d)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2),\n getW(wR, wC, "+f+" + 2, d2)\n );\n\n if ("+h+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1),\n getX(batch, xR, xC, "+f+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC),\n getX(batch, "+f+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+b+"\n "+x+"\n setOutput(result);\n }\n "},zo=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,a=t.strideDepth,o=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,p=t.filterHeight,f=t.filterWidth,d=4*Math.floor(t.inChannels/4),h=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+a+", "+o+", "+i+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+l+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC++) {\n int xC = xCCorner + wC * "+c+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+d+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===h)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+d+") *\n getW(wF, wR, wC, "+d+", d2);\n } else if ("+(2===h)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===h)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1),\n getX(batch, xF, xR, xC, "+d+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2),\n getW(wF, wR, wC, "+d+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Uo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.inHeight,o=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,p=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,h=t.outChannels/t.inChannels,m="",v="";n&&(m=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",v="result = activation(result);");var g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+m+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+h+";\n int q = d2 - d1 * "+h+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+f+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+a+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+p+";\n\n if (xC < 0 || xC >= "+o+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+g+"\n "+v+"\n setOutput(result);\n }\n "},jo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var a=t.inHeight,o=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,p=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,h=d,m="int xR; int xC; int xCOffset;",v=0;v<f;v++)for(var g=0;g<d;g++)m+="\n vec4 xTexelR"+v+"C"+2*g+" = vec4(0.);\n vec4 wR"+v+"C"+g+" = vec4(0.);\n vec4 xR"+v+"C"+g+" = vec4(0.);";for(v=0;v<f;v++)for(var y=0;y<h;y++){if(m+="\n xR = xRCorner + "+v*l+";\n xC = xCCorner + "+(g=2*y)*p+";\n ",1===c){if(g<d&&(m+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+g+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+g+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+o+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+v+"C"+g+" = vec4(previous.zw, xTexelR"+v+"C"+g+".xy);\n } else {\n xR"+v+"C"+g+" = vec4(0, 0, xTexelR"+v+"C"+g+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+a+" && xC >= 0 && xC < "+o+") {\n xTexelR"+v+"C"+g+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+v+"C"+g+" = vec4(0.);\n }\n\n xR"+v+"C"+g+" = xTexelR"+v+"C"+g+";\n ",g+1<d)){var x=s%2==0?I(p):p;p%2==0&&s%2==1||p%2!=0&&s%2!=1?(m+="\n xCOffset = xC + "+s%2+" + "+x+";\n\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",p>1&&(m+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+g+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+g+" = vec4(0.);\n }\n "),m+="\n xR"+v+"C"+(g+1)+" = vec4(\n xTexelR"+v+"C"+g+".zw, xTexelR"+v+"C"+(g+2)+".xy);\n "):m+="\n xCOffset = xC + "+x+";\n\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+v+"C"+(g+1)+" = xTexelR"+v+"C"+(g+2)+";\n "}}else g<d&&(m+="\n if(xR >= 0 && xR < "+a+") {\n ",s%2==1?(m+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+g+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+g+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+o+") {\n xTexelR"+v+"C"+(g+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+v+"C"+(g+2)+" = vec4(0.);\n }\n\n xR"+v+"C"+g+" = vec4(\n xTexelR"+v+"C"+g+".zw, xTexelR"+v+"C"+(g+2)+".zw);\n ",g+1<d&&(m+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+v+"C"+(g+1)+" = vec4(xTexelR"+v+"C"+(g+2)+".xy, final.xy);\n ")):(m+="\n if(xC >= 0 && xC < "+o+") {\n xTexelR"+v+"C"+g+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+v+"C"+g+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+v+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+(g+2)+" = vec4(0.);\n }\n\n xR"+v+"C"+g+" = vec4(\n xTexelR"+v+"C"+g+".xy, xTexelR"+v+"C"+(g+2)+".xy);\n ",g+1<d&&(m+="\n xR"+v+"C"+(g+1)+" = vec4(\n xTexelR"+v+"C"+g+".zw, xTexelR"+v+"C"+(g+2)+".zw);\n ")),m+="}");g<d&&(m+="\n vec4 wTexelR"+v+"C"+g+" = getW("+v+", "+g+", d1, q);\n wR"+v+"C"+g+" = vec4(wTexelR"+v+"C"+g+".xz, wTexelR"+v+"C"+g+".xz);\n ",g+1<d&&(m+="\n vec4 wTexelR"+v+"C"+(g+1)+" = getW("+v+", "+(g+1)+", d1, q);\n wR"+v+"C"+(g+1)+" =\n vec4(wTexelR"+v+"C"+(g+1)+".xz, wTexelR"+v+"C"+(g+1)+".xz);"))}for(v=0;v<f;v++)for(g=0;g<d;g++)m+="dotProd += xR"+v+"C"+g+" * wR"+v+"C"+g+";";var b="",w="";n&&(b=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",w="result = activation(result);");var C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+b+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+m+"\n\n vec4 result = dotProd;\n "+C+"\n "+w+"\n setOutput(result);\n }\n "},Go=function(t,e,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=t[0],i=t[1],s=t[2],u=t[3],c=e[0],l=n[0],p=n[1];this.outputShape=[c,l,p,u];var f="bilinear"===r?1:0,d=[i-1+".0",s-1+".0"],h=d[0],m=d[1],v=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+h+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+h],g=v[0],y=v[1],x=v[2],b=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=b[0],C=b[1],E=b[2];this.userCode="\n const float height_ratio = float("+g+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+o+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+h+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+f+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},Ho=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,a=t[t.length-1],o=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+po(r)+" coords = getOutputCoords();\n int end = "+qo(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+qo(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function qo(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var Ko=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=zt.DENSE;var e=Yt(t),n=to();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+eo(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},Xo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=zt.DENSE;var e=Yt(t),n=to();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+eo(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},Yo=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),$o=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},Qo=function(t){this.variableNames=["A"],this.outTexUsage=Ut.DOWNLOAD;var e=to();this.outputShape=t,this.userCode="\n "+ro+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},Jo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ut.DOWNLOAD;var e=to();this.outputShape=t,this.userCode="\n "+ro+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},Zo=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=to(),a=e[0],o=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+no(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+o+";\n int c = imod(flatIndex, "+o+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+a+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+i+", 0., 0., 0.);\n }\n "},ti=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=to(),a=e[0],o=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;i+="\n localCoords = coords;\n if(localCoords[2] + "+c+" < "+t[2]+") {\n localCoords[2] += "+c+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+o+";\n c = imod(flatIndex, "+o+");\n uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+a+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+l+"] = values[0];\n } else if(offset == 1) {\n result["+l+"] = values[1];\n } else if(offset == 2) {\n result["+l+"] = values[2];\n } else {\n result["+l+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+no(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+i+"\n\n "+r.output+" = "+s+";\n }\n "},ei=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var a=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+a+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},ni=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),ri=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var a=po(this.rank),o=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],o=0;o<t.length;o++)o===e?a.push("int(getIndices("+r[o]+"))"):a.push(""+r[o]);return a.join()}(t,n);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},ai=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=po(e.length),a=po(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+a+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function oi(t,e){var n=to();return ne(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function ii(t,e){return le(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function si(t,e){return pe(t,e,new Uint16Array([0,1,2,2,1,3]))}function ui(t,e,n,r,a,o,i){de(n,r);var s=fe(t,e),u=t.TEXTURE_2D;return Jt(t,e,(function(){return t.bindTexture(u,s)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texImage2D(u,0,a,n,r,0,o,i,null)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function ci(t,e,n,r,a){var o=Xt(n,r);return ui(t,e,o[0],o[1],a.internalFormatFloat,a.textureFormatFloat,t.FLOAT)}function li(t,e,n,r,a){var o=Xt(n,r);return ui(t,e,o[0],o[1],a.internalFormatHalfFloat,a.textureFormatFloat,a.textureTypeHalfFloat)}function pi(t,e,n,r,a){var o=Xt(n,r);return ui(t,e,o[0],o[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function fi(t,e,n,r,a){var o=$t(n,r);return ui(t,e,o[0],o[1],a.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function di(t,e,n,r,a){var o=$t(n,r);return ui(t,e,o[0],o[1],a.internalFormatPackedHalfFloat,t.RGBA,a.textureTypeHalfFloat)}function hi(t,e,n,r){return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),me(t,e,n,"clipSpacePos",r,3,20,0)&&me(t,e,n,"uv",r,2,20,12)}function mi(t,e,n,r,a,o,i){var s,u,c;Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),o instanceof Uint8Array?(s=new Uint8Array(r*a*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*a*4),u=t.FLOAT,c=i.internalFormatPackedFloat),s.set(o),Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,a,0,t.RGBA,u,s)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function vi(t,e,n,r){Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function gi(t,e,n,r,a){var o=t.createBuffer();Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,o)}));var i=16*n*r;return Jt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)})),Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),o}function yi(t,e,n){var r=t,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}function xi(t,e,n,r,a){var o=Xt(n,r),i=o[0],s=o[1],u=new Uint8Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,i,s,a.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function bi(t,e,n,r,a,o,i,s){var u=t,c=new Float32Array(function(t,e){var n=$t(t,e);return n[0]*n[1]*4}(o,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function wi(t,e,n,r){var a=new Float32Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,a)})),a}var Ci=Object.freeze({createVertexShader:oi,createVertexBuffer:ii,createIndexBuffer:si,createFloat32MatrixTexture:ci,createFloat16MatrixTexture:li,createUnsignedBytesMatrixTexture:pi,createPackedMatrixTexture:fi,createFloat16PackedMatrixTexture:di,bindVertexProgramAttributeStreams:hi,uploadDenseMatrixToTexture:mi,uploadPixelDataToTexture:vi,createBufferFromOutputTexture:gi,downloadFloat32MatrixFromBuffer:yi,downloadByteEncodedFloatMatrixFromOutputTexture:xi,downloadPackedMatrixFromBuffer:bi,downloadMatrixFromPackedOutputTexture:wi}),Ei=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=f().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,qt(e,t)):this.gl=Kt(e);var n="WEBGL_color_buffer_float";if(1===f().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=ee(this.gl,this.debug,"OES_texture_float"),Me(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=ee(this.gl,this.debug,"OES_texture_half_float");else if(f().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Me(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=ee(this.gl,this.debug,"EXT_color_buffer_half_float");else if(f().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Me(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Me(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=ii(this.gl,this.debug),this.indexBuffer=si(this.gl,this.debug),this.framebuffer=he(this.gl,this.debug),this.textureConfig=Qt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return f().getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Jt(e,this.debug,(function(){return e.finish()})),Jt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),ci(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),li(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),pi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),vi(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),mi(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),di(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),fi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(we(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Jt(this.gl,this.debug,(function(){return e.gl.deleteTexture(t)}))},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return xi(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,a,o){return bi(this.gl,t,0,0,0,a,o,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return yi(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=gi(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(f().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,o=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=a.clientWaitSync(o,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},e=o}else f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return wi(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=re(e,this.debug,t),r=oi(e,this.debug),a=se(e,this.debug);return Jt(e,this.debug,(function(){return e.attachShader(a,r)})),Jt(e,this.debug,(function(){return e.attachShader(a,n)})),ue(e,this.debug,a),this.debug&&ce(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=hi(e,this.debug,this.program,this.vertexBuffer)),a},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Jt(this.gl,this.debug,(function(){return e.gl.deleteProgram(t)}))},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&ce(this.gl,this.debug,this.program),Jt(this.gl,this.debug,(function(){return e.gl.useProgram(t)}))},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ge(this.gl,this.debug,t,e):ye(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return n.gl.getAttribLocation(t,e)}))},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),xe(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=$t(e,n),a=r[0],o=r[1];this.setOutputMatrixTextureDriver(t,a,o)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&ce(this.gl,this.debug,this.program),Ce(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Jt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=ee(this.gl,this.debug,2===f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},t.prototype.endQuery=function(){if(2!==f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return u(this,void 0,void 0,(function(){var e=this;return c(this,(function(n){switch(n.label){case 0:return[4,L((function(){return e.disposed||e.isQueryAvailable(t,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise((function(n){e.addItemToPoll((function(){return t.isFencePassed()}),(function(){return n()}))}))},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length&&t[e]();++e);return e-1}(this.itemsToPoll.map((function(t){return t.isDoneFn}))),e=0;e<=t;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||L((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),be(this.gl,this.debug,t,this.framebuffer),this.debug&&Ce(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(be(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Ce(this.gl)):we(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;be(r,this.debug,t,this.framebuffer),this.debug&&Ce(r),this.outputTexture=t,Jt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Jt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var a=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return a.gl.scissor(t,e,n,r)}))},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function Si(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach((function(t,n){var r=t.logicalShape,a=e[n],o=a.shape;if(!_(r,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+o+" must match");if(!t.isUniform||!a.isUniform){var i=t.texShape,s=a.isUniform?null:a.texData.texShape;if(!_(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}}))}var Ni=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,a=n.inChannels,o=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,p=n.dataFormat,f=s.left,d=s.top,h=a*r,m=to(),v="channelsLast"===p,g=v?0:1,y=v?1:2,x="",b=0;b<=1;b++)for(var w=0;w<=1;w++)x+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+b+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n d0 = offsetY + "+l+" * (pos / "+h+");\n\n if(d0 < "+e[g]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+o+". - "+f+".);\n d1 = offsetX + "+c+" * (int(mod(float(pos), "+h+".) / "+a+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+a+".));\n\n if ("+v+") {\n innerDims = vec2(d1, ch);\n result["+(2*b+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*b+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+x+"\n\n "+m.output+" = result;\n }\n "},Ii=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[];var o,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+i+"; j <= "+i+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+o+";\n setOutput(val);\n }\n "},Ri=function(t,e,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=a,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+a+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+a+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},Ti=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var o,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+i+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+i+"; j <= "+i+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+o+";\n setOutput(result);\n }\n "},ki=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,o=t.effectiveFilterWidth,i=a-1-t.padInfo.top,s=o-1-t.padInfo.left,u=a*o-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+a+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Ai=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,o=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,p=u-1-t.padInfo.top,f=c-1-t.padInfo.left,d=s*u*c-1;this.userCode="\n const ivec3 pads = ivec3("+l+", "+p+", "+f+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+a+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+c+";\n wC += "+i+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+d+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+c+" +\n wR * "+c+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Oi=function(t,e,n,r,a,o,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===o&&(o=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),c=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",h="";o&&(d=i?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+o+"\n }":"vec4 activation(vec4 x) {\n "+o+"\n }",h="result = activation(result);");var m=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+d+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+c+");\n vec4 b = getMatrixB(rc.x, "+l+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+f[0]+");\n result += ("+p[1]+" * "+f[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+h+"\n\n setOutput(result);\n }\n "},Di=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),_i=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Fi=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=Za("rc",e),r=po(e),a=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",a=t-2;a<t;a++)r+=n[a]+" >= "+e[a],a<t-1&&(r+="||");return r}(e,t,n),o=function(t,e,n,r){if(1===t)return"";var a=r.slice(-2);return"\n int r = "+a[0]+";\n int c = "+a[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var a=0;a<=1;a++){for(var o=(0===r?"r":"rp1")+", "+(0===a?"c":"cp1"),i=2;i<t;i++)o=e[e.length-1-i]+","+o;n.push(o)}return n}(n,e);return 1===n?"getA(rc),\n rc + 1 >= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+a+") {\n setOutput(vec4(0));\n } else {\n "+o+"\n\n setOutput(vec4("+i+"));\n }\n }\n "}},Mi=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));var r=t.length,a=po(r),o=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+a+" start = "+a+"("+o+");\n "+a+" end = "+a+"("+i+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+o+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Bi=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,a=po(r),o=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=Za("rc",r),u=Za("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[a+" rc = outputLoc;",s[r-1]+" += 1;\n if("+c+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+c+") {"],f=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",h=0,m=1===r?2:4;h<m;h++)d+="\n "+p[h]+"\n if ("+f+") {\n result["+h+"] = float("+n+");\n } else {\n "+a+" source = rc - start;\n result["+h+"] = getChannel(getX("+u.join()+"), "+l+");\n }\n ";d+=1===r?"} ":"}}",this.userCode="\n const "+a+" start = "+a+"("+o+");\n const "+a+" end = "+a+"("+i+");\n\n void main() {\n "+a+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+d+"\n setOutput(result);\n }\n "},Pi=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,a=t.strideHeight,o=t.strideWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,p=t.padInfo.left;this.outputShape=t.outShape;var f="avg"===e,d="0.0";if(f||(d="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+l+", "+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+c+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var h=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(h="avgValue / count");var m=4*Math.floor(r/4),v=r%4,g="\n if ("+f+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+l+", "+p+");\n const float initializationValue = "+d+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+d+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+g+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===v)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2===v)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(3===v)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+g+"\n }\n }\n setOutput("+h+");\n }\n "}},Li=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,a=t.strideDepth,o=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,p=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=t.padInfo.front,h=t.padInfo.top,m=t.padInfo.left;this.outputShape=t.outShape;var v="avg"===e,g="0.0";if(v||(g="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+a+", "+o+", "+i+");\n const ivec3 pads = ivec3("+d+", "+h+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+";\n wC += "+c+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+p+" * "+f+" +\n wR * "+f+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var x=4*Math.floor(r/4),b=r%4,w="\n if ("+v+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+a+", "+o+", "+i+");\n const ivec3 pads = ivec3("+d+", "+h+", "+m+");\n const float initializationValue = "+g+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+g+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+x+"; wC += 4) {\n int xC = xCCorner + wC * "+c+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n getValue(batch, xD, xR, xC + 3 * "+c+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+x+";\n if ("+(1===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Vi=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,a=t.inSize,o=Math.ceil(a/n);this.outputShape=[r,o];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var c=4*Math.floor(n/4),l=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",f="vec4";"all"===e?(i="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",f="bvec4"):"any"===e&&(i="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",f="bvec4");var d="";a%n>0&&(d="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+d+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+i+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+c+"; i += 4) {\n int inIdx = inOffset + i;\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+c+";\n if ("+(1===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},Wi=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var a="thisRC = rc;";r%2==1&&(a+="thisRC.z += 1;"),r>1&&(a+="thisRC.y += 1;"),n+="\n "+a+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+eo(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+no(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},zi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],o=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?a-1:a,n&&u>1?o-1:o],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=c[0]/l[0],f=c[1]/l[1],d=1/p,h=1/f,m=2*Math.ceil(d)+2,v=2*Math.ceil(h)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+h+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+v+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Ui=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],o=t[1],i=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},ji=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],o=t[1],i=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+",\n "+u[1]/c[1]+");\n const vec3 inputShapeRC = vec3("+o+".0, "+i+".0,\n "+i+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Gi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],o=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?a-1:a,n&&u>1?o-1:o],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=c[0]/l[0],f=c[1]/l[1],d=1/p,h=1/f,m=2*Math.ceil(d)+2,v=2*Math.ceil(h)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+h+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+v+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+c[0]+") *\n (float(dyR) / float("+l[0]+"));\n\n float sourceFracCol =\n float("+c[1]+") *\n (float(dyC) / float("+l[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Hi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],o=t[1],i=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n],l=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+l+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},qi=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map((function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)})).join(","),a=po(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},Ki=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=Za("rc",n),a=r[n-1]+" + 1 < "+this.outputShape[n-1],o=r[n-2]+" + 1 < "+this.outputShape[n-2],i=po(n);function s(n){var r=t.map((function(r,a){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(a,n)}));return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+a+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+a+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+o+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+a+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},Xi=function(t,e,n,r,a,o,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=po(a.length),u=po(o.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var f="getUpdates("+p+")",d=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+a+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+l+");\n flattenedIndex += index * "+d+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+f+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Yi=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,a=t.inSize,o=t.numSegments,i=o*Math.ceil(a/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ",l="";a%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var p="";a%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+a+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+l+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+c+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+c+"\n }\n setOutput(sumValue);\n }\n "},$i=function(t,e,n){var r,a;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)a="resRC",r="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+o[u]),u<t&&i.push(""+o[u]);r=i.join(),a=s.join()}var c=po(n);this.userCode="\n void main() {\n "+c+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "},Qi=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=po(this.rank),r="uniform int start["+this.rank+"];",a=function(t){if(1===t)return"sourceLoc";if(t<=6)return Ji.slice(0,t).map((function(t){return"sourceLoc."+t})).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map((function(t,e){return"sourceLoc."+Ji[e]+" = start["+e+"] + coords."+Ji[e]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+a+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ji=["x","y","z","w","u","v"],Zi=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=po(this.rank),n=Za("coords",this.rank),r=Za("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",o="getChannel(getSource("+r.join()+"), "+a+")",i="\n result.x = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+o+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+o+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map((function(t,e){return"start["+e+"]"})).join()+");":t.map((function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+"\n vec4 result = vec4(0.);\n "+i+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),ts=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,a=po(n.length),o=po(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=n.map((function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"})).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+o+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "},es=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,a=ns(e,n),o=rs(t,a,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[o].shift();return this.usedTextures[o].push(i),i}return this.numUsedTextures++,this.log(),a===jt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):a===jt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):a===jt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var a=rs(e,ns(n,r),r);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(t),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[a],i=o.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(i,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));for(var e in this.usedTextures)this.usedTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function ns(t,e){if(t===Ut.UPLOAD)return jt.PACKED_2X2_FLOAT32;if(t===Ut.RENDER||null==t)return function(t){return f().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?jt.PACKED_2X2_FLOAT32:jt.UNPACKED_FLOAT32:t?jt.PACKED_2X2_FLOAT16:jt.UNPACKED_FLOAT16}(e);if(t===Ut.DOWNLOAD||t===Ut.PIXELS)return jt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function rs(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var as=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var a=po(this.rank),o=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a<t.length;a++)r.push("imod("+n[a]+", "+t[a]+")");return r.join()}(t);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},os=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var a=po(this.rank),o=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),a=0;a<t.length;a++)r[t[a]]=n[a];return r.join()}(e);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},is=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var a=po(this.rank),o=Ja("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=o[r];var s="vec2("+i.slice(-2).join()+")",u="++"+o[this.rank-1]+" < "+n[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n void main() {\n "+a+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = "+c+";\n if("+u+") {\n result[1] = "+c+";\n }\n --"+o[this.rank-1]+";\n if(++"+o[this.rank-2]+" < "+n[this.rank-2]+") {\n result[2] = "+c+";\n if("+u+") {\n result[3] = "+c+";\n }\n }\n setOutput(result);\n }\n "},ss=1.7580993408473768,us=1.0507009873554805,cs=function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n float unaryOperation(float x) {\n "+e+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n "},ls="if (isnan(x)) return x;",ps="return abs(x);",fs=ls+"\n return (x < 0.0) ? 0.0 : x;\n",ds=ls+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",hs="return (x >= 0.0) ? x : (exp(x) - 1.0);",ms="return -x;",vs="return ceil(x);",gs="return floor(x);",ys="return exp(x);",xs="return exp(x) - 1.0;",bs="return x;",ws="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Cs="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Es="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Ss=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "},Ns=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Za("rc",e),r=po(e),a=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),o=n.slice(-2),i=e<=1?"rc":"vec2("+o.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+a+");\n\n setOutput(getChannel(packedInput, "+i+"));\n }\n "},Is={};function Rs(t,e){if(void 0===e&&(e=!1),"linear"===t)return"return x;";if("relu"===t)return e?ws:fs;if("elu"===t)return e?Es:hs;if("relu6"===t)return e?Cs:ds;if("prelu"===t)return e?Io:So;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var Ts=function(t){function e(e){var n,r=t.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!f().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var a=Kt(f().getNumber("WEBGL_VERSION"));r.binaryCache=((n=f().getNumber("WEBGL_VERSION"))in Is||(Is[n]={}),Is[n]),r.gpgpu=new Ei(a),r.canvas=a.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new es(r.gpgpu),r.numMBBeforeWarning=null==f().global.screen?1024:f().global.screen.height*f().global.screen.width*window.devicePixelRatio*600/1024/1024,r.texData=new pa(r,Lt),r}return s(e,t),e.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},e.prototype.write=function(t,e,n){if(f().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:Ut.UPLOAD}),r},e.prototype.move=function(t,e,n,r){if(f().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:Ut.UPLOAD})},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,a=e.complexTensors,o=e.slice,i=e.shape,s=e.isPacked;if(null!=o){var u;u=s?new Ss(i,bs):new cs(i,bs);var c=this.runWebGLProgram(u,[{dataId:t,shape:i,dtype:r}],r),l=this.readSync(c.dataId);return this.disposeData(c.dataId),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var p,f,d=null!=this.activeTimers;return d&&(p=st()),f="complex64"===r?_a(a.real.dataSync(),a.imag.dataSync()):this.getValuesFromTexture(t),d&&(this.downloadWaitMs+=st()-p),this.convertAndCacheOnCPU(t,f)},e.prototype.read=function(t){return u(this,void 0,void 0,(function(){var e,n,r,a,o,i,s,u,l,p,d,h,m,v,g,y,x,b,w,C,E,S;return c(this,(function(c){switch(c.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise((function(t){return e.push(t)}))];if(n=this.texData.get(t),r=n.values,a=n.shape,o=n.slice,i=n.dtype,s=n.complexTensors,u=n.isPacked,null!=o)return void 0,l=u?new Ss(a,bs):new cs(a,bs),p=this.runWebGLProgram(l,[{dataId:t,shape:a,dtype:i}],i),d=this.read(p.dataId),this.disposeData(p.dataId),[2,d];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!f().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===f().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return h=null,"complex64"!==i&&f().get("WEBGL_BUFFER_SUPPORTED")&&(m=this.decode(t),v=this.texData.get(m.dataId),h=(S=this.gpgpu).createBufferFromTexture.apply(S,[v.texture].concat(Yt(a)))),this.pendingRead.set(t,[]),"complex64"===i?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:c.sent(),c.label=2;case 2:return"complex64"!==i?[3,4]:[4,Promise.all([s.real.data(),s.imag.data()])];case 3:return y=c.sent(),x=y[0],b=y[1],g=_a(x,b),[3,5];case 4:null==h?g=this.getValuesFromTexture(t):(w=D(a),g=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)),c.label=5;case 5:return null!=m&&this.disposeData(m.dataId),C=this.convertAndCacheOnCPU(t,g),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach((function(t){return t(C)})),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}}))}))},e.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!Zt(n)){if(f().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},e.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,a=n.dtype,o=n.isPacked,i=D(r);if(f().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var s=this.decode(t),u=this.texData.get(s.dataId),c=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[u.texture].concat(Yt(r))).subarray(0,i);return this.disposeData(s.dataId),c}var l=f().getBool("WEBGL_PACK")&&!0===o,p=l?Te(r):r,d=l?new Jo(p):new Qo(p),h=this.runWebGLProgram(d,[{shape:p,dtype:a,dataId:t}],"float32"),m=this.texData.get(h.dataId),v=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,i);return this.disposeData(h.dataId),v},e.prototype.time=function(t){return u(this,void 0,void 0,(function(){var e,n,r,a,o,i,s;return c(this,(function(u){switch(u.label){case 0:return e=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=O(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),o=O(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,r&&(this.programTimersStack=null),[4,Promise.all(a)];case 1:return i=u.sent(),s={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:R(i),getExtraProfileInfo:function(){return i.map((function(t,e){return{name:o[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,s]}}))}))},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:st(),endMs:null}},e.prototype.endTimer=function(t){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=st(),t)},e.prototype.getQueryTime=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,a=e.texShape,o=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(a,r),this.textureManager.releaseTexture(n,a,o,i)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return f().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Lt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every((function(t){return null==n.texData.get(t.dataId).texture&&t.size<e}))},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.complex=function(t,e){var n=this.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},e.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===D(n))return An([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,a=Zr(t.shape,e,n);if(r||!a){var o=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Zi(n):new Qi(n),i=o.getCustomSetupFunc(e);return this.compileAndRun(o,[t],null,i)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},e.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),a=this.makeOutput(n,t.dtype),o=this.texData.get(a.dataId);Object.assign(o,r),o.shape=n,o.dtype=t.dtype;var i=ta(e,t.strides);r.slice&&(i+=r.slice.flatOffset),o.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,s+1),a},e.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var a=$r(e,n,r);if(a.some((function(t){return 0===t})))return An([],a);var o=new ts(e,r,a);return this.compileAndRun(o,[t])},e.prototype.reverse=function(t,e){var n=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ki(t.shape,e):new qi(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map((function(t){return Tn(t)})),r=t.map((function(t){return kn(t)}));return Rn(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>f().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(t.length/2),o=this.concat(t.slice(0,a),e),i=this.concat(t.slice(a),e);return this.concat([o,i],e)}if(f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var s=new Do(t.map((function(t){return t.shape})),e);return this.compileAndRun(s,t)}var u=Nn(t.map((function(t){return t.shape})),e),c=t.map((function(t){return t.as2D(-1,D(t.shape.slice(e)))})),l=new Oo(c.map((function(t){return t.shape})));return this.compileAndRun(l,c).reshape(u)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ms,t.dtype);var e=new cs(t.shape,ms);return this.compileAndRun(e,[t])},e.prototype.batchMatMul=function(t,e,n,r){var a=n?t.shape[2]:t.shape[1],o=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===a||1===o)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===o?t:t.as3D(s,i,1),c=1===o?2:1,l=1===o?e.as3D(s,1,i):e;return this.multiply(u,l).sum(c,!0)}var p=kt(t.dtype,e.dtype),f=new Oi(t.shape,[s,a,o],n,r);return this.compileAndRun(f,[t,e],p)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,a=t.transposeB,o=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],c=a?n.shape[1]:n.shape[2],l=e.shape[0],p=kt(e.dtype,n.dtype),f=null!=o,d=null!=s,h=i?Rs(i,!0):null,m=new Oi(e.shape,[l,u,c],r,a,f,h,d),v=[e,n];return o&&v.push(o),s&&v.push(s),this.compileAndRun(m,v,p)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),a=new bo("return areal * breal - aimag * bimag;",t.shape,e.shape),o=new bo("return areal * bimag + aimag * breal;",t.shape,e.shape),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],s=this.compileAndRun(a,i),u=this.compileAndRun(o,i),c=this.complex(s,u);return s.dispose(),u.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Eo,t.dtype);var l=new No(Eo,t.shape,e.shape);return this.compileAndRun(l,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,o){var i=[t,e,n],s=null;null!=o&&(s=o.shape,i.push(o));var u=null;if(null!=a&&(u=a.shape,i.push(a)),f().getBool("WEBGL_PACK_NORMALIZATION")){var c=new xo(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,i)}var l=new yo(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,i)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){var o=f().getBool("WEBGL_PACK_NORMALIZATION")?new Ti(t.shape,e,n,r,a):new Ii(t.shape,e,n,r,a);return this.compileAndRun(o,[t])},e.prototype.LRNGrad=function(t,e,n,r,a,o,i){var s=new Ri(e.shape,r,a,o,i);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map((function(t){return lt(t)}));return qa(pr(t.shape,t.dtype,n),e)}var r=new as(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Bi(t.shape,e,n):new Mi(t.shape,e,n);return this.compileAndRun(r,[t])},e.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new is(t.shape,e):new os(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ri(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){T(t.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=Wr(t.shape,e,r),o=zr(a.length,e.length),i=Ur(t.shape,e,r),s=jr(n,e.length),u=Gr(i,n,e.length);return t.reshape(a).transpose(o).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){T(t.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=[[0,0]];a.push.apply(a,n);for(var o=1+e.length;o<t.shape.length;++o)a.push([0,0]);var i=t.pad(a),s=Wr(i.shape,e,r,!1),u=zr(s.length,e.length,!1),c=Ur(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],a=t.shape[1],o=qr(a),i=new Vi({windowSize:o,inSize:a,batchSize:r},e),s=this.compileAndRun(i,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},e.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],a=t.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var o=qr(a),i=new Qa({windowSize:o,inSize:a,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(i,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,a=qr(r[r.length-1]),o=new mo(r,a,e,null==n),i=null==n?[t]:[t,n],s=this.compileAndRun(o,i,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){bn("sum",e,t.rank);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a),i=At(t.dtype);return this.reduce(o,"sum",i).reshape(r)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a),i=At(t.dtype);return this.reduce(o,"prod",i).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,a=wn([r],t.rank),o=t;null!=a&&(o=t.transpose(a),r=En(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],a=t.length,o=0;o<a;o++)o!==e?r.push(t[o]):r.push(n);return r}(o.shape,r,n),s=D([o.shape[r]]),u=o.as2D(-1,s),c=At(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(i);return null!=a&&(l=l.transpose(Cn(a))),l},e.prototype.segOpCompute=function(t,e,n,r,a){var o=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=30?(n=t,r=!0):n=et(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=et(t,n+1);return n}(i,a),u=new Yi({windowSize:s,inSize:i,batchSize:o,numSegments:a},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===a?c:(n=Gn(0,a).tile([i/s]),this.segOpCompute(c,e,n,r,a))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(bn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!f().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var a=yn(t.shape,r),o=a[0],i=D(a[1]),s=t.as2D(-1,i);return this.argReduce(s,n).reshape(o)}return this.argReducePacked(t,n)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var a=new Ho(t.shape,n,r);return this.compileAndRun(a,[t])},e.prototype.equal=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new No("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new No("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new No("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new No("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new No("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new No("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new cs(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new No("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new No("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var r=new $i(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],kt(e.dtype,n.dtype))},e.prototype.where=function(t){pn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return Xa(t.shape,e)},e.prototype.topk=function(t,e,n){return Ka(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){bn("min",e,t.rank);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a);return this.reduce(o,"min",o.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new No("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new No("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);bn("max",e,t.rank);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a);return this.reduce(o,"max",o.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new No("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){bn("all",e,t.rank);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a);return this.reduce(o,"all",o.dtype).reshape(r)},e.prototype.any=function(t,e){bn("any",e,t.rank);var n=yn(t.shape,e),r=n[0],a=D(n[1]),o=t.as2D(-1,a);return this.reduce(o,"any",o.dtype).reshape(r)},e.prototype.squaredDifference=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("return (a - b) * (a - b);",t.shape,e.shape):new No("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.realDivide=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var n=new No("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return this.compileAndRun(n,[t,e],"float32")},e.prototype.floorDiv=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new No("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,wo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=kt(t.dtype,e.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,wo,n);var r=new No(wo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Ss(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,a){void 0===a&&(a=!1);var o=new Ro(n,t.shape,e.shape,a);return this.compileAndRun(o,[t,e],r)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,a=this.texData.get(t.dataId),o=this.texData.get(e.dataId),i=[[a.complexTensors.real,o.complexTensors.real],[a.complexTensors.imag,o.complexTensors.imag]].map((function(a){var o=a[0],i=a[1],s=r.makeComplexComponentTensorInfo(t,o),u=r.makeComplexComponentTensorInfo(e,i),c=new No(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],kt(o.dtype,i.dtype))})),s=i[0],u=i[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>f().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var a=t.map((function(t){return t.dtype})).reduce((function(t,e){return kt(t,e)})),o=t.map((function(t){return t.shape})),i=f().getBool("WEBGL_PACK")?new $a(t[0].shape,o):new Ya(t[0].shape,o);return this.compileAndRun(i,t,a)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Co);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=kt(t.dtype,e.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Co,t.dtype);var r=new No(Co,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new No("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=kt(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,vs,t.dtype);var e=new cs(t.shape,vs);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,gs,t.dtype);var e=new cs(t.shape,gs);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new cs(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new cs(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new cs(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new cs(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new cs(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ys,t.dtype);var e=new cs(t.shape,ys);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,xs,t.dtype);var e=new cs(t.shape,xs);return this.compileAndRun(e,[t])},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new cs(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new cs(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new cs(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new cs(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new cs(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=f().getBool("WEBGL_PACK")?new Ss(t.shape,ws):new cs(t.shape,fs),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=f().getBool("WEBGL_PACK")?new Ss(t.shape,Cs):new cs(t.shape,ds),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro(Io,t.shape,e.shape):new No(So,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Es,t.dtype);var e=new cs(t.shape,hs);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new No("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new cs(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new cs(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,a=(r=f().getBool("WEBGL_PACK_CLIP")?new ko(t.shape):new To(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,a)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ps,t.dtype);var e=new cs(t.shape,ps);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Ao(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new cs(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new cs(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new cs(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ro("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new No("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new cs(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new cs(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new cs(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new cs(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new cs(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new cs(t.shape,function(t){return void 0===t&&(t=0),ls+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,r,a,o){var i=t.shape,s=this.texData.get(t.dataId),u=n.inChannels,c=i[0]*i[1]*i[2],l=n.outChannels,p="channelsLast"===n.dataFormat,d=(1===c||1===l)&&u>1e3,h=i[2]%2!=0&&!!s.isPacked;if(d||!f().getBool("WEBGL_LAZILY_UNPACK")||!f().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!h){var m=p?i[0]*i[1]*i[2]:i[0]*i[2]*i[3],v=this.reshape(t,[1,m,n.inChannels]),g=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:v,b:g,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:o}),n.outShape)}var y=p?i[0]*i[1]*(i[2]+1):i[0]*i[2]*(i[3]+1),x={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},b=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,T(Oe(s.shape,x.shape),(function(){return"packed reshape "+s.shape+" to "+x.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),C=this.fusedBatchMatMul({a:x,b:w,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:o}),E=this.texData.get(C.dataId);return T(E.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=b,E.shape=n.outShape,Lt.makeTensorFromDataId(C.dataId,n.outShape,C.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,a,o){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,p="channelsLast"===n.dataFormat,f=i*s*u,d=l*c,h=[f,d],m=t.squeeze([0]),v=e.reshape([1,f,-1]),g=new Ni(h,m.shape,n),y=this.compileAndRun(g,[m]).reshape([1,h[0],h[1]]),x=null!=r,b=null!=o,w=a?Rs(a,!0):null,C=new Oi(y.shape,[1,d,n.outChannels],!0,!1,x,w,b),E=[y,v];r&&E.push(r),b&&E.push(o);var S=this.compileAndRun(C,E);return p?S.reshape([1,l,c,n.outChannels]):S.reshape([1,n.outChannels,l,c])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,o=t.activation,i=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,a,o,i);if(f().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,a,o,i);var s=null!=a,u=null!=i,c=o?Rs(o,!1):null,l=new Wo(r,s,c,u),p=[e,n];return a&&p.push(a),i&&p.push(i),this.compileAndRun(l,p)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(f().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Wo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Mo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Fo(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,a=t.convInfo,o=t.bias,i=t.activation,s=t.preluActivationWeights,u=f().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels==1,c=i?Rs(i,u):null,l=[n,r],p=null!=o,d=null!=s;return p&&l.push(o),d&&l.push(s),u?(e=new jo(a,p,c,d),this.compileAndRun(e,l)):(e=new Uo(a,p,c,d),this.compileAndRun(e,l))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return f().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new jo(n),this.compileAndRun(r,[t,e])):(r=new Uo(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Vo(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Lo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new zo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new Po(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new Bo(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Pi(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Pi(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var a=new Pi(r,"max",!0),o=this.compileAndRun(a,[e]),i=new ki(r),s=this.compileAndRun(i,[t,o],e.dtype);return o.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new vo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return ka(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),a=0,o=0;o<t.rank;o++)o!==e&&(r[a++]=t.shape[o]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(o=0;o<u.length;o++)i[e]=o,u[o]=this.slice(t,i,s).reshape(r);return u},e.prototype.avgPool3d=function(t,e){var n=new Li(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new go(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new Li(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,r){var a=new Li(r,"max",!0),o=this.compileAndRun(a,[e]),i=new Ai(r),s=this.compileAndRun(i,[t,o],e.dtype);return o.dispose(),s},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!Oe(t.shape,e)&&(null===n.texture||!Oe(n.shape,e))){var r=this.packedReshape(t,e);return Lt.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Aa(t,e)},e.prototype.resizeBilinear=function(t,e,n,r){var a=f().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ji(t.shape,e,n,r):new Ui(t.shape,e,n,r);return this.compileAndRun(a,[t],"float32")},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new zi(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var a=new Hi(t.shape,e,n,r);return this.compileAndRun(a,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Gi(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var a=e?t:ca(t),o=a.shape[0],i=a.shape[1],s=new Di(o,i,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],"int32",u)},e.prototype.oneHot=function(t,e,n,r){var a=new _i(t.size,e,n,r);return this.compileAndRun(a,[t])},e.prototype.diag=function(t){var e=new $o(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,a){return pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Va(t.dataSync(),e.dataSync(),n,r,a)},e.prototype.cropAndResize=function(t,e,n,r,a,o){var i=new Go(t.shape,e.shape,r,a,o);return this.compileAndRun(i,[t,e,n],"float32")},e.prototype.depthToSpace=function(t,e,n){T(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));var r=t.shape[0],a="NHWC"===n?t.shape[1]:t.shape[2],o="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=a*e,u=o*e,c=i/(e*e),l=new Yo("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},e.prototype.split=function(t,e,n){return Ha(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=Kr(0,t,n),a=r.sliceRank,o=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/i,i],l=t.reshape([o,a]),p=e.reshape([o,i]);if(0===u)return Aa(An([]),n);var f=Dn(0),d=new Xi(o,a,l.rank,p.rank,s,c);return this.compileAndRun(d,[p,l,f]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var a=Kr(0,t,n),o=a.sliceRank,i=a.numUpdates,s=a.strides,u=a.outputSize,c=new Xi(i,o,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ei("return real * expR - imag * expI;",t.shape,e),a=new ei("return real * expI + imag * expR;",t.shape,e),o=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],i=this.compileAndRun(r,o),s=this.compileAndRun(a,o),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],a=Hr(t,e),o=a[0],i=a[1],s=a[2],u=a[3],c=e.reshape([i,r]),l=t.reshape([t.size/s,s]),p=new ai(r,u,[i,s]);return this.compileAndRun(p,[l,c]).reshape(o)},e.prototype.fill=function(t,e,n){if("string"===(n=n||Z(e))){var r=j(n,D(t));return r.fill(e),Lt.makeTensor(r,t,n,this)}var a=new ni(t,e),o=a.getCustomSetupFunc(e);return this.compileAndRun(a,[],n,o)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Oa(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Lt.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new Ns(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new Fi(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[Ie(t.shape)].concat(Re(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},a=[Ie(e)].concat(Re(e)),o=new Wi(a,n),i=this.runWebGLProgram(o,[r],t.dtype,null,!0);return{dataId:i.dataId,shape:e,dtype:i.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,a=n.shape,o=n.dtype,i=Te(a);return e=r?new Xo(i):new Ko(i),{dtype:o,shape:a,dataId:this.runWebGLProgram(e,[{shape:i,dtype:o,dataId:t}],o,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,a){var o=this;void 0===a&&(a=!1);var i=this.makeTensorInfo(t.outputShape,n),s=this.texData.get(i.dataId);if(t.packedOutput&&(s.isPacked=!0),t.outPackingScheme===zt.DENSE){var u=Yt(t.outputShape);s.texShape=u.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(s.usage=t.outTexUsage),0===D(i.shape))return s.values=U(i.dtype,0),i;var c=[],l=e.map((function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&D(e.shape)<=f().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?o.unpackTensor(e):o.packTensor(e),c.push(e),n=o.texData.get(e.dataId);else if(n.isPacked&&!Oe(n.shape,e.shape)){var r=e,a=e.shape;e.shape=n.shape,e=o.packedReshape(e,a),c.push(e),n=o.texData.get(e.dataId),r.shape=a}return o.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);var p,d={shape:i.shape,texData:s,isUniform:!1},h=function(t,e,n){var r="";e.concat(n).forEach((function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e}));var a=t.userCode;return t.constructor.name+"_"+r+"_"+a}(t,l,d),m=this.getAndSaveBinary(h,(function(){return function(t,e,n,r){var a=e.userCode,o=n.map((function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}})),i=o.map((function(t){return t.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=ao(o,s,a,e.packedInputs),c=t.createProgram(u),l=null,p=t.getUniformLocation(c,"NAN",!1);1===f().getNumber("WEBGL_VERSION")&&(l=t.getUniformLocation(c,"INFINITY",!1));for(var d={},h=0;h<e.variableNames.length;h++){var m=e.variableNames[h];d[m]=t.getUniformLocation(c,m,!1),d["offset"+m]=t.getUniformLocation(c,"offset"+m,!1)}return{program:e,source:u,webGLProgram:c,uniformLocations:d,inShapeInfos:i,outShapeInfo:s,infLoc:l,nanLoc:p}}(o.gpgpu,t,l,d)})),v=null!=this.activeTimers;if(v&&(p=this.startTimer()),function(t,e,n,r,a){Si(e.inShapeInfos,n),Si([e.outShapeInfo],[r]);var o=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(o,i[0],i[1]):t.setOutputMatrixTexture(o,i[0],i[1]),t.setProgram(e.webGLProgram),1===f().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach((function(n,r){var a=e.program.variableNames[r],o=e.uniformLocations[a],i=e.uniformLocations["offset"+a];if(null!=o)if(n.isUniform)if(D(n.shape)<2)t.gl.uniform1f(o,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(o,s)}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,o,r)})),null!=a&&a(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,m,l,d,r),c.forEach((function(t){return o.disposeData(t.dataId)})),v&&(p=this.endTimer(p),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(p)})),!f().getBool("WEBGL_LAZILY_UNPACK")&&s.isPacked&&!1===a){var g=this.unpackTensor(i);return this.disposeData(i.dataId),g}return i},e.prototype.compileAndRun=function(t,e,n,r,a){void 0===a&&(a=!1),n=n||e[0].dtype;var o=this.runWebGLProgram(t,e,n,r,a);return Lt.makeTensorFromDataId(o.dataId,o.shape,o.dtype)},e.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){var t=this;this.disposed||(f().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((function(e){t.gpgpu.deleteProgram(t.binaryCache[e].webGLProgram),delete t.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},e.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Qe((function(){if(!f().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=f().getBool("DEBUG");f().set("DEBUG",!1);var n=t.abs(Dn(1e-8)).dataSync()[0];if(f().set("DEBUG",e),n>0)return 32}return 16}))),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,a=n.dtype,o=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var c,l=null!=this.activeTimers;l&&(c=st());var p=n.texShape;if(null==p&&(p=ke(r,u),n.texShape=p),null!=o){var f=Te(r),d=void 0,h=p[1],m=p[0],v=o instanceof Uint8Array;u?(h=(e=$t(p[0],p[1]))[0],m=e[1],d=new ti(f,[m,h],v)):d=new Zo(f,[m,h],v);var g=this.makeTensorInfo([m,h],a);this.texData.get(g.dataId).usage=v?Ut.PIXELS:Ut.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),h,m,o);var y=this.runWebGLProgram(d,[g],a,null,!0),x=this.texData.get(y.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(g.dataId),this.texData.delete(y.dataId),n.values=null,l&&(this.uploadWaitMs+=st()-c)}else{var b=this.acquireTexture(p,s,a,u);n.texture=b}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},e.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+a+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*X(e)},e}(fa);Vt()&&Lt.registerBackend("webgl",(function(){return new Ts}),2),b({kernelName:"Square",gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}});var ks=In({square_:function(t){var e=hn(t,"x","square"),n=[e];return Lt.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}}),As=In({abs_:function(t){var e=hn(t,"x","abs");return"complex64"===e.dtype?Lt.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Lt.runKernelFunc((function(t,n){var r=t.abs(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().step(-1))}}}),"Abs")}}),Os=In({acos_:function(t){var e=hn(t,"x","acos");return Lt.runKernelFunc((function(t,n){var r=t.acos(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Dn(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Ds=In({acosh_:function(t){var e=hn(t,"x","acosh");return Lt.runKernelFunc((function(t,n){var r=t.acosh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}}))}}),_s=In({asin_:function(t){var e=hn(t,"x","asin");return Lt.runKernelFunc((function(t,n){var r=t.asin(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Dn(1).sub(n.toFloat().square()).sqrt())}}}))}}),Fs=In({asinh_:function(t){var e=hn(t,"x","asinh");return Lt.runKernelFunc((function(t,n){var r=t.asinh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Dn(1).add(n.toFloat().square()).sqrt())}}}))}}),Ms=In({atan_:function(t){var e=hn(t,"x","atan");return Lt.runKernelFunc((function(t,n){var r=t.atan(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}}))}}),Bs=In({atanh_:function(t){var e=hn(t,"x","atanh");return Lt.runKernelFunc((function(t,n){var r=t.atanh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(Dn(1).sub(n.toFloat().square()))}}}))}}),Ps=In({ceil_:function(t){var e=hn(t,"x","ceil");return Lt.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),Ls=In({clipByValue_:function(t,e,n){var r=hn(t,"x","clipByValue");T(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var a=[r],o={min:e,max:n};return Lt.runKernelFunc((function(t,a){var o=t.clip(r,e,n);return a([r]),o}),{x:r},(function(t,r){var a=r[0];return{x:function(){return t.where(a.greaterEqual(e).logicalAnd(a.lessEqual(n)),qn(t))}}}),"ClipByValue",o,a)}}),Vs=In({cos_:function(t){var e=hn(t,"x","cos"),n=[e];return Lt.runKernelFunc((function(t,n){var r=t.cos(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return n.toFloat().sin().neg().mul(t)}}}),"Cos",{},n)}}),Ws=In({cosh_:function(t){var e=hn(t,"x","cosh");return Lt.runKernelFunc((function(t,n){var r=t.cosh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}}))}}),zs=In({erf_:function(t){var e=hn(t,"x","erf");return T("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Lt.runKernelFunc((function(t,n){var r=t.erf(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),Us=In({exp_:function(t){var e=hn(t,"x","exp");return Lt.runKernelFunc((function(t,n){var r=t.exp(e);return n([r]),r}),{x:e},(function(t,e){return{x:function(){return t.mulStrict(e[0])}}}),"Exp",{},[],[!0])}}),js=In({expm1_:function(t){var e=hn(t,"x","expm1");return Lt.runKernelFunc((function(t,n){var r=t.expm1(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}}))}}),Gs=In({floor_:function(t){var e=hn(t,"x","floor");return Lt.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),Hs=In({log_:function(t){var e=hn(t,"x","log"),n=[e];return Lt.runKernelFunc((function(t,n){var r=t.log(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.div(n.toFloat())}}}),"Log",{},n)}}),qs=In({log1p_:function(t){var e=hn(t,"x","log1p");return Lt.runKernelFunc((function(t,n){var r=t.log1p(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}}))}}),Ks=In({logSigmoid_:function(t){var e=hn(t,"x","logSigmoid");return Lt.runKernelFunc((function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}}))}}),Xs=In({neg_:function(t){var e=hn(t,"x","neg");return Lt.runKernelFunc((function(t){return t.neg(e)}),{$x:e},(function(t){return{$x:function(){return t.neg()}}}))}}),Ys=In({reciprocal_:function(t){var e=hn(t,"x","reciprocal");return Lt.runKernelFunc((function(t,n){var r=t.reciprocal(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}}))}}),$s=In({round_:function(t){var e=hn(t,"x","round");return Lt.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),Qs=In({rsqrt_:function(t){var e=hn(t,"x","rsqrt"),n=[e];return Lt.runKernelFunc((function(t,n){var r=t.rsqrt(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}}),"Rsqrt",{},n)}}),Js=In({sigmoid_:function(t){var e=hn(t,"x","sigmoid");return Lt.runKernelFunc((function(t,n){var r=t.sigmoid(e);return n([r]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mul(n.mul(Dn(1).sub(n)))}}}),"Sigmoid")}}),Zs=In({sign_:function(t){var e=hn(t,"x","sign");return Lt.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),tu=In({isNaN_:function(t){var e=hn(t,"x","isNaN");return Lt.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),eu=In({isInf_:function(t){var e=hn(t,"x","isInf");return Lt.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),nu=In({isFinite_:function(t){var e=hn(t,"x","isFinite");return Lt.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return qn(t)}}}))}}),ru=In({sin_:function(t){var e=hn(t,"x","sin"),n=[e];return Lt.runKernelFunc((function(t,n){var r=t.sin(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return n.toFloat().cos().mul(t)}}}),"Sin",{},n)}}),au=In({sinh_:function(t){var e=hn(t,"x","sinh");return Lt.runKernelFunc((function(t,n){var r=t.sinh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}}))}}),ou=In({softplus_:function(t){var e=hn(t,"x","softplus");return Lt.runKernelFunc((function(t,n){var r=t.softplus(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}}))}}),iu=In({sqrt_:function(t){var e=hn(t,"x","sqrt");return Lt.runKernelFunc((function(t,n){var r=t.sqrt(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}}))}}),su=In({step_:function(t,e){void 0===e&&(e=0);var n=hn(t,"x","step");return Lt.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return qn(t)}}}))}}),uu=In({tan_:function(t){var e=hn(t,"x","tan");return Lt.runKernelFunc((function(t,n){var r=t.tan(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}}))}}),cu=In({tanh_:function(t){var e=hn(t,"x","tanh");return Lt.runKernelFunc((function(t,n){var r=t.tanh(e);return n([r]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return Dn(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}});function lu(t,e,n,r,a,o){var i,s,u=hn(t,"x","batchNorm"),c=hn(e,"mean","batchNorm"),l=hn(n,"variance","batchNorm");return null!=a&&(i=hn(a,"scale","batchNorm")),null!=r&&(s=hn(r,"offset","batchNorm")),T(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),T(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),T(2===l.rank||1===l.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."})),null!=i&&T(2===i.rank||1===i.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),du(u,c,l,s,i,o)}function pu(t,e,n,r,a,o){var i,s,u=hn(t,"x","batchNorm"),c=hn(e,"mean","batchNorm"),l=hn(n,"variance","batchNorm");return null!=a&&(i=hn(a,"scale","batchNorm")),null!=r&&(s=hn(r,"offset","batchNorm")),T(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),T(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),T(3===l.rank||1===l.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."})),null!=i&&T(3===i.rank||1===i.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),du(u,c,l,s,i,o)}function fu(t,e,n,r,a,o){var i,s,u=hn(t,"x","batchNorm"),c=hn(e,"mean","batchNorm"),l=hn(n,"variance","batchNorm");return null!=a&&(i=hn(a,"scale","batchNorm")),null!=r&&(s=hn(r,"offset","batchNorm")),T(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),T(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),T(4===l.rank||1===l.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."})),null!=i&&T(4===i.rank||1===i.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."})),null!=s&&T(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),du(u,c,l,s,i,o)}function du(t,e,n,r,a,o){null==o&&(o=.001);var i,s,u,c=hn(t,"x","batchNorm"),l=hn(e,"mean","batchNorm"),p=hn(n,"variance","batchNorm");null!=a&&(i=hn(a,"scale","batchNorm")),null!=r&&(s=hn(r,"offset","batchNorm")),T(l.rank===p.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),T(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),T(null==i||l.rank===i.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."})),u=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var f=[c,l,p,i];return Lt.runKernelFunc((function(t,e){var n=t.batchNormalization(u,hu(l),hu(p),o,hu(i),hu(s));return e([c,l,p,i]),n}),{x:c,mean:l,variance:p,scale:i,offset:s},(function(t,e){var n=e,r=n[0],a=n[1],i=n[2],s=n[3],c=null==s?Dn(1):s,l=ma(a.shape,u.shape),p=[];if(1===a.rank){for(var f=0;f<u.shape.length-1;++f)p.push(u.shape[f]);p.push(1)}var d=r.sub(a),h=t.mul(c),m=Qs(i.add(Dn(o))),v=m.mul(m).mul(m).mul(Dn(-.5));return{x:function(){return 1===a.rank?t.mul(Br(m.as4D(1,1,1,a.shape[0]),p)).mul(c).reshape(r.shape):t.mul(m).mul(c).reshape(r.shape)},mean:function(){var t=m.mul(Dn(-1)).mul(h);return 1===a.rank&&(t=t.sum(l)),t.reshape(a.shape)},variance:function(){var t=v.mul(d).mul(h);return 1===a.rank&&(t=t.sum(l)),t.reshape(a.shape)},scale:function(){var e=d.mul(m),n=t.mul(e);return 1===a.rank&&(n=n.sum(l)),n.reshape(a.shape)},offset:function(){var e=t;return 1===a.rank&&(e=e.sum(l)),e.reshape(a.shape)}}}),"BatchNormalization",{varianceEpsilon:o},f).reshape(c.shape)}function hu(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function mu(){qe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var vu=In({batchNormalization2d_:function(t,e,n,r,a,o){return void 0===r&&(r=.001),mu(),lu(t,e,n,o,a,r)}}),gu=In({batchNormalization3d_:function(t,e,n,r,a,o){return void 0===r&&(r=.001),mu(),pu(t,e,n,o,a,r)}}),yu=In({batchNormalization4d_:function(t,e,n,r,a,o){return void 0===r&&(r=.001),mu(),fu(t,e,n,o,a,r)}}),xu=In({batchNormalization_:function(t,e,n,r,a,o){return void 0===r&&(r=.001),mu(),du(t,e,n,o,a,r)}}),bu=In({batchNorm_:du}),wu=In({batchNorm2d_:lu}),Cu=In({batchNorm3d_:pu}),Eu=In({batchNorm4d_:fu}),Su=In({logicalAnd_:function(t,e){var n=hn(t,"a","logicalAnd","bool"),r=hn(e,"b","logicalAnd","bool");return va(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Nu=In({logicalNot_:function(t){var e=hn(t,"x","logicalNot","bool");return Lt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),Iu=In({logicalOr_:function(t,e){var n=hn(t,"a","logicalOr","bool"),r=hn(e,"b","logicalOr","bool");return va(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),Ru=In({logicalXor_:function(t,e){var n=hn(t,"a","logicalXor","bool"),r=hn(e,"b","logicalXor","bool");return va(n.shape,r.shape),Iu(t,e).logicalAnd(Su(t,e).logicalNot())}}),Tu=In({where_:function(t,e,n){var r=hn(e,"a","where"),a=hn(n,"b","where"),o=hn(t,"condition","where","bool");return k(r.shape,a.shape,"Error in where: "),1===o.rank?T(o.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):k(o.shape,a.shape,"Error in where: "),Lt.runKernelFunc((function(t,e){var n=t.select(o,r,a);return e([o]),n}),{$condition:o,$a:r,$b:a},(function(t,e){var n=e[0];return{$condition:function(){return qn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),ku=function(t){return u(this,void 0,void 0,(function(){var e,n,r;return c(this,(function(a){switch(a.label){case 0:return[4,(e=hn(t,"condition","whereAsync","bool")).data()];case 1:return n=a.sent(),r=Xa(e.shape,n),t!==e&&e.dispose(),[2,r]}}))}))},Au=In({add_:function(t,e){var n,r=hn(t,"a","add"),a=hn(e,"b","add");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t){return t.add(r,a)}),{a:r,b:a},(function(t){return{a:function(){var e=t,n=ma(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=ma(a.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(a.shape)}}}),"Add")}}),Ou=In({addN_:function(t){T(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),T(t.length>=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length}));var e=t.map((function(t,e){return hn(t,"tensors"+e,"addN")})),n=e[0];e.forEach((function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),e.forEach((function(t){if(!_(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Lt.runKernelFunc((function(t){return t.addN(e)}),r,(function(t){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}),"AddN")}}),Du=In({addStrict_:function(t,e){var n=hn(t,"a","addStrict"),r=hn(e,"b","addStrict");return k(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),_u=In({atan2_:function(t,e){var n,r=hn(t,"a","atan2"),a=hn(e,"b","atan2");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t,e){var n=t.atan2(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Au(n.square(),r.square()),a=t.mul(r.div(e)),i=ma(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape)},$b:function(){var e=Au(n.square(),r.square()),a=Xs(t.mul(n.div(e))),i=ma(r.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(r.shape)}}}))}}),Fu=In({div_:function(t,e){var n,r=hn(t,"a","div"),a=hn(e,"b","div");if(n=Ot(r,a),r=n[0],a=n[1],"int32"===r.dtype&&"int32"===a.dtype)return Pu(r,a);var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t,e){var n=t.realDivide(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),a=ma(n.shape,o);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=ma(r.shape,o);a.length>0&&(e=e.sum(a).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"Div")}}),Mu=In({divNoNan_:function(t,e){var n,r=hn(t,"a","div"),a=hn(e,"b","div");r=(n=Ot(r,a))[0],a=n[1];var o=Fu(r,a),i=qn(o),s=a.equal(i);return Tu(s,i,o)}}),Bu=In({divStrict_:function(t,e){var n=hn(t,"a","div"),r=hn(e,"b","div");return k(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Pu=In({floorDiv_:function(t,e){var n,r=hn(t,"a","floorDiv"),a=hn(e,"b","floorDiv");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t,e){var n=t.floorDiv(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),a=ma(n.shape,o);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=ma(r.shape,o);a.length>0&&(e=e.sum(a).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"FloorDiv")}}),Lu=In({maximum_:function(t,e){var n,r=hn(t,"a","maximum"),a=hn(e,"b","maximum");return n=Ot(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),va(r.shape,a.shape),Lt.runKernelFunc((function(t,e){var n=t.maximum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.greaterEqual(r).toFloat())},b:function(){return t.mul(n.less(r).toFloat())}}}),"Maximum")}}),Vu=In({maximumStrict_:function(t,e){var n=hn(t,"a","maximumStrict"),r=hn(e,"b","maximumStrict");return k(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Wu=In({minimum_:function(t,e){var n,r=hn(t,"a","minimum"),a=hn(e,"b","minimum");return n=Ot(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),va(r.shape,a.shape),Lt.runKernelFunc((function(t,e){var n=t.minimum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.lessEqual(r).toFloat())},b:function(){return t.mul(n.greater(r).toFloat())}}}),"Minimum")}}),zu=In({minimumStrict_:function(t,e){var n=hn(t,"a","minimumStrict"),r=hn(e,"b","minimumStrict");return k(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Uu=In({mod_:function(t,e){var n,r=hn(t,"a","mod"),a=hn(e,"b","mod");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t,e){var n=t.mod(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=ma(n.shape,o);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),a=ma(r.shape,o);return a.length>0?e.sum(a).reshape(r.shape):e}}}))}}),ju=In({modStrict_:function(t,e){var n=hn(t,"a","modStrict"),r=hn(e,"b","modStrict");return k(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Gu=In({mul_:function(t,e){var n,r=hn(t,"a","mul"),a=hn(e,"b","mul");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t,e){var n=t.multiply(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),a=ma(n.shape,o);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=ma(r.shape,o);return a.length>0?e.sum(a).reshape(r.shape):e}}}),"Mul")}}),Hu=In({mulStrict_:function(t,e){var n=hn(t,"a","mul"),r=hn(e,"b","mul");return k(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),qu=In({pow_:function(t,e){var n=hn(t,"base","pow"),r=hn(e,"exp","pow"),a=va(n.shape,r.shape);return t=n.cast(kt(n.dtype,r.dtype)),e=r.cast(kt(n.dtype,r.dtype)),Lt.runKernelFunc((function(t,e){var a=t.pow(n,r);return e([n,r,a]),a}),{$base:n,$exp:r},(function(t,e){var n=e[0],r=e[1],o=e[2];return{$base:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(Dn(1))))),i=ma(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$exp:function(){var e=n.greater(0),i=n.log().where(e,qn(n)),s=t.mul(o.mul(i)),u=ma(r.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}))}}),Ku=In({powStrict_:function(t,e){return k(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Xu=In({squaredDifference_:function(t,e){var n,r=hn(t,"a","squaredDifference"),a=hn(e,"b","squaredDifference");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t,e){var n=t.squaredDifference(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1],a=Dn(2);return{$a:function(){return t.mul(n.sub(r).mul(a))},$b:function(){return t.mul(r.sub(n).mul(a))}}}))}}),Yu=In({squaredDifferenceStrict_:function(t,e){var n=hn(t,"a","squaredDifferenceStrict"),r=hn(e,"b","squaredDifferenceStrict");return k(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),$u=In({sub_:function(t,e){var n,r=hn(t,"a","sub"),a=hn(e,"b","sub");n=Ot(r,a),r=n[0],a=n[1];var o=va(r.shape,a.shape);return Lt.runKernelFunc((function(t){return t.subtract(r,a)}),{a:r,b:a},(function(t){return{a:function(){var e=t,n=ma(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=ma(a.shape,o);return n.length>0&&(e=e.sum(n)),e.neg().reshape(a.shape)}}}),"Sub")}}),Qu=In({subStrict_:function(t,e){var n=hn(t,"a","subStrict"),r=hn(e,"b","subStrict");return k(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),Ju=In({equal_:function(t,e){var n,r=hn(t,"a","equal"),a=hn(e,"b","equal");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t){return t.equal(r,a)}),{$a:r,$b:a})}}),Zu=In({equalStrict_:function(t,e){var n=hn(t,"a","equalStrict"),r=hn(e,"b","equalStrict");return k(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),tc=In({greater_:function(t,e){var n,r=hn(t,"a","greater"),a=hn(e,"b","greater");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t){return t.greater(r,a)}),{a:r,b:a},null,"Greater")}}),ec=In({greaterEqual_:function(t,e){var n,r=hn(t,"a","greaterEqual"),a=hn(e,"b","greaterEqual");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t,e){var n=t.greaterEqual(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return qn(n)},b:function(){return qn(r)}}}),"GreaterEqual")}}),nc=In({greaterEqualStrict_:function(t,e){var n=hn(t,"a","greaterEqualStrict"),r=hn(e,"b","greaterEqualStrict");return k(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),rc=In({greaterStrict_:function(t,e){var n=hn(t,"a","greaterStrict"),r=hn(e,"b","greaterStrict");return k(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),ac=In({less_:function(t,e){var n,r=hn(t,"a","less"),a=hn(e,"b","less");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t){return t.less(r,a)}),{a:r,b:a},null,"Less")}}),oc=In({lessEqual_:function(t,e){var n,r=hn(t,"a","lessEqual"),a=hn(e,"b","lessEqual");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t,e){var n=t.lessEqual(r,a);return e([r,a]),n}),{a:r,b:a},null,"LessEqual")}}),ic=In({lessEqualStrict_:function(t,e){var n=hn(t,"a","lessEqualStrict"),r=hn(e,"b","lessEqualStrict");return k(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),sc=In({lessStrict_:function(t,e){var n=hn(t,"a","lessStrict"),r=hn(e,"b","lessStrict");return k(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),uc=In({notEqual_:function(t,e){var n,r=hn(t,"a","notEqual"),a=hn(e,"b","notEqual");return n=Ot(r,a),r=n[0],a=n[1],va(r.shape,a.shape),Lt.runKernelFunc((function(t){return t.notEqual(r,a)}),{$a:r,$b:a})}}),cc=In({notEqualStrict_:function(t,e){var n=hn(t,"a","notEqualStrict"),r=hn(e,"b","notEqualStrict");return k(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function lc(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function pc(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var fc=In({gather_:function(t,e,n){void 0===n&&(n=0);var r=hn(t,"x","gather"),a=hn(e,"indices","gather","int32");n=W(n,r.shape)[0];var o=function(t,e,n){for(var r=t.shape[n],a=[],o=1,i=1,s=0;s<n;s++)a.push(t.shape[s]),o*=t.shape[s];for(s=0;s<e.rank;s++)a.push(e.shape[s]);for(s=n+1;s<t.rank;s++)a.push(t.shape[s]),i*=t.shape[s];return{batchSize:o,sliceSize:i,dimSize:r,outputShape:a}}(r,a,n);return Lt.runKernelFunc((function(t,e){var o=t.gather(r,a.flatten(),n);return e([a]),o}),{$x:r},(function(t,e){var a=e[0];return{$x:function(){var e=r.shape,o=a.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),c=u.length,l=lc(0,s),p=lc(s+1,s+1+c),f=pc([i,[o],u]),d=t.reshape(f),h=a.reshape([o]),m=pc([[s],l,p]),v=d.transpose(m),g=dc(v,h,r.shape[n]),y=Cn(m);return g.transpose(y)}}})).reshape(o.outputShape)}}),dc=In({unsortedSegmentSum_:function(t,e,n){var r=hn(t,"x","unsortedSegmentSum"),a=hn(e,"segmentIds","unsortedSegmentSum","int32");return T(F(n),(function(){return"numSegments must be of dtype int"})),Lt.runKernelFunc((function(t,e){var o=t.unsortedSegmentSum(r,a,n);return e([a]),o}),{$x:r},(function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=Lu(e,qn(e)),r=fc(t,n),a=ec(e,Dn(0,"int32")),o=r.rank-a.rank,i=0;i<o;++i)a=xr(a,i+1);a=Su(a,Wn(r.shape,"bool"));var s=qn(r);return Tu(a,r,s)}(t,n)}}}))}}),hc=function(t,e,n){return u(this,void 0,void 0,(function(){var r,a,o,i,s,u,l,p,f,d,h,m,v;return c(this,(function(c){switch(c.label){case 0:for(r=hn(t,"tensor","boolMask"),a=hn(e,"mask","boolMask","bool"),o=null==n?0:n,i=a.rank,s=r.shape,T(i>0,(function(){return"mask cannot be scalar"})),k(s.slice(o,o+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,l=o;l<o+i;l++)u*=s[l];return p=s.slice(0,o).concat([u],s.slice(o+i)),f=r.reshape(p),d=a.reshape([-1]),[4,ku(d)];case 1:return h=c.sent(),m=h.squeeze([1]),v=fc(f,m,o),t!==r&&r.dispose(),e!==a&&a.dispose(),m.dispose(),f.dispose(),d.dispose(),h.dispose(),[2,v]}}))}))};function mc(t,e,n,r,a,o,i){void 0===o&&(o="NHWC"),T(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var s=t,u=e,c=!1;3===e.rank&&(c=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),T(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),T(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),T(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var l="NHWC"===o?s[3]:s[1],p="NHWC"===o?u.shape[3]:u.shape[1];T(l===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."})),T(p===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+p+") must match output depth for filter "+n.shape[3]+"."})),null!=i&&T(F(a),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var f=Ta(o),d=xa(s,n.shape,r,1,a,i,!1,f),h=Lt.runKernelFunc((function(t,e){var r=t.conv2dDerInput(u,n,d);return e([n,u]),r}),{dy4D:u,filter:n},(function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return xc(t,n,r,a,o,1,i)},filter:function(){return wc(t,s,n.shape,r,a,o,i)}}}));return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function vc(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],a=e[2];return 1===n&&1===r&&1===a}function gc(t,e,n,r,a){T(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var o=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),o=[1,t[0],t[1],t[2],t[3]]);var u=o[4],c=i.shape[4];T(5===o.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."})),T(5===i.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank})),T(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),T(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),T(c===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."}));var l=ba(o,n.shape,r,1,a),p=Lt.runKernelFunc((function(t){return t.conv3dDerInput(i,n,l)}),{dy5D:i});return s?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}var yc=In({conv1d_:function(t,e,n,r,a,o,i){void 0===a&&(a="NWC"),void 0===o&&(o=1);var s=hn(t,"x","conv1d"),u=hn(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),T(3===c.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."})),T(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=i&&T(F(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."})),T(c.shape[2]===u.shape[1],(function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."})),T(Ra(n,o),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+o+"'"})),T("NWC"===a,(function(){return"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported."}));var p=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),f=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),d=xc(f,p,[1,n],r,"NHWC",[1,o],i);return l?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}}),xc=In({conv2d_:function(t,e,n,r,a,o,i){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1]);var s=hn(t,"x","conv2d"),u=hn(e,"filter","conv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),T(4===c.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."})),T(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=i&&T(F(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var p="NHWC"===a?c.shape[3]:c.shape[1];T(p===u.shape[2],(function(){return"Error in conv2d: depth of input ("+p+") must match input depth for filter "+u.shape[2]+"."})),T(Ra(n,o),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}));var f=Ta(a),d=xa(c.shape,u.shape,n,o,r,i,!1,f),h=[u,c],m=Lt.runKernelFunc((function(t,e){var n=t.conv2d(c,u,d);return e([u,c]),n}),{x:c,filter:u},(function(t,e){var i=e,s=i[0],u=i[1];return T(Ia(o),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"})),{x:function(){return Cc(u.shape,t,s,n,r,a)},filter:function(){return wc(u,t,s.shape,n,r,a)}}}),"Conv2D",d,h);return l?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),bc=In({conv3d_:function(t,e,n,r,a,o){void 0===a&&(a="NDHWC"),void 0===o&&(o=[1,1,1]);var i=hn(t,"x","conv3d"),s=hn(e,"filter","conv3d"),u=i,c=!1;4===i.rank&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),T(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),T(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),T(u.shape[4]===s.shape[3],(function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."})),T(function(t,e){return vc(t)||vc(e)}(n,o),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),T("NDHWC"===a,(function(){return"Error in conv3d: got dataFormat of "+a+" but only NDHWC is currently supported."}));var l=ba(u.shape,s.shape,n,o,r),p=Lt.runKernelFunc((function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){T(vc(o),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"}));var a=e[0],i=e[1];return{x:function(){return gc(a.shape,t,i,n,r)},$filter:function(){return function(t,e,n,r,a){var o=t;4===t.rank&&(o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),T(5===o.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+o.shape+"."})),T(5===i.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."})),T(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),T(o.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+o.shape[4]+") must match input depth in filter ("+n[3]+"."})),T(i.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=ba(o.shape,n,r,1,a);return Lt.runKernelFunc((function(t){return t.conv3dDerFilter(o,i,s)}),{x5D:o,dy5D:i})}(a,t,i.shape,n,r)}}}));return c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),wc=In({conv2dDerFilter_:function(t,e,n,r,a,o,i){void 0===o&&(o="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),T(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),T(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),T(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var c="NHWC"===o?s.shape[3]:s.shape[1],l="NHWC"===o?u.shape[3]:u.shape[1];T(c===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."})),T(l===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."})),null!=i&&T(F(a),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var p=Ta(o),f=xa(s.shape,n,r,1,a,i,!1,p);return Lt.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,f)}),{x4D:s,dy4D:u})}}),Cc=In({conv2dDerInput_:mc}),Ec=In({depthwiseConv2d_:function(t,e,n,r,a,o,i){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1]);var s=hn(t,"x","depthwiseConv2d"),u=hn(e,"filter","depthwiseConv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),T(4===c.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."})),T(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),T(c.shape[3]===u.shape[2],(function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."})),null==o&&(o=[1,1]),T(Ra(n,o),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=i&&T(F(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var p=xa(c.shape,u.shape,n,o,r,i,!0),f=[c,u],d=Lt.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(c,u,p);return e([c,u]),n}),{x:c,filter:u},(function(t,e){T(Ia(o),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"}));var n=e[0],r=e[1];return{x:function(){return Sc(n.shape,t,r,p)},filter:function(){return Nc(n,t,r.shape,p)}}}),"DepthwiseConv2dNative",p,f);return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}}),Sc=In({depthwiseConv2dDerInput_:function(t,e,n,r){var a=e,o=!1;3===e.rank&&(o=!0,a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(a,n,r)}),{dy4D:a});return o?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),Nc=In({depthwiseConv2dDerFilter_:function(t,e,n,r){var a=t;3===t.rank&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=e;return 3===o.rank&&(o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(a,o,r)}),{x4D:a,dy4D:o})}}),Ic=In({separableConv2d_:function(t,e,n,r,a,o,i){void 0===o&&(o=[1,1]),void 0===i&&(i="NHWC");var s=hn(t,"x","separableConv2d"),u=hn(e,"depthwiseFilter","separableConv2d"),c=hn(n,"pointwiseFilter","separableConv2d"),l=s,p=!1;if(3===s.rank&&(p=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");T(4===l.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."})),T(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),T(4===c.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),T(1===c.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."})),T(1===c.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."}));var f=u.shape[2],d=u.shape[3];T(c.shape[2]===f*d,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+f*d+", but got "+c.shape[2]+"."}));var h=Ec(l,u,r,a,i,o),m=xc(h,c,1,"valid",i);return p?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Rc=In({conv2dTranspose_:function(t,e,n,r,a,o){return mc(n,hn(t,"x","conv2dTranspose"),hn(e,"filter","conv2dTranspose"),r,a,"NHWC",o)}}),Tc=In({conv3dTranspose_:function(t,e,n,r,a){return gc(n,hn(t,"x","conv3dTranspose"),hn(e,"filter","conv3dTranspose"),r,a)}}),kc=In({matMul_:function(t,e,n,r){var a;void 0===n&&(n=!1),void 0===r&&(r=!1);var o=hn(t,"a","matMul"),i=hn(e,"b","matMul");a=Ot(o,i),o=a[0],i=a[1];var s=n?o.shape[o.rank-2]:o.shape[o.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?o.shape[o.rank-1]:o.shape[o.rank-2],l=r?i.shape[i.rank-2]:i.shape[i.rank-1],p=o.shape.slice(0,-2),f=i.shape.slice(0,-2),d=D(p),h=D(f);T(o.rank>=2&&i.rank>=2&&o.rank===i.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+i.rank+"."})),T(_(p,f),(function(){return"Error in matMul: outer dimensions ("+p+") and ("+f+") of Tensors with shapes "+o.shape+" and "+i.shape+" must match."})),T(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var m=o.shape.slice(0,-2).concat([c,l]),v=n?o.as3D(d,s,c):o.as3D(d,c,s),g=r?i.as3D(h,l,u):i.as3D(h,u,l),y={transposeA:n,transposeB:r};return Lt.runKernelFunc((function(t,e){var a=t.batchMatMul(v,g,n,r);return e([v,g]),a}),{a:v,b:g},(function(t,e){var a=e,o=a[0],i=a[1];return n||r?!n&&r?{a:function(){return t.matMul(i,!1,!1)},b:function(){return t.matMul(o,!0,!1)}}:n&&!r?{a:function(){return i.matMul(t,!1,!0)},b:function(){return o.matMul(t,!1,!1)}}:{a:function(){return i.matMul(t,!0,!0)},b:function(){return t.matMul(o,!0,!0)}}:{a:function(){return t.matMul(i,!1,!0)},b:function(){return o.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(m)}}),Ac=In({dot_:function(t,e){var n=hn(t,"t1","dot"),r=hn(e,"t2","dot");T(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."}));var a=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];return T(a===o,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+o+"."})),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Oc=In({outerProduct_:function(t,e){var n=hn(t,"v1","outerProduct"),r=hn(e,"v2","outerProduct");return T(1===n.rank&&1===r.rank,(function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."})),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Dc=In({reverse_:function(t,e){var n=hn(t,"x","reverse");if(0===n.rank)return n.clone();var r=W(e,n.shape);return Lt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),_c=In({reverse1d_:function(t){var e=hn(t,"x","reverse");return T(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),Dc(e,0)}}),Fc=In({reverse2d_:function(t,e){var n=hn(t,"x","reverse");return T(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),Dc(n,e)}}),Mc=In({reverse3d_:function(t,e){var n=hn(t,"x","reverse");return T(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),Dc(n,e)}}),Bc=In({reverse4d_:function(t,e){var n=hn(t,"x","reverse");return T(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),Dc(n,e)}});function Pc(t,e,n,r,a,o){var i=hn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),T(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),T(Ra(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=o&&T(F(a),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."}));var c=ga(s.shape,e,n,r,a,o);if(1===c.filterWidth&&1===c.filterHeight&&_(c.inShape,c.outShape))return i.clone();var l=[s],p=Lt.runKernelFunc((function(t,e){var n=t.maxPool(s,c);return e([s,n]),n}),{x:s},(function(t,o){var i=o[0],s=o[1];return{x:function(){return function(t,e,n,r,a,o,i,s){var u=hn(t,"dy","maxPoolBackprop"),c=hn(e,"input","maxPoolBackprop"),l=hn(n,"output","maxPoolBackprop");T(c.rank===u.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"})),null==o&&(o=[1,1]),T(Ra(a,o),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"})),T(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),T(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."}));var p=ga(c.shape,r,a,o,i,s);return Lt.runKernelFunc((function(t){return t.maxPoolBackprop(u,c,l,p)}),{$dy:u,$input:c})}(t,i,s,e,n,r,a)}}}),"MaxPool",c,l);return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function Lc(t,e,n,r,a,o){var i=hn(t,"x","avgPool","float32");null==r&&(r=[1,1]),T(Ra(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=o&&T(F(a),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."}));var c=ga(s.shape,e,n,r,a,o);if(1===c.filterWidth&&1===c.filterHeight&&_(c.inShape,c.outShape))return i.clone();var l=Lt.runKernelFunc((function(t){return t.avgPool(s,c)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,a,o){var i=hn(t,"dy","avgPoolBackprop"),s=hn(e,"input","avgPoolBackprop");T(s.rank===i.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"})),null==a&&(a=[1,1]),T(Ra(r,a),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'"}));var u=s,c=i,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),T(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var p=ga(u.shape,n,r,a,o),f=Lt.runKernelFunc((function(t){return t.avgPoolBackprop(c,u,p)}),{dy4D:c,input4D:u});return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(t,s,e,n,r,a)}}}),"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var Vc=In({maxPool_:function(t,e,n,r,a){return Pc(t,e,n,1,r,a)}}),Wc=In({avgPool_:function(t,e,n,r,a){return Lc(t,e,n,1,r,a)}}),zc=In({pool_:function(t,e,n,r,a,o){null==a&&(a=[1,1]),null==o&&(o=1),0===r&&(r="valid");var i=hn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),T(Ra(o,a),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}));var c,l=ga(s.shape,e,o,a,r),p=[l.dilationHeight,l.dilationWidth];c="same"===r?function(t,e){var n=t.map((function(t,n){return t+(t-1)*(e[n]-1)})).map((function(t){return t-1})),r=n.map((function(t){return Math.floor(t/2)})),a=n.map((function(t,e){return t-r[e]}));return n.map((function(t,e){return[r[e],a[e]]}))}([l.filterHeight,l.filterWidth],p):[[0,0],[0,0]];var f=1===p[0]&&1===p[1],d=function(t,e,n){var r=n.map((function(t){return t[0]})),a=n.map((function(t){return t[1]})),o=t.concat(r,a),i=e.map((function(t,e){return(t-o[e]%t)%t})),s=a.map((function(t,e){return t+i[e]}));return[e.map((function(t,e){return[r[e],s[e]]})),e.map((function(t,e){return[0,i[e]]}))]}([l.inHeight,l.inWidth],p,c),h=d[0],m=d[1],v=f?r:"valid",g=f?s:_r(s,p,h),y=("avg"===n?function(){return Lc(g,e,o,1,v)}:function(){return Pc(g,e,o,1,v)})(),x=f?y:dr(y,p,m);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),Uc=In({maxPool3d_:function(t,e,n,r,a,o,i){void 0===o&&(o="NDHWC");var s=hn(t,"x","maxPool3d"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),T(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),T("NDHWC"===o,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+o})),T(Ra(n,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=a&&T(F(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var l=ya(u.shape,e,n,i,r,a,o),p=Lt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,l);return e([u,n]),n}),{x:u},(function(t,o){var s=o[0],u=o[1];return{x:function(){return function(t,e,n,r,a,o,i,s){var u=hn(t,"dy","maxPool3dBackprop"),c=hn(e,"input","maxPool3dBackprop"),l=hn(n,"output","maxPool3dBackprop"),p=u,f=c,d=l,h=!1;4===c.rank&&(h=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),d=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3])),T(5===p.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."})),T(5===f.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."})),T(5===d.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."})),null==o&&(o=[1,1,1]),T(Ra(a,o),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"})),null!=s&&T(F(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var m=ya(f.shape,r,a,o,i,s),v=Lt.runKernelFunc((function(t){return t.maxPool3dBackprop(p,f,d,m)}),{dy5D:p,input5D:f});return h?v.as4D(v.shape[1],v.shape[2],v.shape[3],v.shape[4]):v}(t,s,u,e,n,i,r,a)}}}));return c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),jc=In({avgPool3d_:function(t,e,n,r,a,o,i){void 0===o&&(o="NDHWC");var s=hn(t,"x","avgPool3d","float32"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),T(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),T("NDHWC"===o,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+o})),T(Ra(n,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=a&&T(F(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var l=ya(u.shape,e,n,i,r,a,o),p=Lt.runKernelFunc((function(t){return t.avgPool3d(u,l)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,a,o,i){var s=hn(t,"dy","avgPool3dBackprop"),u=hn(e,"input","avgPool3dBackprop"),c=s,l=u,p=!1;4===u.rank&&(p=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),l=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),T(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),T(5===l.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."})),null==a&&(a=[1,1,1]),T(Ra(r,a),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'"})),null!=i&&T(F(o),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var f=ya(l.shape,n,r,a,o,i),d=Lt.runKernelFunc((function(t){return t.avgPool3dBackprop(c,l,f)}),{dy5D:c,input5D:l});return p?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,i,r,a)}}}));return p=p.cast(u.dtype),c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),Gc=In({slice_:function(t,e,n){var r,a,o=hn(t,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(o.rank-1).fill(0)):e.length<o.rank?e.concat(new Array(o.rank-e.length).fill(0)):e.slice()).forEach((function(t){T(-1!==t,(function(){return"slice() does not support negative begin indexing."}))})),a=(a=null==n?new Array(o.rank).fill(-1):"number"==typeof n?[n].concat(new Array(o.rank-1).fill(-1)):n.length<o.rank?n.concat(new Array(o.rank-n.length).fill(-1)):n).map((function(t,e){return t>=0?t:(T(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),o.shape[e]-r[e])})),Xr(o,r,a);var i=o.shape,s={begin:r,size:a};return Lt.runKernelFunc((function(t){return t.slice(o,r,a)}),{x:o},(function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-a[n]]);return{x:function(){return t.pad(e)}}}),"Slice",s)}}),Hc=In({slice1d_:function(t,e,n){var r=hn(t,"x","slice1d");return T(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),Gc(r,[e],[n])}}),qc=In({slice2d_:function(t,e,n){var r=hn(t,"x","slice2d");return T(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),Gc(r,e,n)}}),Kc=In({slice3d_:function(t,e,n){var r=hn(t,"x","slice3d");return T(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),Gc(r,e,n)}}),Xc=In({slice4d_:function(t,e,n){var r=hn(t,"x","slice4d");return T(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),Gc(r,e,n)}});function Yc(t,e,n,r,a){return e.rank<n.rank&&(e=e.reshape(xn(e.shape,r))),t.rank<n.rank&&(t=t.reshape(xn(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==a?r:r.transpose(a)}}}var $c=In({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","all","bool"),a=W(e,r.shape),o=a,i=wn(o,r.rank);null!=i&&(r=r.transpose(i),o=En(o.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.all(r,o)}),{$x:r});if(n){var u=xn(s.shape,a);return s.reshape(u)}return s}}),Qc=In({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","any","bool"),a=W(e,r.shape),o=a,i=wn(o,r.rank);null!=i&&(r=r.transpose(i),o=En(o.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.any(r,o)}),{$x:r});if(n){var u=xn(s.shape,a);return s.reshape(u)}return s}}),Jc=In({argMax_:function(t,e){void 0===e&&(e=0);var n=hn(t,"x","argMax");null==e&&(e=0);var r=W(e,n.shape),a=wn(r,n.rank);null!=a&&(n=n.transpose(a),r=En(r.length,n.rank));var o={axis:r[0]},i=[n];return Lt.runKernelFunc((function(t,e){var a=t.argMax(n,r[0]);return e([n]),a}),{x:n},(function(t,e){var n=e[0];return{x:function(){return qn(n)}}}),"ArgMax",o,i)}}),Zc=In({argMin_:function(t,e){void 0===e&&(e=0);var n=hn(t,"x","argMin");null==e&&(e=0);var r=W(e,n.shape),a=wn(r,n.rank);return null!=a&&(n=n.transpose(a),r=En(r.length,n.rank)),Lt.runKernelFunc((function(t,e){var a=t.argMin(n,r[0]);return e([n]),a}),{$x:n},(function(t,e){var n=e[0];return{$x:function(){return qn(n)}}}))}}),tl=In({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","logSumExp"),a=W(e,r.shape),o=r.max(a,!0),i=r.sub(o).exp().sum(a).log(),s=o.reshape(i.shape).add(i);if(n){var u=xn(s.shape,a);return s.reshape(u)}return s}}),el=In({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","max"),a=r,o=W(e,r.shape),i=o,s=wn(i,r.rank);null!=s&&(r=r.transpose(s),i=En(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.max(r,i);return e([a,n]),n}),{x:r},(function(t,e){return Yc(t,e[1],e[0],o,s)}),"Max",{axes:i},u,[!0]);if(n){var l=xn(c.shape,o);c=c.reshape(l)}return c}}),nl=In({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","mean"),a=W(e,r.shape),o=D(yn(r.shape,a)[1]);return sa((function(t){var r=Dn(o);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return a.forEach((function(t){n[t]=1})),e.reshape(n).mul(Wn(t.shape,"float32")).div(o)}}}))(r)}}),rl=In({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","min"),a=r,o=W(e,r.shape),i=o,s=wn(i,r.rank);null!=s&&(r=r.transpose(s),i=En(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.min(r,i);return e([a,n]),n}),{x:r},(function(t,e){return Yc(t,e[1],e[0],o,s)}),"Min",{axes:i},u,[!0]);if(n){var l=xn(c.shape,o);c=c.reshape(l)}return c}}),al=In({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=W(e,(t=hn(t,"x","moments")).shape),a=t.mean(r,n),o=a.shape;n||(o=xn(a.shape,r));var i=t.toFloat().sub(a.reshape(o)).square();return{mean:a,variance:i.mean(r,n)}}}),ol=In({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var a=W(e,r.shape);return sa((function(t){var e=wn(a,t.rank),r=a,o=t;null!=e&&(o=t.transpose(e),r=En(r.length,t.rank));var i=function(e){var n=t.shape.slice();return a.forEach((function(t){n[t]=1})),e.reshape(n).mul(Wn(t.shape,"float32"))},s={axes:r},u=Lt.runKernelFunc((function(t){return t.sum(o,r)}),{x:o},(function(t){return{x:function(){return i(t)}}}),"Sum",s);if(n){var c=xn(u.shape,a);u=u.reshape(c)}return{value:u,gradFunc:i}}))(r)}}),il=In({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=hn(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var a=W(e,r.shape),o=wn(a,r.rank),i=a,s=r;null!=o&&(s=r.transpose(o),i=En(i.length,r.rank));var u=Lt.runKernelFunc((function(t){return t.prod(s,i)}),{permutedX:s});if(n){var c=xn(u.shape,a);u=u.reshape(c)}return u}}),sl=In({elu_:function(t){var e=hn(t,"x","elu");return Lt.runKernelFunc((function(t,n){var r=t.elu(e);return n([r]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return Lt.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),ul=In({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=hn(t,"x","leakyRelu");return Lu(Dn(e).mul(n),n)}}),cl=In({prelu_:function(t,e){var n=hn(t,"x","prelu"),r=hn(e,"alpha","prelu");return Lt.runKernelFunc((function(t,e){var a=t.prelu(n,r);return e([n,r]),a}),{x:n,alpha:r},(function(t,e){var n=e[0],r=e[1],a=n.greater(0);return{x:function(){return Tu(a,t,t.mul(r))},alpha:function(){var e=Tu(a,qn(t),t.mul(n)),o=ma(r.shape,t.shape);return o.length>0&&(e=e.sum(o)),e.reshape(r.shape)}}}),"Prelu")}}),ll=In({relu_:function(t){var e=hn(t,"x","relu");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((function(t,n){var r=t.relu(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mulStrict(n.step().toFloat())}}}),"Relu")}}),pl=In({relu6_:function(t){var e=hn(t,"x","relu6");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),fl=In({selu_:function(t){var e=hn(t,"x","selu");return Lt.runKernelFunc((function(t,n){var r=t.selu(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){var e=n.greater(Dn(0)),r=Dn(ss),a=Dn(us),o=t.mul(a),i=t.mul(r).mul(n.toFloat().exp());return Tu(e,o,i)}}}))}}),dl=In({transpose_:function(t,e){var n=hn(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),T(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){T(t>=0&&t<n.rank,(function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e}))})),n.rank<=1)return n.clone();var r={perm:e};return Lt.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},(function(t){var n=Cn(e);return{x:function(){return t.transpose(n)}}}),"Transpose",r)}}),hl=In({localResponseNormalization_:function(t,e,n,r,a){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===a&&(a=.5);var o=hn(t,"x","localResponseNormalization");T(4===o.rank||3===o.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+o.rank+"."})),T(F(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var i=o,s=!1;3===o.rank&&(s=!0,i=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]));var u=Lt.runKernelFunc((function(t,o){var s=t.localResponseNormalization4D(i,e,n,r,a);return o([i,s]),s}),{x4D:i},(function(t,o){var i=o[0],s=o[1];return{x4D:function(){return Lt.runKernelFunc((function(o){return o.LRNGrad(t,i,s,e,n,r,a)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),ml=In({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var a=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(Dn(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=hn(t,"x","norm"),e,n),o=a.shape;if(r){var i=W(n,t.shape);o=xn(a.shape,i)}return a.reshape(o)}}),vl=In({basicLSTMCell_:function(t,e,n,r,a,o){var i=hn(t,"forgetBias","basicLSTMCell"),s=hn(e,"lstmKernel","basicLSTMCell"),u=hn(n,"lstmBias","basicLSTMCell"),c=hn(r,"data","basicLSTMCell"),l=hn(a,"c","basicLSTMCell"),p=hn(o,"h","basicLSTMCell"),f=c.concat(p,1).matMul(s).add(u),d=f.shape[0],h=f.shape[1]/4,m=[d,h],v=f.slice([0,0],m),g=f.slice([0,h],m),y=f.slice([0,2*h],m),x=f.slice([0,3*h],m),b=v.sigmoid().mulStrict(g.tanh()).addStrict(l.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),gl=In({multiRNNCell_:function(t,e,n,r){for(var a=hn(e,"data","multiRNNCell"),o=mn(n,"c","multiRNNCell"),i=mn(r,"h","multiRNNCell"),s=a,u=[],c=0;c<t.length;c++){var l=t[c](s,o[c],i[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var p=[],f=[];for(c=0;c<u.length;c+=2)p.push(u[c]),f.push(u[c+1]);return[p,f]}}),yl=In({movingAverage_:function(t,e,n,r,a){void 0===a&&(a=!0);var o=hn(t,"v","movingAverage"),i=hn(e,"x","movingAverage"),s=hn(n,"decay","movingAverage");Dt(o,i),T(_(o.shape,i.shape),(function(){return"Shape mismatch in v and x"}));var u=Dn(1),c=u.sub(s),l=i.sub(o).mul(c);if(a){T(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var p=hn(r,"step","movingAverage");l=l.div(u.sub(qu(s,p)))}return o.add(l)}}),xl=In({stridedSlice_:function(t,e,n,r,a,o,i,s,u){if(void 0===a&&(a=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==i)throw new Error("ellipsis mask is not yet supported");var c=hn(t,"x","stridedSlice"),l=Yr(s),p=c.shape.slice();l.forEach((function(t){e[t]=0,n[t]=1,p.splice(t,0,1)})),c=c.reshape(p);for(var f=0;f<c.rank;f++)e[f]=Qr(a,e,r,c.shape,f),n[f]=Jr(o,n,r,c.shape,f),r[f]=r[f]||1;var d=Yr(u);d.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var h=$r(e,n,r),m=h.filter((function(t,e){return-1===d.indexOf(e)}));return r.every((function(t){return 1===t}))?Gc(c,e,h).reshape(m):Lt.runKernelFunc((function(t){return t.stridedSlice(c,e,n,r)}),{$x:c}).reshape(m)}}),bl=In({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=hn(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var a=r.shape[r.shape.length-1];if(e>a)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+e);var o=Lt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:o[0],indices:o[1]}}}),wl=In({scatterND_:function(t,e,n){var r=hn(t,"indices","scatterND","int32"),a=hn(e,"updates","scatterND");return function(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,a=e.rank>1?e.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+a+".";if(n.rank<a)throw new Error(o+" update.rank < "+a+". ");if(t.length<r+(n.rank-a))throw new Error(o+" Output shape length < "+(r+(n.rank-a)));if(n.rank!==a+t.length-r)throw new Error(o+" update.rank != "+(a+t.length-r));for(var i=0;i<a;++i)if(n.shape[i]!==e.shape[i])throw new Error(o+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-a;++i)if(n.shape[i+a]!==t[i+r])throw new Error(o+" updates.shape["+(i+a)+"] ("+n.shape[i+a]+") != shape["+(i+a)+"] ("+t[i+a]+")")}(n,e,t)}(a,r,n),Lt.runKernelFunc((function(t){return t.scatterND(r,a,n)}),{$indices:r,$updates:a})}}),Cl=In({fft_:function(t){T("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),El=In({ifft_:function(t){T("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),Sl=In({rfft_:function(t,e){T("float32"===t.dtype,(function(){return"The dtype for rfft() must be real value but got "+t.dtype}));var n,r=t.shape[t.shape.length-1],a=t.size/r;if(null!=e&&e<r){var o=t.shape.map((function(t){return 0})),i=t.shape.map((function(t){return t}));i[t.shape.length-1]=e,n=t.slice(o,i),r=e}else if(null!=e&&e>r){var s=t.shape.map((function(t){return t}));s[t.shape.length-1]=e-r,n=t.concat(zn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=Rn(n,u).as2D(a,r),l=Cl(c),p=Math.floor(r/2)+1,f=Tn(l),d=kn(l),h=f.split([p,r-p],f.shape.length-1),m=d.split([p,r-p],d.shape.length-1),v=n.shape.slice();return v[n.shape.length-1]=p,Rn(h[0],m[0]).reshape(v)}}),Nl=In({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),a=El(r);return Tn(a)}var o=[n,2*(e-1)],i=Tn(t).as2D(n,e),s=kn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(Dn(-1)),l=i.concat(u,1),p=s.concat(c,1);return r=Rn(l,p).as2D(o[0],o[1]),a=El(r),Tn(a)}}),Il=Object.freeze({fft:Cl,ifft:El,rfft:Sl,irfft:Nl}),Rl=In({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var a=hn(t,"sparseIndices","sparseToDense","int32"),o=hn(e,"sparseValues","sparseToDense"),i=hn(r,"defaultValue","sparseToDense",o.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var a=t.rank>0?t.shape[0]:1,o=t.rank>1?t.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==a))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+a+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,o,n,i),Lt.runKernelFunc((function(t){return t.sparseToDense(a,o,n,i)}),{$sparseIndices:a,$sparseValues:o,$defaultValue:i})}}),Tl=In({gatherND_:function(t,e){var n=hn(e,"indices","gatherND","int32"),r=hn(t,"x","gatherND");return Lt.runKernelFunc((function(t){return t.gatherND(r,n)}),{$x:r,$indices:n})}}),kl=In({diag_:function(t){var e=hn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Lt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}}),Al=In({dropout_:function(t,e,n,r){var a=hn(t,"x","dropout");if(T("float32"===a.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+a.dtype+" tensor instead."})),T(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof wt?a.clone():a;var o=function(t,e){if(null==e)return t.shape.slice();if(_(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(a,n),i=1-e,s=Or(o,0,1,"float32",r).add(i).floor().div(i);return a.mul(s)}});function Ol(t,e,n){for(var r=1-t%2,a=new Float32Array(t),o=0;o<t;++o){var i=2*Math.PI*o/(t+r-1);a[o]=e-n*Math.cos(i)}return _n(a,"float32")}var Dl,_l=In({hannWindow_:function(t){return Ol(t,.5,.5)}}),Fl=In({hammingWindow_:function(t){return Ol(t,.54,.46)}}),Ml=In({frame_:function(t,e,n,r,a){void 0===r&&(r=!1),void 0===a&&(a=0);for(var o=0,i=[];o+e<=t.size;)i.push(Gc(t,o,e)),o+=n;if(r)for(;o<t.size;){var s=o+e-t.size,u=Kn([Gc(t,o,e-s),Un([s],a)]);i.push(u),o+=n}return 0===i.length?Fn([],[0,e]):Kn(i).as2D(i.length,e)}}),Bl=In({stft_:function(t,e,n,r,a){var o;void 0===a&&(a=_l),null==r&&(o=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(o)/Math.log(2)))));for(var i=Ml(t,e,n),s=Gu(i,a(e)),u=[],c=0;c<i.shape[0];c++)u.push(Sl(s.slice([c,0],[1,e]),r));return Kn(u)}}),Pl=Object.freeze({hannWindow:_l,hammingWindow:Fl,frame:Ml,stft:Bl}),Ll=function(t,e,n){return void 0===n&&(n=1),u(this,void 0,void 0,(function(){var r,a,o,i,s,u,l,p,f,d,h,m,v,g;return c(this,(function(c){switch(c.label){case 0:return r=hn(t,"predictions","inTopK"),a=hn(e,"targets","inTopK"),T(r.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),T(r.rank-1===a.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank})),k(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=r.shape[r.shape.length-1],T(n>0&&n<=o,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n})),[4,r.data()];case 1:return i=c.sent(),[4,a.data()];case 2:for(s=c.sent(),u=[i.length/o,o],p=u[1],f=U("bool",l=u[0]),d=0;d<l;d++){for(h=d*p,m=i.subarray(h,h+p),v=[],g=0;g<m.length;g++)v.push({value:m[g],index:g});for(v.sort((function(t,e){return e.value-t.value})),f[d]=0,g=0;g<n;g++)if(v[g].index===s[d]){f[d]=1;break}}return t!==r&&r.dispose(),e!==a&&a.dispose(),[2,An(f,a.shape,"bool")]}}))}))};!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(Dl||(Dl={}));var Vl=In({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=Dl.SUM_BY_NONZERO_WEIGHTS);var a=hn(t,"labels","absoluteDifference"),o=hn(e,"predictions","absoluteDifference"),i=null;null!=n&&(i=hn(n,"weights","absoluteDifference")),k(a.shape,o.shape,"Error in absoluteDifference: ");var s=a.sub(o).abs();return Wl(s,i,r)}}),Wl=In({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=Dl.SUM_BY_NONZERO_WEIGHTS);var r=hn(t,"losses","computeWeightedLoss"),a=null;null!=e&&(a=hn(e,"weights","computeWeightedLoss"));var o=null==a?r:r.mul(a);if(n===Dl.NONE)return o;if(n===Dl.SUM)return o.sum();if(n===Dl.MEAN){if(null==a)return o.mean();var i=r.size/a.size,s=o.sum().div(a.sum());return i>1?s.div(Dn(i)):s}if(n===Dl.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(Dn(r.size));var u=a.mul(Wn(r.shape)).notEqual(Dn(0)).sum().toFloat();return o.sum().div(u)}throw Error("Unknown reduction: "+n)}}),zl=In({cosineDistance_:function(t,e,n,r,a){void 0===a&&(a=Dl.SUM_BY_NONZERO_WEIGHTS);var o=hn(t,"labels","cosineDistance"),i=hn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=hn(r,"weights","cosineDistance")),k(o.shape,i.shape,"Error in cosineDistance: ");var u=Dn(1).sub(o.mul(i).sum(n,!0));return Wl(u,s,a)}}),Ul=In({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Dl.SUM_BY_NONZERO_WEIGHTS);var a=hn(t,"labels","hingeLoss"),o=hn(e,"predictions","hingeLoss"),i=null;null!=n&&(i=hn(n,"weights","hingeLoss")),k(a.shape,o.shape,"Error in hingeLoss: ");var s=Dn(1);a=Dn(2).mul(a).sub(s);var u=s.sub(a.mul(o)).relu();return Wl(u,i,r)}}),jl=In({huberLoss_:function(t,e,n,r,a){void 0===r&&(r=1),void 0===a&&(a=Dl.SUM_BY_NONZERO_WEIGHTS);var o=hn(t,"labels","huberLoss"),i=hn(e,"predictions","huberLoss"),s=null;null!=n&&(s=hn(n,"weights","huberLoss")),k(o.shape,i.shape,"Error in huberLoss: ");var u=Dn(r),c=i.sub(o).abs(),l=Wu(c,u),p=c.sub(l),f=Dn(.5).mul(l.square()).add(u.mul(p));return Wl(f,s,a)}}),Gl=In({logLoss_:function(t,e,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=Dl.SUM_BY_NONZERO_WEIGHTS);var o=hn(t,"labels","logLoss"),i=hn(e,"predictions","logLoss"),s=null;null!=n&&(s=hn(n,"weights","logLoss")),k(o.shape,i.shape,"Error in logLoss: ");var u=Dn(1),c=Dn(r),l=o.mul(i.add(c).log()).neg().sub(u.sub(o).mul(u.sub(i).add(c).log()));return Wl(l,s,a)}}),Hl=In({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Dl.SUM_BY_NONZERO_WEIGHTS);var a=hn(t,"labels","meanSquaredError"),o=hn(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=hn(n,"weights","meanSquaredError")),k(a.shape,o.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(o);return Wl(s,i,r)}}),ql=In({sigmoidCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Dl.SUM_BY_NONZERO_WEIGHTS);var o=hn(t,"multiClassLabels","sigmoidCrossEntropy"),i=hn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=hn(n,"weights","sigmoidCrossEntropy")),k(o.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=Dn(r),c=Dn(1),l=Dn(.5);o=o.mul(c.sub(u)).add(l.mul(u))}var p=function(t,e){var n=hn(t,"labels","sigmoidCrossEntropyWithLogits"),r=hn(e,"logits","sigmoidCrossEntropyWithLogits");k(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),o=r.mul(n),i=r.abs().neg().exp().log1p();return a.sub(o).add(i)}(o,i);return Wl(p,s,a)}}),Kl=In({softmaxCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Dl.SUM_BY_NONZERO_WEIGHTS);var o=hn(t,"onehotLabels","softmaxCrossEntropy"),i=hn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=hn(n,"weights","softmaxCrossEntropy")),k(o.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=Dn(r),c=Dn(1),l=Dn(o.shape[1]);o=o.mul(c.sub(u)).add(u.div(l))}var p=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return sa((function(t,e,r){var a=e.logSumExp([n],!0),o=e.toFloat().sub(a);return r([t,o]),{value:o.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],a=e[1],o=xn(t.shape,[n]);return[t.reshape(o).mul(r.toFloat().sub(a.exp())),t.reshape(o).mul(a.exp().sub(r.toFloat()))]}}}))(t,e)}(o,i);return Wl(p,s,a)}}),Xl=Object.freeze({get Reduction(){return Dl},absoluteDifference:Vl,computeWeightedLoss:Wl,cosineDistance:zl,hingeLoss:Ul,huberLoss:jl,logLoss:Gl,meanSquaredError:Hl,sigmoidCrossEntropy:ql,softmaxCrossEntropy:Kl});function Yl(t,e){return void 0===e&&(e=!1),Lt.tidy((function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],a=br(n),o=t.clone(),i=Fn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,c=function(t){var e,u=o,c=s,l=a;e=Lt.tidy((function(){var e=o.slice([t,t],[n-t,1]),u=e.norm(),c=o.slice([t,t],[1,1]),l=Fn([[-1]]).where(c.greater(0),Fn([[1]])),p=c.sub(l.mul(u)),f=e.div(p);s=1===f.shape[0]?i.clone():i.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var d=l.matMul(p).div(u).neg(),h=o.slice([t,0],[n-t,r]),m=d.mul(s);if(0===t)o=h.sub(m.matMul(s.transpose().matMul(h)));else{var v=h.sub(m.matMul(s.transpose().matMul(h)));o=o.slice([0,0],[t,r]).concat(v,0)}var g=a.slice([0,t],[n,a.shape[1]-t]);if(0===t)a=g.sub(g.matMul(s).matMul(m.transpose()));else{var y=g.sub(g.matMul(s).matMul(m.transpose()));a=a.slice([0,0],[n,t]).concat(y,1)}return[s,o,a]})),s=e[0],o=e[1],a=e[2],Je([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(a=a.slice([0,0],[n,r]),o=o.slice([0,0],[r,r])),[a,o]}))}var $l=In({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=hn(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var a=r.shape,o=r.shape.slice(-2),i=o[0],s=o[1];if(!(e<=i))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+i+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=i),n<0&&(n=s);var u=Gn(0,i,1,"int32").reshape([-1,1]),c=Gn(0,s,1,"int32"),l=$u(u,c),p=Su(l.lessEqual(Dn(+e,"int32")),l.greaterEqual(Dn(-n,"int32"))),f=zn([i,s],r.dtype);return Mr(Lr(r.reshape([-1,i,s])).map((function(t){return Tu(p,t,f)}))).reshape(a)}}),Ql=In({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,T(null!=t&&t.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var n=t[0].shape[0],r=function(e){T(t[e].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"}))},a=1;a<t.length;++a)r(a)}else e=!0,t=Jn(t,t.shape[0],0).map((function(t){return Fr(t,[0])}));T(t.length<=t[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."}));var o=[],i=t,s=function(t){o.push(Lt.tidy((function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=ol(o[n].mulStrict(e)).mul(o[n]);e=e.sub(r)}return e.div(ml(e,"euclidean"))})))};for(a=0;a<t.length;++a)s(a);return e?Mr(o,0):o}}),Jl=In({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return Yl(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=Lr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),a=[],o=[];return r.forEach((function(t){var n=Yl(t,e),r=n[0],i=n[1];a.push(r),o.push(i)})),[Mr(a,0).reshape(t.shape),Mr(o,0).reshape(t.shape)]}}),Zl=Object.freeze({bandPart:$l,gramSchmidt:Ql,qr:Jl});function tp(t,e,n,r,a,o){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==o&&(o=0);var i=t.shape[0];return n=Math.min(n,i),T(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),T(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),T(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),T(1===e.rank,(function(){return"scores must be a 1D tensor"})),T(e.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]})),T(0<=o&&o<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+o+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:o}}var ep=In({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=hn(t,"images","resizeBilinear");T(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),T(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));var a=r,o=!1;3===r.rank&&(o=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([a]),t.resizeBilinear(a,i,s,n)}),{x:a},(function(t,e){return{x:function(){return Lt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:i,newWidth:s});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),np=In({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=hn(t,"images","resizeNearestNeighbor");T(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),T(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),T("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var a=r,o=!1;3===r.rank&&(o=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([a]),t.resizeNearestNeighbor(a,i,s,n)}),{batchImages:a},(function(t,e){return{batchImages:function(){return Lt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),rp=In({nonMaxSuppression_:function(t,e,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var o=hn(t,"boxes","nonMaxSuppression"),i=hn(e,"scores","nonMaxSuppression"),s=tp(o,i,n,r,a);n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:a};return Lt.runKernelFunc((function(t){return t.nonMaxSuppression(o,i,n,r,a)}),{boxes:o,scores:i},null,"NonMaxSuppressionV3",u)}}),ap=In({nonMaxSuppressionWithScore_:function(t,e,n,r,a,o){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===o&&(o=0);var i=hn(t,"boxes","nonMaxSuppression"),s=hn(e,"scores","nonMaxSuppression"),u=tp(i,s,n,r,a,o),c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:o=u.softNmsSigma},l=Lt.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),op=In({cropAndResize_:function(t,e,n,r,a,o){var i=hn(t,"image","cropAndResize"),s=hn(e,"boxes","cropAndResize","float32"),u=hn(n,"boxInd","cropAndResize","int32");a=a||"bilinear",o=o||0;var c=s.shape[0];return T(4===i.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),T(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),T(1===u.rank&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),T(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),T(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),T("bilinear"===a||"nearest"===a,(function(){return"method must be bilinear or nearest, but was "+a})),Lt.runKernelFunc((function(t,e){return t.cropAndResize(i,s,u,r,a,o)}),{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:a,extrapolationValue:o,cropSize:r})}}),ip=Object.freeze({resizeBilinear:ep,resizeNearestNeighbor:np,nonMaxSuppression:rp,nonMaxSuppressionAsync:function(t,e,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),u(this,void 0,void 0,(function(){var o,i,s,u,l,p,f;return c(this,(function(c){switch(c.label){case 0:return o=hn(t,"boxes","nonMaxSuppressionAsync"),i=hn(e,"scores","nonMaxSuppressionAsync"),s=tp(o,i,n,r,a),n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,[4,Promise.all([o.data(),i.data()])];case 1:return u=c.sent(),l=u[0],p=u[1],f=Va(l,p,n,r,a),o!==t&&o.dispose(),i!==e&&i.dispose(),[2,f]}}))}))},nonMaxSuppressionWithScore:ap,nonMaxSuppressionWithScoreAsync:function(t,e,n,r,a,o){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===o&&(o=0),u(this,void 0,void 0,(function(){var i,s,u,l,p,f,d;return c(this,(function(c){switch(c.label){case 0:return i=hn(t,"boxes","nonMaxSuppressionAsync"),s=hn(e,"scores","nonMaxSuppressionAsync"),u=tp(i,s,n,r,a,o),n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,o=u.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return l=c.sent(),p=l[0],f=l[1],d=Wa(p,f,n,r,a,o),i!==t&&i.dispose(),s!==e&&s.dispose(),[2,d]}}))}))},cropAndResize:op}),sp=function(t,e){return!(t>0)||"linear"===e},up=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},cp=function(t,e){var n=e,r=ma(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},lp=function(t,e,n){if("linear"===e)return t;if("relu"===e)return ll(t);if("elu"===e)return sl(t);if("relu6"===e)return pl(t);if("prelu"===e)return cl(t,n);throw new Error("Unknown fused activation "+e+".")},pp=In({fusedMatMul_:function(t){var e,n=t.a,r=t.b,a=t.transposeA,o=void 0!==a&&a,i=t.transposeB,s=void 0!==i&&i,u=t.bias,c=t.activation,l=void 0===c?"linear":c,p=t.preluActivationWeights;if(!1===sp(Lt.state.gradientDepth,l)){var f=kc(n,r,o,s);return null!=u&&(f=Au(f,u)),lp(f,l,p)}var d=hn(n,"a","fused matMul"),h=hn(r,"b","fused matMul");e=Ot(d,h),d=e[0],h=e[1];var m=o?d.shape[d.rank-2]:d.shape[d.rank-1],v=s?h.shape[h.rank-1]:h.shape[h.rank-2],g=o?d.shape[d.rank-1]:d.shape[d.rank-2],y=s?h.shape[h.rank-2]:h.shape[h.rank-1],x=d.shape.slice(0,-2),b=h.shape.slice(0,-2),w=D(x),C=D(b);T(d.rank>=2&&h.rank>=2&&d.rank===h.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+h.rank+"."})),T(_(x,b),(function(){return"Error in fused matMul: outer dimensions ("+x+") and ("+b+") of Tensors with shapes "+d.shape+" and "+h.shape+" must match."})),T(m===v,(function(){return"Error in fused matMul: inner shapes ("+m+") and ("+v+") of Tensors with shapes "+d.shape+" and "+h.shape+" and transposeA="+o+" and transposeB="+s+" must match."}));var E,S,N=d.shape.slice(0,-2).concat([g,y]),I=o?d.as3D(w,m,g):d.as3D(w,g,m),R=s?h.as3D(C,y,v):h.as3D(C,v,y);null!=u&&va(N,(E=Ot(E=hn(u,"bias","fused matMul"),d)[0]).shape),null!=p&&(S=hn(p,"prelu weights","fused matMul"));var k={$a:I,$b:R};return null!=u&&(k.$bias=E),null!=p&&(k.$preluActivationWeights=S),Lt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:I,b:R,transposeA:o,transposeB:s,bias:E,activation:l,preluActivationWeights:S});return e([I,R,n]),n}),k,(function(t,e){var n=e[0],r=e[1],a=e[2],i=up(t,a,l),c={};return null!=u&&(c={$bias:function(){return cp(E,i)}}),o||s?!o&&s?Object.assign({$a:function(){return i.matMul(r,!1,!1)},$b:function(){return i.matMul(n,!0,!1)}},c):o&&!s?Object.assign({$a:function(){return r.matMul(i,!1,!0)},$b:function(){return n.matMul(i,!1,!1)}},c):Object.assign({$a:function(){return r.matMul(i,!0,!0)},$b:function(){return i.matMul(n,!0,!0)}},c):Object.assign({$a:function(){return i.matMul(r,!1,!0)},$b:function(){return n.matMul(i,!0,!1)}},c)})).reshape(N)}}),fp=In({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,o=t.dataFormat,i=void 0===o?"NHWC":o,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,p=t.activation,f=void 0===p?"linear":p,d=t.preluActivationWeights;if(f=f||"linear",!1===sp(Lt.state.gradientDepth,f)){var h=xc(e,n,r,a,i,u,c);return null!=l&&(h=Au(h,l)),lp(h,f,d)}var m=hn(e,"x","conv2d"),v=hn(n,"filter","conv2d"),g=m,y=!1;3===m.rank&&(y=!0,g=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),T(4===g.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),T(4===v.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+v.rank+"."})),null!=c&&T(F(a),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+a+"."})),T(g.shape[3]===v.shape[2],(function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+v.shape[2]+"."})),T(Ra(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),T("NHWC"===i,(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var x,b,w=xa(g.shape,v.shape,r,u,a,c);null!=l&&(x=Ot(x=hn(l,"bias","fused conv2d"),m)[0],va(w.outShape,x.shape)),null!=d&&(b=hn(d,"prelu weights","fused conv2d"));var C={x:g,filter:v};null!=l&&(C.bias=x),null!=d&&(C.preluActivationWeights=b);var E=[v,g],S=Lt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:g,filter:v,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([v,g,n]),n}),C,(function(t,e){var n=e,o=n[0],i=n[1],s=n[2],c=up(t,s,f);T(Ia(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var p={};return null!=l&&(p={bias:function(){return cp(x,c)}}),Object.assign({x:function(){return Cc(i.shape,c,o,r,a)},filter:function(){return wc(i,c,o.shape,r,a)}},p)}),"FusedConv2D",{convInfo:w,activation:f},E,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),dp=In({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,o=t.dataFormat,i=void 0===o?"NHWC":o,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,p=t.activation,f=void 0===p?"linear":p,d=t.preluActivationWeights;if(!1===sp(Lt.state.gradientDepth,f)){var h=Ec(e,n,r,a,i,u,c);return null!=l&&(h=Au(h,l)),lp(h,f,d)}var m=hn(e,"x","depthwiseConv2d"),v=hn(n,"filter","depthwiseConv2d"),g=m,y=!1;3===m.rank&&(y=!0,g=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),T(4===g.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),T(4===v.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+v.rank+"."})),T(g.shape[3]===v.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+v.shape[2]+"."})),null==u&&(u=[1,1]),T(Ra(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=c&&T(F(a),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+a+"."}));var x,b,w=xa(g.shape,v.shape,r,u,a,c,!0);null!=l&&(x=Ot(x=hn(l,"bias","fused conv2d"),m)[0],va(w.outShape,x.shape)),null!=d&&(b=hn(d,"prelu weights","fused depthwiseConv2d"));var C={x:g,filter:v};null!=l&&(C.bias=x),null!=d&&(C.preluActivationWeights=b);var E=[v,g],S=Lt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:g,filter:v,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([v,g,n]),n}),C,(function(t,e){T(Ia(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],a=e[2],o=up(t,a,f),i={};return null!=l&&(i={bias:function(){return cp(x,o)}}),Object.assign({x:function(){return Sc(r.shape,o,n,w)},filter:function(){return Nc(r,o,n.shape,w)}},i)}),"FusedDepthwiseConv2D",{convInfo:w,activation:f},E,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),hp=Object.freeze({matMul:pp,conv2d:fp,depthwiseConv2d:dp}),mp=Object.freeze({image:ip,linalg:Zl,losses:Xl,spectral:Il,fused:hp,signal:Pl,square:ks,conv1d:yc,conv2d:xc,conv3d:bc,depthwiseConv2d:Ec,separableConv2d:Ic,conv2dTranspose:Rc,conv3dTranspose:Tc,op:In,batchNormalization2d:vu,batchNormalization3d:gu,batchNormalization4d:yu,batchNormalization:xu,batchNorm:bu,batchNorm2d:wu,batchNorm3d:Cu,batchNorm4d:Eu,booleanMaskAsync:hc,complex:Rn,real:Tn,imag:kn,concat:Kn,concat1d:Xn,concat2d:Yn,concat3d:$n,concat4d:Qn,split:Jn,matMul:kc,dot:Ac,outerProduct:Oc,reverse:Dc,reverse1d:_c,reverse2d:Fc,reverse3d:Mc,reverse4d:Bc,maxPool:Vc,avgPool:Wc,pool:zc,maxPool3d:Uc,avgPool3d:jc,slice:Gc,slice1d:Hc,slice2d:qc,slice3d:Kc,slice4d:Xc,abs:As,acos:Os,acosh:Ds,asin:_s,asinh:Fs,atan:Ms,atanh:Bs,ceil:Ps,clipByValue:Ls,cos:Vs,cosh:Ws,erf:zs,exp:Us,expm1:js,floor:Gs,log:Hs,log1p:qs,logSigmoid:Ks,neg:Xs,reciprocal:Ys,round:$s,rsqrt:Qs,sigmoid:Js,sign:Zs,isNaN:tu,isInf:eu,isFinite:nu,sin:ru,sinh:au,softplus:ou,sqrt:iu,step:su,tan:uu,tanh:cu,all:$c,any:Qc,argMax:Jc,argMin:Zc,logSumExp:tl,max:el,mean:nl,min:rl,moments:al,sum:ol,prod:il,equal:Ju,equalStrict:Zu,greater:tc,greaterEqual:ec,greaterEqualStrict:nc,greaterStrict:rc,less:ac,lessEqual:oc,lessEqualStrict:ic,lessStrict:sc,notEqual:uc,notEqualStrict:cc,add:Au,addN:Ou,addStrict:Du,atan2:_u,div:Fu,divNoNan:Mu,divStrict:Bu,floorDiv:Pu,maximum:Lu,maximumStrict:Vu,minimum:Wu,minimumStrict:zu,mod:Uu,modStrict:ju,mul:Gu,mulStrict:Hu,pow:qu,powStrict:Ku,squaredDifference:Xu,squaredDifferenceStrict:Yu,sub:$u,subStrict:Qu,elu:sl,leakyRelu:ul,prelu:cl,relu:ll,relu6:pl,selu:fl,logicalAnd:Su,logicalNot:Nu,logicalOr:Iu,logicalXor:Ru,where:Tu,whereAsync:ku,buffer:pr,print:fr,batchToSpaceND:dr,broadcastTo:hr,cast:mr,clone:vr,cumsum:gr,depthToSpace:yr,expandDims:xr,eye:br,multinomial:wr,oneHot:Cr,pad:Er,pad1d:Sr,pad2d:Nr,pad3d:Ir,pad4d:Rr,rand:Tr,randomNormal:kr,randomGamma:Ar,randomUniform:Or,reshape:Dr,spaceToBatchND:_r,squeeze:Fr,stack:Mr,tile:Br,truncatedNormal:Pr,unstack:Lr,setdiff1dAsync:Vr,fill:Un,linspace:jn,ones:Wn,range:Gn,scalar:Dn,tensor:An,tensor1d:_n,tensor2d:Fn,tensor3d:Mn,tensor4d:Bn,tensor5d:Pn,tensor6d:Ln,variable:Vn,zeros:zn,onesLike:Hn,zerosLike:qn,transpose:dl,softmax:ca,logSoftmax:la,localResponseNormalization:hl,norm:ml,gather:fc,unsortedSegmentSum:dc,basicLSTMCell:vl,multiRNNCell:gl,movingAverage:yl,stridedSlice:xl,topk:bl,scatterND:wl,fft:Cl,ifft:El,rfft:Sl,irfft:Nl,sparseToDense:Rl,gatherND:Tl,diag:kl,dropout:Al,hannWindow:_l,hammingWindow:Fl,frame:Ml,stft:Bl,inTopKAsync:Ll});function vp(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&T("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function gp(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var yp=function(t){function e(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new pa(e,Lt),e}return s(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,f().get("IS_NODE")&&pn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},e.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},e.prototype.numDataIds=function(){return this.data.numDataIds()},e.prototype.read=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){return[2,this.readSync(t)]}))}))},e.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?_a(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},e.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map((function(t){return lt(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return pr(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Lt.makeTensorFromDataId(r,e,n,this)},e.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},e.prototype.time=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return e=st(),t(),[2,{kernelMs:st()-e}]}))}))},e.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},e.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},e.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(vp(t,"slice"),Zr(t.shape,e,n)){var r=ta(e,t.strides),a=D(n);return An(this.readSync(t.dataId).subarray(r,r+a),n,t.dtype)}for(var o=pr(n,t.dtype),i=this.bufferSync(t),s=0;s<o.size;++s){var u=o.indexToLoc(s).map((function(t,n){return t+e[n]}));o.values[s]=i.get.apply(i,u)}return o.toTensor()},e.prototype.stridedSlice=function(t,e,n,r){vp(t,"stridedSlice");var a=$r(e,n,r);if(a.some((function(t){return 0===t})))return An([],a);for(var o=pr(a,t.dtype),i=this.bufferSync(t),s=0;s<o.size;s++){for(var u=o.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];o.set.apply(o,[i.get.apply(i,c)].concat(u))}return o.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=pr([t.size,t.size],t.dtype),r=n.values,a=0;a<e.length;a++)r[a*t.size+a]=e[a];return n.toTensor()},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),a=0,o=0;o<t.rank;o++)o!==e&&(r[a++]=t.shape[o]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(o=0;o<u.length;o++)i[e]=o,u[o]=this.slice(t,i,s).reshape(r);return u},e.prototype.reverse=function(t,e){vp(t,"reverse");for(var n=pr(t.shape,t.dtype),r=this.bufferSync(t),a=function(a){var o=n.indexToLoc(a),i=o.slice();e.forEach((function(e){return i[e]=t.shape[e]-1-i[e]})),n.set.apply(n,[r.get.apply(r,i)].concat(o))},o=0;o<n.size;o++)a(o);return n.toTensor()},e.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map((function(t){return Tn(t)})),a=t.map((function(t){return kn(t)}));return Rn(this.concat(r,e),this.concat(a,e))}var o=t.map((function(t){var n=D(t.shape.slice(e));return t.as2D(-1,n)})),i=Nn(o.map((function(t){return t.shape})),1),s=pr(i,t[0].dtype).values;if(1===o[0].shape[0]){var u=0;o.forEach((function(t){s.set(n.readSync(t.dataId),u),u+=t.size}))}else{var c=0;o.forEach((function(t){for(var e=n.readSync(t.dataId),r=0,a=0;a<t.shape[0];++a)for(var o=a*i[1]+c,u=0;u<t.shape[1];++u)s[o+u]=e[r++];c+=t.shape[1]}))}var l=Nn(t.map((function(t){return t.shape})),e);return An(s,l,t[0].dtype)},e.prototype.neg=function(t){return vp(t,"neg"),this.multiply(Dn(-1),t)},e.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t+n,imag:e+r}})):this.broadcastedBinaryOp(t,e,kt(t.dtype,e.dtype),(function(t,e){return t+e}))},e.prototype.addN=function(t){var e=this;vp(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=pr(t[0].shape,t[0].dtype),a=r.values,o=0;o<t.length;o++)for(var i=n[o],s=0;s<a.length;s++)a[s]+=i[s];return r.toTensor()},e.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t-n,imag:e-r}})):this.broadcastedBinaryOp(t,e,kt(t.dtype,e.dtype),(function(t,e){return t-e}))},e.prototype.pow=function(t,e){return vp([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.pow(t,e)}))},e.prototype.batchMatMul=function(t,e,n,r){vp([t,e],"matMul");for(var a=n?t.shape[1]:t.shape[2],o=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],p=l[0],f=l[1],d=l[2],h=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],m=h[0],v=h[1],g=h[2],y=o*i,x=pr([s,o,i],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<o;E+=w)for(var S=0;S<i;S+=w)for(var N=0;N<a;N+=w)for(var I=Math.min(E+w,o),R=Math.min(S+w,i),T=Math.min(N+w,a),k=E;k<I;k++)for(var A=S;A<R;A++){for(var O=0,D=N;D<T;D++)O+=u[C*p+k*f+D*d]*c[D*m+A*v+C*g];b[C*y+(k*i+A)]+=O}return x.toTensor()},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,a=t.transposeB,o=t.bias,i=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,a);return o&&(u=this.add(u,o)),i&&(u=gp(this,u,i,s)),u},e.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}})):this.broadcastedBinaryOp(t,e,kt(t.dtype,e.dtype),(function(t,e){return t*e}))},e.prototype.realDivide=function(t,e){return vp([t,e],"realDivide"),this.broadcastedBinaryOp(t,e,"float32",(function(t,e){return t/e}))},e.prototype.floorDiv=function(t,e){return vp([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},e.prototype.sum=function(t,e){vp(t,"sum"),bn("sum",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,kt(t.dtype,"int32")),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=0,f=0;f<i;++f)p+=u[l+f];s[c]=p}return o},e.prototype.prod=function(t,e){vp(t,"sum");for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,kt(t.dtype,"int32")),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=1,f=0;f<i;++f)p*=u[l+f];s[c]=p}return o},e.prototype.unsortedSegmentSum=function(t,e,n){vp(t,"unsortedSegmentSum");for(var r=[],a=t.rank-e.rank,o=0;o<a;++o)e=e.expandDims(o+1);for(o=0;o<n;++o){var i=Dn(o,"int32"),s=Ju(i,e).asType("float32").mul(t).sum(0);r.push(s)}return Mr(r)},e.prototype.argMin=function(t,e){vp(t,"argMin");var n=[e];bn("argMin",n,t.rank);for(var r=yn(t.shape,n),a=r[0],o=r[1],i=zn(a,"int32"),s=D(o),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var p=l*s,f=c[p],d=0,h=0;h<s;++h){var m=c[p+h];m<f&&(f=m,d=h)}u[l]=d}return i},e.prototype.argMax=function(t,e){vp(t,"argMax");var n=[e];bn("argMax",n,t.rank);for(var r=yn(t.shape,n),a=r[0],o=r[1],i=zn(a,"int32"),s=D(o),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var p=l*s,f=c[p],d=0,h=0;h<s;++h){var m=c[p+h];m>f&&(f=m,d=h)}u[l]=d}return i},e.prototype.cumsum=function(t,e,n,r){if(vp(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var a=kt(t.dtype,"int32"),o=zn(t.shape,a),i=this.readSync(o.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],c=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},l=0;l<s.length;l+=u)for(var p=0;p<u;p++){var f=c(l,p);if(0===p)i[f]=n?0:s[f];else{var d=c(l,p-1);i[f]=n?s[d]+i[d]:s[f]+i[d]}}return o},e.prototype.equal=function(t,e){return vp([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},e.prototype.notEqual=function(t,e){return vp([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},e.prototype.less=function(t,e){return vp([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},e.prototype.lessEqual=function(t,e){return vp([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},e.prototype.greater=function(t,e){return vp([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},e.prototype.greaterEqual=function(t,e){return vp([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},e.prototype.logicalNot=function(t){vp(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return this.makeOutput(n,t.shape,"bool")},e.prototype.logicalAnd=function(t,e){return vp([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},e.prototype.logicalOr=function(t,e){return vp([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},e.prototype.select=function(t,e,n){vp([t,e,n],"select");for(var r=this.readSync(t.dataId),a=this.readSync(e.dataId),o=this.readSync(n.dataId),i=zn(e.shape,kt(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:D(e.shape.slice(1)),l=0;l<r.length;l++)for(var p=0;p<c;p++)1===r[l]?s[u++]=a[l]:s[u++]=o[l];return i},e.prototype.where=function(t){vp([t],"where");var e=this.readSync(t.dataId);return Xa(t.shape,e)},e.prototype.topk=function(t,e,n){return vp(t,"topk"),Ka(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){vp(t,"min"),bn("min",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,t.dtype),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],f=0;f<i;++f){var d=u[l+f];d<p&&(p=d)}s[c]=p}return o},e.prototype.minimum=function(t,e){return vp([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},e.prototype.mod=function(t,e){return vp([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e}))},e.prototype.max=function(t,e){vp(t,"max"),bn("max",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,t.dtype),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],f=0;f<i;++f){var d=u[l+f];d>p&&(p=d)}s[c]=p}return o},e.prototype.maximum=function(t,e){return vp([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},e.prototype.all=function(t,e){vp(t,"all"),bn("all",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,t.dtype),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],f=0;f<i;++f){var d=u[l+f];p=p&&d}s[c]=p}return o},e.prototype.any=function(t,e){vp(t,"any"),bn("any",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],o=zn(r,t.dtype),i=D(a),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],f=0;f<i;++f){var d=u[l+f];p=p||d}s[c]=p}return o},e.prototype.squaredDifference=function(t,e){return vp([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},e.prototype.ceil=function(t){vp(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.floor=function(t){vp(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.sign=function(t){vp(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){vp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isInf=function(t){vp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isFinite=function(t){vp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.round=function(t){vp(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=Math.floor(e[r]);e[r]-a<.5?n[r]=Math.floor(e[r]):e[r]-a>.5?n[r]=Math.ceil(e[r]):n[r]=a%2==0?a:a+1}return this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){vp(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.expm1=function(t){vp(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.log=function(t){vp(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.log(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.log1p=function(t){vp(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.log1p(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.sqrt=function(t){vp(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.sqrt(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.rsqrt=function(t){vp(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=1/Math.sqrt(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.reciprocal=function(t){vp(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return this.makeOutput(n,t.shape,"float32")},e.prototype.linear=function(t){return t},e.prototype.relu=function(t){vp(t,"relu");for(var e=zn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),a=0;a<r.length;++a)n[a]=Math.max(0,r[a]);return e},e.prototype.relu6=function(t){vp(t,"relu");for(var e=zn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),a=0;a<r.length;++a)n[a]=Math.min(Math.max(0,r[a]),6);return e},e.prototype.prelu=function(t,e){return vp([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},e.prototype.elu=function(t){vp(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=n[r];e[r]=a>=0?a:Math.exp(a)-1}return this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){vp([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),a=this.readSync(t.dataId),o=0;o<r.length;++o){var i=r[o];n[o]=i>=1?a[o]:a[o]*(i+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){vp(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=n[r];e[r]=a>=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return this.makeOutput(e,t.shape,"float32")},e.prototype.clip=function(t,e,n){vp(t,"clip");for(var r=new Float32Array(t.size),a=this.readSync(t.dataId),o=0;o<a.length;++o){var i=a[o];r[o]=i>n?n:i<e?e:i}return this.makeOutput(r,t.shape,"float32")},e.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var a=n[2*r],o=n[2*r+1];e[r]=Math.hypot(a,o)}return this.makeOutput(e,t.shape,"float32")},e.prototype.int=function(t){vp(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return this.makeOutput(e,t.shape,"int32")},e.prototype.sigmoid=function(t){vp(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(e,t.shape,"float32")},e.prototype.softplus=function(t){vp(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),a=0;a<r.length;++a){var o,i=r[a]>-e,s=r[a]<e,u=Math.exp(r[a]);o=s?u:i?r[a]:Math.log(1+u),n[a]=o}return this.makeOutput(n,t.shape,"float32")},e.prototype.sin=function(t){vp(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cos=function(t){vp(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tan=function(t){vp(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asin=function(t){vp(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acos=function(t){vp(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan=function(t){vp(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan2=function(t,e){return vp([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},e.prototype.sinh=function(t){vp(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cosh=function(t){vp(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tanh=function(t){vp(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=M(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asinh=function(t){vp(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acosh=function(t){vp(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atanh=function(t){vp(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.erf=function(t){vp(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=Math.sign(n[r]),o=Math.abs(n[r]),i=1/(1+.3275911*o);e[r]=a*(1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-o*o))}return this.makeOutput(e,t.shape,"float32")},e.prototype.step=function(t,e){void 0===e&&(e=0),vp(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),a=0;a<r.length;++a){var o=r[a];isNaN(o)?n[a]=NaN:n[a]=o>0?1:e}return this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,o=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return a&&(s=this.add(s,a)),o&&(s=gp(this,s,o,i)),s},e.prototype.conv2d=function(t,e,n){vp([t,e],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,o=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c="channelsLast"===n.dataFormat,l=pr(n.outShape,t.dtype),p=t.strides[0],f=c?t.strides[1]:t.strides[2],d=c?t.strides[2]:1,h=c?1:t.strides[1],m=l.strides[0],v=c?l.strides[1]:l.strides[2],g=c?l.strides[2]:1,y=c?1:l.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=l.values,C=0;C<n.batchSize;++C)for(var E=C*p,S=C*m,N=0;N<n.outHeight;++N)for(var I=S+N*v,R=N*n.strideHeight-u,T=0;T<r;T++){var k=R+T*o;if(!(k<0||k>=n.inHeight))for(var A=T*e.strides[0],O=E+k*f,D=0;D<n.outWidth;++D)for(var _=I+D*g,F=D*n.strideWidth-s,M=0;M<a;M++){var B=F+M*i;if(!(B<0||B>=n.inWidth))for(var P=O+B*d,L=A+M*e.strides[1],V=0;V<n.inChannels;++V){for(var W=x[P+V*h],z=0;z<n.outChannels;++z)w[_+z*y]+=W*b[L+z];L+=n.outChannels}}}return l.toTensor()},e.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,a=n.filterHeight,o=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,c=n.padInfo.front,l=n.padInfo.left,p=n.padInfo.top,f=pr(n.outShape,t.dtype),d=this.readSync(t.dataId),h=this.readSync(e.dataId),m=f.values,v=0;v<n.batchSize;++v)for(var g=v*t.strides[0],y=v*f.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*f.strides[1],w=x*n.strideDepth-c,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var S=C*e.strides[0],N=g+E*t.strides[1],I=0;I<n.outHeight;++I)for(var R=b+I*f.strides[2],T=I*n.strideHeight-p,k=0;k<a;k++){var A=T+k*s;if(!(A<0||A>=n.inHeight))for(var O=S+k*e.strides[1],D=N+A*t.strides[2],_=0;_<n.outWidth;++_)for(var F=R+_*n.outChannels,M=_*n.strideWidth-l,B=0;B<o;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=O+B*e.strides[2],V=D+P*n.inChannels,W=L,z=0;z<n.inChannels;++z){for(var U=d[V+z],j=0;j<n.outChannels;++j)m[F+j]+=U*h[W+j];W+=n.outChannels}}}}return f.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){vp([t,e],"conv2dDerInput");for(var r=pr(n.inShape,"float32"),a=r.values,o=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],p=n.batchSize,f=n.filterHeight,d=n.filterWidth,h=n.inChannels,m=n.inHeight,v=n.inWidth,g=n.outChannels,y=n.outHeight,x=n.outWidth,b=n.strideHeight,w=n.strideWidth,C=n.dataFormat,E=f-1-n.padInfo.top,S=d-1-n.padInfo.left,N="channelsLast"===C,I=r.strides[0],R=N?r.strides[1]:r.strides[2],T=N?r.strides[2]:1,k=N?1:r.strides[1],A=t.strides[0],O=N?t.strides[1]:t.strides[2],D=N?t.strides[2]:1,_=N?1:t.strides[1],F=0;F<p;++F)for(var M=0;M<h;++M)for(var B=0;B<m;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),V=Math.min(y,(f+P)/b),W=0;W<v;++W){for(var z=W-S,U=Math.max(0,Math.ceil(z/w)),j=Math.min(x,(d+z)/w),G=0,H=L;H<V;++H)for(var q=H*b-P,K=U;K<j;++K)for(var X=A*F+O*H+D*K,Y=u*(f-1-q)+c*(d-1-(K*w-z))+l*M,$=0;$<g;++$)G+=o[X+_*$]*i[Y+$];a[I*F+R*B+T*W+k*M]=G}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=pr(n.inShape,"float32"),a=r.values,o=r.strides,i=o[0],s=o[1],u=o[2],c=o[3],l=this.readSync(t.dataId),p=t.strides,f=p[0],d=p[1],h=p[2],m=p[3],v=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,S=n.filterHeight,N=n.filterWidth,I=n.inChannels,R=n.inDepth,T=n.inHeight,k=n.inWidth,A=n.outChannels,O=n.outDepth,D=n.outHeight,_=n.outWidth,F=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=S-1-n.padInfo.top,V=N-1-n.padInfo.left,W=0;W<C;++W)for(var z=0;z<I;++z)for(var U=0;U<R;++U)for(var j=U-P,G=Math.max(0,Math.ceil(j/F)),H=Math.min(O,(E+j)/F),q=0;q<T;++q)for(var K=q-L,X=Math.max(0,Math.ceil(K/M)),Y=Math.min(D,(S+K)/M),$=0;$<k;++$){for(var Q=$-V,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(_,(N+Q)/B),tt=0,et=G;et<H;++et)for(var nt=et*F-j,rt=X;rt<Y;++rt)for(var at=rt*M-K,ot=J;ot<Z;++ot)for(var it=f*W+d*et+h*rt+m*ot,st=y*(E-1-nt)+x*(S-1-at)+b*(N-1-(ot*B-Q))+w*z,ut=0;ut<A;++ut)tt+=l[it+ut]*v[st+ut];a[i*W+s*U+u*q+c*$+z]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){vp([t,e],"conv2dDerFilter");for(var r=n.strideHeight,a=n.strideWidth,o=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=pr(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,p=this.bufferSync(t),f=this.bufferSync(e),d=0;d<o;++d)for(var h=Math.max(0,Math.ceil((l-d)/r)),m=Math.min(n.outHeight,(n.inHeight+l-d)/r),v=0;v<i;++v)for(var g=Math.max(0,Math.ceil((c-v)/a)),y=Math.min(n.outWidth,(n.inWidth+c-v)/a),x=0;x<n.inChannels;++x)for(var b=0;b<n.outChannels;++b){for(var w=0,C=0;C<n.batchSize;++C)for(var E=h;E<m;++E)for(var S=d+E*r-l,N=g;N<y;++N){var I=v+N*a-c;w+=s?p.get(C,S,I,x)*f.get(C,E,N,b):p.get(C,x,S,I)*f.get(C,b,E,N)}u.set(w,d,v,x,b)}return u.toTensor()},e.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,a=n.strideHeight,o=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=pr(n.filterShape,"float32"),l=c.values,p=c.strides,f=p[0],d=p[1],h=p[2],m=p[3],v=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=this.readSync(t.dataId),E=t.strides,S=E[0],N=E[1],I=E[2],R=E[3],T=n.padInfo.front,k=n.padInfo.left,A=n.padInfo.top,O=0;O<i;++O)for(var D=Math.max(0,Math.ceil((T-O)/r)),_=Math.min(n.outDepth,(n.inDepth+T-O)/r),F=O*f,M=0;M<s;++M)for(var B=Math.max(0,Math.ceil((A-M)/a)),P=Math.min(n.outHeight,(n.inHeight+A-M)/a),L=M*d+F,V=0;V<u;++V)for(var W=Math.max(0,Math.ceil((k-V)/o)),z=Math.min(n.outWidth,(n.inWidth+k-V)/o),U=V*h+L,j=0;j<n.inChannels;++j)for(var G=j*m+U,H=0;H<n.outChannels;++H){for(var q=0,K=0;K<n.batchSize;++K)for(var X=K*S,Y=K*y,$=D;$<_;++$)for(var Q=(O+$*r-T)*N+X,J=$*x+Y,Z=B;Z<P;++Z)for(var tt=(M+Z*a-A)*I+Q,et=Z*b+J,nt=W;nt<z;++nt){var rt=nt*w+et;q+=C[(V+nt*o-k)*R+tt+j]*v[rt+H]}l[G+H]=q}return c.toTensor()},e.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,o=t.activation,i=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return a&&(s=this.add(s,a)),o&&(s=gp(this,s,o,i)),s},e.prototype.depthwiseConv2D=function(t,e,n){vp([t,e],"depthwiseConv2D");for(var r=n.filterHeight,a=n.filterWidth,o=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=pr(n.outShape,t.dtype),p=this.readSync(t.dataId),f=this.readSync(e.dataId),d=l.values,h=0;h<n.batchSize;++h)for(var m=h*t.strides[0],v=h*l.strides[0],g=0;g<n.outHeight;++g)for(var y=v+g*l.strides[1],x=g*n.strideHeight-s,b=0;b<r;++b){var w=x+b*o;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=m+w*t.strides[1],S=0;S<n.outWidth;++S)for(var N=y+S*l.strides[2],I=S*n.strideWidth-u,R=0;R<a;++R){var T=I+R*i;if(!(T<0||T>=n.inWidth))for(var k=C+R*e.strides[1],A=E+T*n.inChannels,O=N,D=k,_=0;_<n.inChannels;++_){for(var F=p[A+_],M=0;M<c;++M)d[O+M]+=F*f[D+M];O+=c,D+=c}}}return l.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){vp([t,e],"depthwiseConv2DDerInput");for(var r=pr(n.inShape,"float32"),a=r.values,o=r.strides,i=o[0],s=o[1],u=o[2],c=this.readSync(t.dataId),l=t.strides,p=l[0],f=l[1],d=l[2],h=this.readSync(e.dataId),m=e.strides,v=m[0],g=m[1],y=m[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,S=n.inWidth,N=n.outChannels,I=n.outHeight,R=n.outWidth,T=n.strideHeight,k=n.strideWidth,A=b-1-n.padInfo.top,O=w-1-n.padInfo.left,D=N/C,_=0;_<x;++_)for(var F=0;F<C;++F)for(var M=0;M<E;++M)for(var B=M-A,P=Math.max(0,Math.ceil(B/T)),L=Math.min(I,(b+B)/T),V=0;V<S;++V){for(var W=V-O,z=Math.max(0,Math.ceil(W/k)),U=Math.min(R,(w+W)/k),j=0,G=P;G<L;++G)for(var H=G*T-B,q=z;q<U;++q)for(var K=p*_+f*G+d*q,X=v*(b-1-H)+g*(w-1-(q*k-W))+y*F,Y=0;Y<D;++Y)j+=c[K+(F*D+Y)]*h[X+Y];a[i*_+s*M+u*V+F]=j}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){vp([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,a=n.strideWidth,o=n.filterHeight,i=n.filterWidth,s=pr(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,p=this.bufferSync(t),f=this.bufferSync(e),d=0;d<o;++d)for(var h=Math.max(0,Math.ceil((c-d)/r)),m=Math.min(n.outHeight,(n.inHeight+c-d)/r),v=0;v<i;++v)for(var g=Math.max(0,Math.ceil((u-v)/a)),y=Math.min(n.outWidth,(n.inWidth+u-v)/a),x=0;x<n.outChannels;++x){for(var b=Math.trunc(x/l),w=x%l,C=0,E=0;E<n.batchSize;++E)for(var S=h;S<m;++S)for(var N=d+S*r-c,I=g;I<y;++I){var R=v+I*a-u;C+=p.get(E,N,R,b)*f.get(E,S,I,x)}s.set(C,d,v,b,w)}return s.toTensor()},e.prototype.tile=function(t,e){return vp(t,"tile"),qa(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){vp(t,"pad");var r=e.map((function(e,n){return e[0]+t.shape[n]+e[1]})),a=e.map((function(t){return t[0]})),o=this.bufferSync(t),i=pr(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=o.indexToLoc(s),c=u.map((function(t,e){return t+a[e]}));i.set.apply(i,[o.get.apply(o,u)].concat(c))}return i.toTensor()},e.prototype.transpose=function(t,e){vp(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var a=this.readSync(t.dataId),o=pr(n,t.dtype),i=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=i.indexToLoc(r),u=new Array(s.length),c=0;c<u.length;c++)u[c]=s[e[c]];var l=o.locToIndex(u);o.values[l]=a[r]}return o.toTensor()},e.prototype.gather=function(t,e,n){vp([t,e],"gather");var r=t.shape.slice(),a=this.readSync(e.dataId);r[n]=a.length;for(var o=pr(r,t.dtype),i=this.bufferSync(t),s=0;s<o.size;++s){var u=o.indexToLoc(s),c=u.slice();c[n]=a[u[n]];var l=i.locToIndex(c);o.values[s]=i.values[l]}return o.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){vp([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),a=Wr(t.shape,e,r),o=zr(a.length,e.length),i=Ur(t.shape,e,r),s=jr(n,e.length),u=Gr(i,n,e.length);return t.reshape(a).transpose(o).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){vp([t],"spaceToBatchND");var r=e.reduce((function(t,e){return t*e})),a=[[0,0]];a.push.apply(a,n);for(var o=1+e.length;o<t.shape.length;++o)a.push([0,0]);var i=t.pad(a),s=Wr(i.shape,e,r,!1),u=zr(s.length,e.length,!1),c=Ur(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.pool=function(t,e,n){vp(t,"pool");for(var r=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,p="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=this.readSync(t.dataId),d=pr(e.outShape,t.dtype),h=d.values,m=e.outShape[1]*e.outShape[2]*e.outShape[3],v=e.outShape[2]*e.outShape[3],g=e.outShape[3],y=0;y<e.batchSize;++y)for(var x=y*m,b=y*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var E=C*r-c,S=Math.max(0,E),N=Math.min(e.inHeight,s+E),I=x+C*v,R=0;R<e.outWidth;++R){for(var T=R*a-l,k=Math.max(0,T),A=Math.min(e.inWidth,u+T),O=p,D=0,_=0,F=S;F<N;F+=o){for(var M=b+F*t.strides[1],B=k;B<A;B+=i){var P=f[M+B*t.strides[2]+w];"max"===n&&P>O?O=P:"avg"===n&&(D+=P,_++)}if(isNaN(O))break}h[I+R*g+w]="avg"===n?D/_:O}return d.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=pr(e.outShape,"int32"),r=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,p=this.bufferSync(t),f=0;f<e.batchSize;++f)for(var d=0;d<e.inChannels;++d)for(var h=0;h<e.outHeight;++h){for(var m=h*r-c,v=m;v<0;)v+=o;for(var g=Math.min(e.inHeight,s+m),y=0;y<e.outWidth;++y){for(var x=y*a-l,b=x;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,S=v;S<g;S+=o)for(var N=S-m,I=b;I<w;I+=i){var R=I-x,T=p.get(f,S,I,d);T>C&&(C=T,E=N*u+R)}n.set(E,f,h,y,d)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){vp([e,n],"maxPoolBackprop");for(var a=this.maxPoolPositions(e,r),o=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,p=l-1-r.padInfo.left,f=c-1-r.padInfo.top,d=pr(e.shape,"float32"),h=this.bufferSync(a),m=this.bufferSync(t),v=0;v<r.batchSize;++v)for(var g=0;g<r.inChannels;++g)for(var y=0;y<r.inHeight;++y)for(var x=0;x<r.inWidth;++x){for(var b=y-f,w=x-p,C=0,E=0;E<c;E+=s){var S=(b+E)/o;if(!(S<0||S>=r.outHeight||Math.floor(S)!==S))for(var N=0;N<l;N+=u){var I=(w+N)/i;if(!(I<0||I>=r.outWidth||Math.floor(I)!==I)){var R=c*l-1-h.get(v,S,I,g)===E*l+N?1:0;0!==R&&(C+=m.get(v,S,I,g)*R)}}}d.set(C,v,y,x,g)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){vp([t,e],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,o=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,p=l-1-n.padInfo.left,f=c-1-n.padInfo.top,d=pr(e.shape,"float32"),h=1/(o*i),m=this.bufferSync(t),v=0;v<n.batchSize;++v)for(var g=0;g<n.inChannels;++g)for(var y=0;y<n.inHeight;++y)for(var x=0;x<n.inWidth;++x){for(var b=y-f,w=x-p,C=0,E=0;E<c;E+=s){var S=(b+E)/r;if(!(S<0||S>=n.outHeight||Math.floor(S)!==S))for(var N=0;N<l;N+=u){var I=(w+N)/a;I<0||I>=n.outWidth||Math.floor(I)!==I||(C+=m.get(v,S,I,g))}}d.set(C*h,v,y,x,g)}return d.toTensor()},e.prototype.pool3d=function(t,e,n){vp(t,"pool3d");for(var r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,h=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=this.readSync(t.dataId),g=pr(e.outShape,t.dtype),y=g.values,x=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;E<e.batchSize;++E)for(var S=E*x,N=E*t.strides[0],I=0;I<e.inChannels;++I)for(var R=0;R<e.outDepth;++R){for(var T=R*r-f,k=T;k<0;)k+=i;for(var A=Math.min(e.inDepth,c+T),O=S+R*b,D=0;D<e.outHeight;++D){for(var _=D*a-d,F=_;F<0;)F+=s;for(var M=Math.min(e.inHeight,l+_),B=O+D*w,P=0;P<e.outWidth;++P){for(var L=P*o-h,V=L;V<0;)V+=u;for(var W=Math.min(e.inWidth,p+L),z=B+P*C,U=m,j=0,G=0,H=k;H<A;H+=i){for(var q=N+H*t.strides[1],K=F;K<M;K+=s){for(var X=q+K*t.strides[2],Y=V;Y<W;Y+=u){var $=v[X+Y*t.strides[3]+I];if("max"===n&&$>U?U=$:"avg"===n&&(j+=$,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[z+I]="avg"===n?j/G:U}}}return g.toTensor()},e.prototype.avgPool3d=function(t,e){return vp(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){vp([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,a=n.strideHeight,o=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,p=n.dilationWidth,f=n.effectiveFilterDepth,d=n.effectiveFilterHeight,h=n.effectiveFilterWidth,m=f-1-n.padInfo.front,v=h-1-n.padInfo.left,g=d-1-n.padInfo.top,y=pr(e.shape,"float32"),x=1/(i*s*u),b=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var E=0;E<n.inDepth;++E)for(var S=0;S<n.inHeight;++S)for(var N=0;N<n.inWidth;++N){for(var I=E-m,R=S-g,T=N-v,k=0,A=0;A<f;A+=c){var O=(I+A)/r;if(!(O<0||O>=n.outDepth||Math.floor(O)!==O))for(var D=0;D<d;D+=l){var _=(R+D)/a;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var F=0;F<h;F+=p){var M=(T+F)/o;M<0||M>=n.outWidth||Math.floor(M)!==M||(k+=b.get(w,O,_,M,C))}}}y.set(k*x,w,E,S,N,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return vp(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=pr(e.outShape,"int32"),r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,h=e.padInfo.left,m=this.bufferSync(t),v=0;v<e.batchSize;++v)for(var g=0;g<e.inChannels;++g)for(var y=0;y<e.outDepth;++y){for(var x=y*r-f,b=x;b<0;)b+=i;for(var w=Math.min(e.inDepth,c+x),C=0;C<e.outHeight;++C){for(var E=C*a-d,S=E;S<0;)S+=s;for(var N=Math.min(e.inHeight,l+E),I=0;I<e.outWidth;++I){for(var R=I*o-h,T=R;T<0;)T+=u;for(var k=Math.min(e.inWidth,p+R),A=Number.NEGATIVE_INFINITY,O=-1,D=b;D<w;D+=i)for(var _=D-x,F=S;F<N;F+=s)for(var M=F-E,B=T;B<k;B+=u){var P=B-R,L=m.get(v,D,F,B,g);L>=A&&(A=L,O=_*l*p+M*l+P)}n.set(O,v,y,C,I,g)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){vp([e,n],"maxPool3dBackprop");for(var a=this.maxPool3dPositions(e,r),o=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,p=r.effectiveFilterDepth,f=r.effectiveFilterHeight,d=r.effectiveFilterWidth,h=p-1-r.padInfo.front,m=d-1-r.padInfo.left,v=f-1-r.padInfo.top,g=pr(e.shape,"float32"),y=this.bufferSync(a),x=this.bufferSync(t),b=0;b<r.batchSize;++b)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var E=0;E<r.inHeight;++E)for(var S=0;S<r.inWidth;++S){for(var N=C-h,I=E-v,R=S-m,T=0,k=0;k<p;k+=u){var A=(N+k)/o;if(!(A<0||A>=r.outDepth||Math.floor(A)!==A))for(var O=0;O<f;O+=c){var D=(I+O)/i;if(!(D<0||D>=r.outHeight||Math.floor(D)!==D))for(var _=0;_<d;_+=l){var F=(R+_)/s;if(!(F<0||F>=r.outWidth||Math.floor(F)!==F)){var M=p*f*d-1-y.get(b,A,D,F,w)===k*f*d+O*d+_?1:0;0!==M&&(T+=x.get(b,A,D,F,w)*M)}}}}g.set(T,b,C,E,S,w)}return g.toTensor()},e.prototype.cast=function(t,e){return ka(t,e,this)},e.prototype.reshape=function(t,e){return Aa(t,e)},e.prototype.avgPool=function(t,e){return vp(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){vp(t,"resizeBilinear");for(var a=t.shape,o=a[0],i=a[1],s=a[2],u=a[3],c=this.readSync(t.dataId),l=new Float32Array(D([o,e,n,u])),p=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,h=p[0]/f[0],m=p[1]/f[1],v=0;v<o;v++)for(var g=0;g<e;g++)for(var y=h*g,x=Math.floor(y),b=y-x,w=Math.min(i-1,Math.ceil(y)),C=v*t.strides[0]+x*t.strides[1],E=v*t.strides[0]+w*t.strides[1],S=0;S<n;S++)for(var N=m*S,I=Math.floor(N),R=N-I,T=Math.min(s-1,Math.ceil(N)),k=C+I*t.strides[2],A=E+I*t.strides[2],O=C+T*t.strides[2],_=E+T*t.strides[2],F=0;F<u;F++){var M=c[k+F],B=c[A+F],P=M+(c[O+F]-M)*R,L=P+(B+(c[_+F]-B)*R-P)*b;l[d++]=L}return An(l,[o,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){vp([t,e],"resizeBilinearBackprop");for(var r=e.shape,a=r[0],o=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],p=new Float32Array(a*o*i*s),f=[n&&c>1?o-1:o,n&&l>1?i-1:i],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],h=f[0]/d[0],m=f[1]/d[1],v=this.readSync(t.dataId),g=0,y=0;y<a;y++)for(var x=y*e.strides[0],b=0;b<c;b++)for(var w=b*h,C=Math.floor(w),E=Math.min(Math.ceil(w),o-1),S=x+C*e.strides[1],N=x+E*e.strides[1],I=w-C,R=1-I,T=0;T<l;T++)for(var k=T*m,A=Math.floor(k),O=Math.min(Math.ceil(k),i-1),D=k-A,_=1-D,F=S+A*e.strides[2],M=S+O*e.strides[2],B=N+A*e.strides[2],P=N+O*e.strides[2],L=R*_,V=R*D,W=I*_,z=I*D,U=0;U<s;U++){var j=v[g++];p[F+U]+=j*L,p[M+U]+=j*V,p[B+U]+=j*W,p[P+U]+=j*z}return Bn(p,[a,i,o,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){vp(t,"resizeNearestNeighbor");for(var a=t.shape,o=a[0],i=a[1],s=a[2],u=a[3],c=this.readSync(t.dataId),l=new Float32Array(o*e*n*u),p=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=p[0]/f[0],h=p[1]/f[1],m=0,v=0;v<o;v++)for(var g=v*t.strides[0],y=0;y<e;y++)for(var x=d*y,b=g+Math.min(i-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=h*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],S=0;S<u;S++){var N=c[E+S];l[m++]=N}return An(l,[o,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){vp([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,a=r[0],o=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],p=new Float32Array(a*o*i*s),f=this.readSync(t.dataId),d=[n&&c>1?o-1:o,n&&l>1?i-1:i],h=[n&&c>1?c-1:c,n&&l>1?l-1:l],m=d[0]/h[0],v=d[1]/h[1],g=1/m,y=1/v,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w<a;w++)for(var C=w*e.strides[0],E=0;E<o;E++)for(var S=C+E*e.strides[1],N=Math.floor(E*g),I=Math.floor(N-x/2),R=0;R<i;R++)for(var T=S+R*e.strides[2],k=Math.floor(R*y),A=Math.floor(k-b/2),O=0;O<s;O++){for(var D=0,_=0;_<x;_++){var F=_+I;if(!(F<0||F>=c)){var M=C+F*t.strides[1],B=F*m;if(E===Math.min(o-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+A;if(!(L<0||L>=l)){var V=M+L*t.strides[2],W=L*v;R===Math.min(i-1,n?Math.round(W):Math.floor(W))&&(D+=f[V+O])}}}}p[T+O]=D}return Bn(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,o){vp([t,e,n,a,o],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=a?this.readSync(a.dataId):new Float32Array([1]),l=o?this.readSync(o.dataId):new Float32Array([0]),p=new Float32Array(i.length),f=l.length,d=c.length,h=u.length,m=s.length,v=0,g=0,y=0,x=0,b=0;b<i.length;++b)p[b]=l[v++]+(i[b]-s[g++])*c[y++]/Math.sqrt(u[x++]+r),v>=f&&(v=0),g>=m&&(g=0),y>=d&&(y=0),x>=h&&(x=0);return Bn(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){vp(t,"localResponseNormalization4D");var o=t.shape[3],i=o-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%o,r=t-n+Math.max(0,n-e),a=t-n+Math.min(n+e,i),u=0;r<=a;r++){var c=s[r];u+=c*c}return u}for(var p=0;p<u;p++){var f=l(p),d=s[p]*Math.pow(n+r*f,-a);c[p]=d}return Bn(c,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,a,o,i){vp(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=this.readSync(n.dataId),p=new Float32Array(t.size),f=t.size,d=0;d<f;d++){for(var h=d%s,m=d-h+Math.max(0,h-r),v=d-h+Math.min(s,h+r+1),g=0,y=m;y<v;y++)g+=Math.pow(c[y],2);for(g=o*g+a,y=m;y<v;y++){var x=-2*o*i*c[y]*l[d]/g;d===y&&(x+=Math.pow(g,-i)),x*=u[d],p[y]+=x}}return Bn(p,t.shape)},e.prototype.multinomial=function(t,e,n,r){vp(t,"multinomial");for(var a=e?t:ca(t),o=a.shape[0],i=a.shape[1],s=zn([o,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(a.dataId),l=0;l<o;++l){var p=l*i,f=new Float32Array(i-1);f[0]=c[p];for(var d=1;d<f.length;++d)f[d]=f[d-1]+c[p+d];for(var h=sr(r.toString()),m=l*n,v=0;v<n;++v){var g=h();u[m+v]=f.length;for(var y=0;y<f.length;y++)if(g<f[y]){u[m+v]=y;break}}}return s},e.prototype.oneHot=function(t,e,n,r){vp(t,"oneHot");var a=new Float32Array(t.size*e);a.fill(r);for(var o=this.readSync(t.dataId),i=0;i<t.size;++i)o[i]>=0&&o[i]<e&&(a[i*e+o[i]]=n);return Fn(a,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,a){return vp(t,"nonMaxSuppression"),Va(this.readSync(t.dataId),this.readSync(e.dataId),n,r,a)},e.prototype.fft=function(t){return this.fftBatch(t,!1)},e.prototype.ifft=function(t){return this.fftBatch(t,!0)},e.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],a=pr(t.shape,"float32"),o=pr(t.shape,"float32"),i=Tn(t).as2D(n,r),s=kn(t).as2D(n,r),u=0;u<n;u++)for(var c=i.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),p=Rn(c,l),f=this.readSync(this.fftImpl(p,e).dataId),d=0;d<r;d++){var h=Fa(f,d);a.values[u*r+d]=h.real,o.values[u*r+d]=h.imag}return Rn(a.toTensor(),o.toTensor()).as2D(n,r)},e.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var a=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(a=Rn(Tn(a).div(Dn(r)),kn(a).div(Dn(r)))),a}var o=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(o,r,e));return Rn(i.real,i.imag).as2D(t.shape[0],t.shape[1])},e.prototype.isExponentOf2=function(t){return 0==(t&t-1)},e.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),a=e/2,o=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),a=0;a<t.length;a+=4)n[Math.floor(a/4)]=t[a],r[Math.floor(a/4)]=t[a+1];return{real:n,imag:r}}(r),i=Rn(o.real,o.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),a=2;a<t.length;a+=4)n[Math.floor(a/4)]=t[a],r[Math.floor(a/4)]=t[a+1];return{real:n,imag:r}}(r),u=Rn(s.real,s.imag).as1D();i=this.fftRadix2(i,a,n),u=this.fftRadix2(u,a,n);var c=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),a=0;a<Math.ceil(t/2);a++){var o=(e?2:-2)*Math.PI*(a/t);n[a]=Math.cos(o),r[a]=Math.sin(o)}return{real:n,imag:r}}(e,n),l=Rn(c.real,c.imag).mul(u),p=i.add(l),f=i.sub(l),d=Tn(p).concat(Tn(f)),h=kn(p).concat(kn(f));return Rn(d,h).as1D()},e.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),a=0;a<e;a++){for(var o=0,i=0,s=0;s<e;s++){var u=Ba(a*s,e,n),c=Fa(t,s);o+=c.real*u.real-c.imag*u.imag,i+=c.real*u.imag+c.imag*u.real}n&&(o/=e,i/=e),Ma(r,o,i,a)}return r},e.prototype.depthToSpace=function(t,e,n){T("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),T(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],a=t.shape[1],o=t.shape[2],i=t.shape[3],s=a*e,u=o*e,c=i/(e*e),l=this.readSync(t.dataId),p=new Float32Array(r*s*u*c),f=0,d=0;d<r;++d)for(var h=0;h<s;++h)for(var m=Math.floor(h/e),v=h%e,g=0;g<u;++g)for(var y=Math.floor(g/e),x=(v*e+g%e)*c,b=0;b<c;++b){var w=b+x+i*(y+o*(m+a*d));p[f++]=l[w]}return Bn(p,[r,s,u,c])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var a=va(t.shape,e.shape),o=pr(a,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=ha(t.shape,a),c=ha(e.shape,a),l=o.values;if(u.length+c.length===0)for(var p=0;p<l.length;++p)l[p]=r(i[p%i.length],s[p%s.length]);else{var f=this.bufferSync(t),d=this.bufferSync(e),h=function(n){var a=o.indexToLoc(n),p=a.slice(-t.rank);u.forEach((function(t){return p[t]=0}));var h=f.locToIndex(p),m=a.slice(-e.rank);c.forEach((function(t){return m[t]=0}));var v=d.locToIndex(m);l[n]=r(i[h],s[v])};for(p=0;p<l.length;++p)h(p)}return o.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=va(t.shape,e.shape),a=pr(r,"float32"),o=pr(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=ha(t.shape,r),c=ha(e.shape,r),l=a.values,p=o.values;if(u.length+c.length===0)for(var f=0;f<l.length;f++){var d=f%i.length,h=f%s.length,m=n(i[2*d],i[2*d+1],s[2*h],s[2*h+1]);l[f]=m.real,p[f]=m.imag}else{var v=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var o=a.indexToLoc(r),f=o.slice(-t.rank);u.forEach((function(t){return f[t]=0}));var d=v.locToIndex(f),h=o.slice(-e.rank);c.forEach((function(t){return h[t]=0}));var m=g.locToIndex(h),y=n(i[2*d],i[2*d+1],s[2*m],s[2*m+1]);l[r]=y.real,p[r]=y.imag};for(f=0;f<l.length;f++)y(f)}return this.complex(a.toTensor(),o.toTensor())},e.prototype.split=function(t,e,n){return Ha(t,e,n)},e.prototype.dispose=function(){},e.prototype.floatPrecision=function(){return 32},e.prototype.epsilon=function(){return 1e-7},e.prototype.cropAndResize=function(t,e,n,r,a,o){for(var i=t.shape,s=i[0],u=i[1],c=i[2],l=i[3],p=e.shape[0],f=r[0],d=r[1],h=pr([p,f,d,l],"float32"),m=this.readSync(e.dataId),v=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=h.strides,b=0;b<p;b++){var w=4*b,C=m[w],E=m[w+1],S=m[w+2],N=m[w+3],I=v[b];if(!(I>=s))for(var R=f>1?(S-C)*(u-1)/(f-1):0,T=d>1?(N-E)*(c-1)/(d-1):0,k=0;k<f;k++){var A=f>1?C*(u-1)+k*R:.5*(C+S)*(u-1);if(A<0||A>u-1)for(var O=0;O<d;O++)for(var D=0;D<l;D++){var _=D+O*x[2]+k*x[1]+b*x[0];h.values[_]=o}else if("bilinear"===a){var F=Math.floor(A),M=Math.ceil(A),B=A-F;for(O=0;O<d;O++)if((H=d>1?E*(c-1)+O*T:.5*(E+N)*(c-1))<0||H>c-1)for(D=0;D<l;D++)_=D+O*x[2]+k*x[1]+b*x[0],h.values[_]=o;else{var P=Math.floor(H),L=Math.ceil(H),V=H-P;for(D=0;D<l;D++){var W=g[_=D+P*y[2]+F*y[1]+I*y[0]],z=g[_=D+L*y[2]+F*y[1]+I*y[0]],U=g[_=D+P*y[2]+M*y[1]+I*y[0]],j=W+(z-W)*V,G=U+(g[_=D+L*y[2]+M*y[1]+I*y[0]]-U)*V;_=D+O*x[2]+k*x[1]+b*x[0],h.values[_]=j+(G-j)*B}}}else for(O=0;O<d;++O){var H;if((H=d>1?E*(c-1)+O*T:.5*(E+N)*(c-1))<0||H>c-1)for(D=0;D<l;D++)_=D+O*x[2]+k*x[1]+b*x[0],h.values[_]=o;else{var q=Math.round(H),K=Math.round(A);for(D=0;D<l;D++){var X=D+q*y[2]+K*y[1]+I*y[0],Y=D+O*x[2]+k*x[1]+b*x[0];h.values[Y]=g[X]}}}}}return h.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var a=Kr(0,t,n),o=a.sliceRank,i=a.numUpdates,s=a.sliceSize,u=a.strides,c=a.outputSize;return this.scatter(t,e,n,c,s,i,o,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],a=Hr(t,e),o=a[0],i=a[1],s=a[2],u=a[3];if(0===i)return An([],o,t.dtype);for(var c=new gt([i,s],t.dtype),l=this.readSync(e.dataId),p=this.readSync(t.dataId),f=0;f<i;f++){for(var d=[],h=0,m=0;m<r;m++){var v=l[f*r+m];h+=v*u[m],d.push(v)}if(h<0||h>=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var g=0;g<s;g++)c.values[f*s+g]=p[h*s+g]}return c.toTensor().reshape(o)},e.prototype.scatterND=function(t,e,n){var r=Kr(0,t,n),a=r.sliceRank,o=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=Dn(0);return this.scatter(t,e,n,u,i,o,a,s,c,!0)},e.prototype.fill=function(t,e,n){var r=j(n=n||Z(e),D(t));return r.fill(e),Lt.makeTensor(r,t,n,this)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){var e=j(t.dtype,D(t.shape));return this.makeOutput(e,t.shape,t.dtype)},e.prototype.linspace=function(t,e,n){return Oa(t,e,n)},e.prototype.scatter=function(t,e,n,r,a,o,i,s,u,c){var l=[r/a,a],p=this.readSync(t.dataId),f=this.readSync(e.dataId);if(0===r)return An([],n,e.dtype);var d=new gt(l,e.dtype);d.values.fill(this.readSync(u.dataId)[0]);for(var h=0;h<o;h++){for(var m=[],v=0,g=0;g<i;g++){var y=p[h*i+g];m.push(y),v+=y*s[g]}if(v<0||v>=r/a)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var x=0;x<a;x++)c?d.values[v*a+x]+=f[h*a+x]:d.values[v*a+x]=0===e.rank?f[0]:f[h*a+x]}return d.toTensor().reshape(n)},e}(fa);Lt.registerBackend("cpu",(function(){return new yp}),1),x({kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,a=n;vp(r,"square");for(var o=a.data.get(r.dataId).values,i=new Float32Array(o.length),s=0;s<o.length;++s){var u=o[s];i[s]=u*u}return{dataId:a.write(i,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}}),x({kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,a=e,o=a.boxes,i=a.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,p=s.softNmsSigma,f=n;vp(o,"NonMaxSuppressionWithScore");var d=Wa(f.data.get(o.dataId).values,f.data.get(i.dataId).values,u,c,l,p);return[d.selectedIndices,d.selectedScores]}}),x({kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,a=n,o=new cs(r.shape,"return x * x;");return a.runWebGLProgram(o,[r],r.dtype)}});var xp,bp=function(t){this.variableNames=["A"];var e=to(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},wp=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=to(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "};x({kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,a=e.pixels,o=r.numChannels,i="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,u=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=u[0],l=u[1],p=[l,c],d=[l,c,o];(s||i)&&(null==xp&&(xp=document.createElement("canvas").getContext("2d")),xp.canvas.width=c,xp.canvas.height=l,xp.drawImage(a,0,0,c,l),a=xp.canvas);var h=n.makeTensorInfo(p,"int32");n.texData.get(h.dataId).usage=Ut.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),a);var m=f().getBool("WEBGL_PACK")?new wp(d):new bp(d),v=n.runWebGLProgram(m,[h],"int32");return n.disposeData(h.dataId),v}}),x({kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var a=e,o=a.boxes,i=a.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,p=s.softNmsSigma,f=n,d=Wa(f.readSync(o.dataId),f.readSync(i.dataId),u,c,l,p);return[d.selectedIndices,d.selectedScores]}});var Cp=function(){function t(){}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();f().get("IS_BROWSER")&&f().setPlatform("browser",new Cp);var Ep,Sp=function(){function t(){this.util=n(12),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=f().global.fetch?f().global.fetch(t,e):(null==Ep&&(Ep=n(11)),Ep(t,e))},t.prototype.now=function(){var t=r.hrtime();return 1e3*t[0]+t[1]/1e6},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},t}();f().get("IS_NODE")&&f().setPlatform("node",new Sp);var Np={float32:4,int32:4,uint16:2,uint8:1,bool:1};function Ip(t,e){for(var n={},r=0,a=function(e){var a=e.name,o=e.dtype,i=e.shape,s=D(i),u=void 0;if("quantization"in e){var c=e.quantization;if("uint8"!==c.dtype&&"uint16"!==c.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+c.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=Np[c.dtype],p=t.slice(r,r+s*l),f="uint8"===c.dtype?new Uint8Array(p):new Uint16Array(p);if("float32"===o)u=Float32Array.from(f,(function(t){return t*c.scale+c.min}));else{if("int32"!==o)throw new Error("Unsupported dtype in weight '"+a+"': "+o);u=Int32Array.from(f,(function(t){return Math.round(t*c.scale+c.min)}))}r+=s*l}else if("string"===o){var d=D(e.shape);u=[];for(var h=0;h<d;h++){var m=new Uint32Array(t.slice(r,r+4))[0];r+=4;var v=new Uint8Array(t.slice(r,r+m));u.push(v),r+=m}}else{var g=Np[o];if(p=t.slice(r,r+s*g),"float32"===o)u=new Float32Array(p);else if("int32"===o)u=new Int32Array(p);else{if("bool"!==o)throw new Error("Unsupported dtype in weight '"+a+"': "+o);u=new Uint8Array(p)}r+=s*g}n[a]=An(u,i,o)},o=0,i=e;o<i.length;o++)a(i[o]);return n}function Rp(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach((function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)}));var r=new Uint8Array(e),a=0;return n.forEach((function(t){r.set(new Uint8Array(t.buffer),a),a+=t.byteLength})),r.buffer}var Tp=void 0!==a&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function kp(t){return Tp?a.byteLength(t):new Blob([t]).size}function Ap(t){var e=0;t.forEach((function(t){e+=t.byteLength}));var n=new Uint8Array(e),r=0;return t.forEach((function(t){n.set(new Uint8Array(t),r),r+=t.byteLength})),n.buffer}function Op(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function Dp(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:kp(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:kp(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var _p=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var a=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach((function(t){var n=t(e,r);null!==n&&a.push(n)})),a},t}(),Fp="://",Mp=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){T(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(Fp)&&(e=e.slice(0,e.indexOf(Fp))),T(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();T(null==r.managers[e],(function(){return"A model store manager is already registered for scheme '"+e+"'."})),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Bp(t){if(-1===t.indexOf(Fp))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Mp.getSchemes().join(","));return{scheme:t.split(Fp)[0],path:t.split(Fp)[1]}}function Pp(t,e,n){return void 0===n&&(n=!1),u(this,void 0,void 0,(function(){var r,a,o,i,s,u,l,p,f;return c(this,(function(c){switch(c.label){case 0:return T(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),T((r=_p.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),T(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."})),a=r[0],T((o=_p.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),T(o.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."})),i=o[0],s=Bp(t).scheme,u=Bp(t).path,l=s===Bp(t).scheme,[4,a.load()];case 1:return p=c.sent(),n&&l?[4,Mp.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,i.save(p)];case 4:return f=c.sent(),!n||l?[3,6]:[4,Mp.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,f.modelArtifactsInfo]}}))}))}var Lp="models_store",Vp="model_info_store";function Wp(){if(!f().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function zp(t){var e=t.result;e.createObjectStore(Lp,{keyPath:"modelPath"}),e.createObjectStore(Vp,{keyPath:"modelPath"})}var Up=function(){function t(t){if(this.indexedDB=Wp(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]}))}))},t.prototype.load=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){return[2,this.databaseAction(this.modelPath)]}))}))},t.prototype.databaseAction=function(t,e){var n=this;return new Promise((function(t,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return zp(a)},a.onsuccess=function(){var o=a.result;if(null==e){var i=o.transaction(Lp,"readonly"),s=i.objectStore(Lp).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return o.close(),r(s.error)},i.oncomplete=function(){return o.close()}}else{var u,c=Dp(e),l=o.transaction(Vp,"readwrite"),p=l.objectStore(Vp),f=p.put({modelPath:n.modelPath,modelArtifactsInfo:c});f.onsuccess=function(){var a=(u=o.transaction(Lp,"readwrite")).objectStore(Lp).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});a.onsuccess=function(){return t({modelArtifactsInfo:c})},a.onerror=function(t){var e=(p=l.objectStore(Vp)).delete(n.modelPath);e.onsuccess=function(){return o.close(),r(a.error)},e.onerror=function(t){return o.close(),r(a.error)}}},f.onerror=function(t){return o.close(),r(f.error)},l.oncomplete=function(){null==u?o.close():u.oncomplete=function(){return o.close()}}}},a.onerror=function(t){return r(a.error)}}))},t.URL_SCHEME="indexeddb://",t}(),jp=function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Up.URL_SCHEME)?(e=t.slice(Up.URL_SCHEME.length),new Up(e)):null;var e};_p.registerSaveRouter(jp),_p.registerLoadRouter(jp);var Gp=function(){function t(){this.indexedDB=Wp()}return t.prototype.listModels=function(){return u(this,void 0,void 0,(function(){var t=this;return c(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return zp(r)},r.onsuccess=function(){var t=r.result,a=t.transaction(Vp,"readonly"),o=a.objectStore(Vp).getAll();o.onsuccess=function(){for(var t={},n=0,r=o.result;n<r.length;n++){var a=r[n];t[a.modelPath]=a.modelArtifactsInfo}e(t)},o.onerror=function(e){return t.close(),n(o.error)},a.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}}))]}))}))},t.prototype.removeModel=function(t){return u(this,void 0,void 0,(function(){var e=this;return c(this,(function(n){var r;return t=(r=t).startsWith(Up.URL_SCHEME)?r.slice(Up.URL_SCHEME.length):r,[2,new Promise((function(n,r){var a=e.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return zp(a)},a.onsuccess=function(){var e,o=a.result,i=o.transaction(Vp,"readwrite"),s=i.objectStore(Vp),u=s.get(t);u.onsuccess=function(){if(null==u.result)return o.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var a=s.delete(t),i=function(){var a=(e=o.transaction(Lp,"readwrite")).objectStore(Lp).delete(t);a.onsuccess=function(){return n(u.result.modelArtifactsInfo)},a.onerror=function(t){return r(u.error)}};a.onsuccess=i,a.onerror=function(t){return i(),o.close(),r(u.error)}},u.onerror=function(t){return o.close(),r(u.error)},i.oncomplete=function(){null==e?o.close():e.oncomplete=function(){return o.close()}}},a.onerror=function(t){return r(a.error)}}))]}))}))},t}();if(f().getBool("IS_BROWSER"))try{Mp.registerManager(Up.URL_SCHEME,new Gp)}catch(i){}var Hp="/",qp="tensorflowjs_models",Kp="info",Xp="model_topology",Yp="weight_specs",$p="weight_data",Qp="model_metadata";function Jp(t){return{info:[qp,t,Kp].join(Hp),topology:[qp,t,Xp].join(Hp),weightSpecs:[qp,t,Yp].join(Hp),weightData:[qp,t,$p].join(Hp),modelMetadata:[qp,t,Qp].join(Hp)}}function Zp(t){var e=t.split(Hp);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(Hp)}var tf=function(){function t(t){if(!f().getBool("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=Jp(this.modelPath)}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){var e,n,r;return c(this,(function(o){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=Dp(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(t){return Tp?a.from(t).toString("base64"):btoa(String.fromCharCode.apply(null,new Uint8Array(t)))}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[2,{modelArtifactsInfo:r}]}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".")}return[2]}))}))},t.prototype.load=function(){return u(this,void 0,void 0,(function(){var t,e,n,r,o,i,s;return c(this,(function(u){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=r,null!=(o=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(o),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(Tp){var e=a.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),o=0;o<n.length;++o)r.set([n.charCodeAt(o)],o);return r.buffer}(s),[2,e]}))}))},t.URL_SCHEME="localstorage://",t}(),ef=function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(tf.URL_SCHEME)?(e=t.slice(tf.URL_SCHEME.length),new tf(e)):null;var e};_p.registerSaveRouter(ef),_p.registerLoadRouter(ef);var nf=function(){function t(){T(f().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),T(void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return t.prototype.listModels=function(){return u(this,void 0,void 0,(function(){var t,e,n,r,a,o;return c(this,(function(i){for(t={},e=qp+Hp,n=Hp+Kp,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(o=Zp(a),t[o]=JSON.parse(this.LS.getItem(a)));return[2,t]}))}))},t.prototype.removeModel=function(t){return u(this,void 0,void 0,(function(){var e,n;return c(this,(function(r){var a;if(t=(a=t).startsWith(tf.URL_SCHEME)?a.slice(tf.URL_SCHEME.length):a,e=Jp(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]}))}))},t}();if(f().getBool("IS_BROWSER"))try{Mp.registerManager(tf.URL_SCHEME,new nf)}catch(i){}function rf(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var af=function(){function t(e){if(!f().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelTopologyFileName=e+".json",this.weightDataFileName=e+".weights.bin"}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){var e,n,r,a,o,i;return c(this,(function(s){switch(s.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(o=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,o.href=a,[4,rf((function(){return o.dispatchEvent(new MouseEvent("click"))}))];case 2:return s.sent(),null==t.weightData?[3,4]:((i=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,i.href=e,[4,rf((function(){return i.dispatchEvent(new MouseEvent("click"))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:Dp(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),of=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return u(this,void 0,void 0,(function(){var t,e,n=this;return c(this,(function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(r,a){var o=new FileReader;o.onload=function(o){var i=JSON.parse(o.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void a(t)}var l=[],p=[],f=[];u.forEach((function(t){t.paths.forEach((function(t){p.push(t),f.push(null)})),l.push.apply(l,t.weights)})),u.forEach((function(t){t.paths.forEach((function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,a=p.indexOf(t);f[a]=n,-1===f.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:Ap(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy,userDefinedMetadata:i.userDefinedMetadata})},e.onerror=function(e){return a("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(c[t])}))}))}else a(new Error("weightManifest field is missing from file "+t.name))}else a(new Error("modelTopology field is missing from file "+t.name))},o.onerror=function(e){return a("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},o.readAsText(t)}))]}))}))},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map((function(t){return Op(t.name)})),a={},o=0,i=t;o<i.length;o++)i[o].paths.forEach((function(t){var o=Op(t);if(-1!==n.indexOf(o))throw new Error("Duplicate file basename found in weights manifest: '"+o+"'");if(n.push(o),-1===r.indexOf(o))throw new Error("Weight file with basename '"+o+"' is not provided.");a[t]=e[r.indexOf(o)]}));if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return a},t}();function sf(t,e,n,r){!function(t){T(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){T(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),T(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),T(e>=t,(function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e}))}(n=null==n?0:n,r=null==r?1:r);var a=0;return Promise.all(t.map((function(o){return o.then((function(o){var i=n+ ++a/t.length*(r-n);return e(i),o})),o})))}function uf(t,e){return u(this,void 0,void 0,(function(){var n,r,a,o,i,s,u,l,p;return c(this,(function(c){switch(c.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?f().platform.fetch:e.fetchFunc,r=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,o=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return i=c.sent(),[3,4];case 2:return[4,sf(r,e.onProgress,a,o)];case 3:i=c.sent(),c.label=4;case 4:return s=i.map((function(t){return t.arrayBuffer()})),u=.5,l=1,null!=e.onProgress?[3,6]:[4,Promise.all(s)];case 5:return p=c.sent(),[3,8];case 6:return[4,sf(s,e.onProgress,u,l)];case 7:p=c.sent(),c.label=8;case 8:return[2,p]}}))}))}function cf(t){var e=this;return function(n,r,a){return void 0===r&&(r=""),u(e,void 0,void 0,(function(){var e,o,i,s,u,l,p,f,d,h;return c(this,(function(c){switch(c.label){case 0:if(e=n.map((function(){return!1})),o={},i=null!=a?a.map((function(){return!1})):[],s=[],n.forEach((function(t,n){var r=0;t.weights.forEach((function(t){var u="quantization"in t?t.quantization.dtype:t.dtype,c=Np[u]*D(t.shape),l=function(){e[n]=!0,null==o[n]&&(o[n]=[]),o[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=a?a.forEach((function(e,n){e===t.name&&(l(),i[n]=!0)})):l(),s.push(t.name),r+=c}))})),!i.every((function(t){return t})))throw u=a.filter((function(t,e){return!i[e]})),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),p=[],l.forEach((function(t){n[t].paths.forEach((function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)}))})),[4,t(p)];case 1:return f=c.sent(),d={},h=0,l.forEach((function(t){for(var e=n[t].paths.length,r=0,a=0;a<e;a++)r+=f[h+a].byteLength;for(var i=new ArrayBuffer(r),s=new Uint8Array(i),u=0,c=0;c<e;c++){var l=new Uint8Array(f[h+c]);s.set(l,u),u+=l.byteLength}o[t].forEach((function(t){var e=Ip(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)d[n]=e[n]})),h+=e})),[2,d]}}))}))}}_p.registerSaveRouter((function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(af.URL_SCHEME)?function(t){return void 0===t&&(t="model"),new af(t)}(t.slice(af.URL_SCHEME.length)):null}));var lf=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(T("function"==typeof e.fetchFunc,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=e.fetchFunc):this.fetch=f().platform.fetch,T(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&T(2===t.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."})),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){var e,n,r,a;return c(this,(function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=o.sent()).ok)return[2,{modelArtifactsInfo:Dp(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return u(this,void 0,void 0,(function(){var t,e,n,r,a,o,i,s,u,l,p,f;return c(this,(function(c){switch(c.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=c.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");c.label=2;case 2:return c.trys.push([2,4,,5]),[4,t.json()];case 3:return e=c.sent(),[3,5];case 4:throw c.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,o=e.generatedBy,i=e.convertedBy,s=e.format,u=e.userDefinedMetadata,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:f=c.sent(),l=f[0],p=f[1],c.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:p,userDefinedMetadata:u,generatedBy:o,convertedBy:i,format:s}]}}))}))},t.prototype.loadWeights=function(t){return u(this,void 0,void 0,(function(){var e,n,r,a,o,i,s,u,l,p,f;return c(this,(function(c){switch(c.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],o=this.weightPathPrefix||r,i=[],s=0,u=t;s<u.length;s++)l=u[s],i.push.apply(i,l.weights);return p=[],t.forEach((function(t){t.paths.forEach((function(t){p.push(o+t+a)}))})),[4,uf(p,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=c.sent(),[2,[i,Ap(f)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function pf(t){return null!=t.match(lf.URL_SCHEME_REGEX)}var ff=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every((function(t){return pf(t)})):pf(t))?df(t,{onProgress:e}):null};function df(t,e){return new lf(t,e)}_p.registerSaveRouter(ff),_p.registerLoadRouter(ff);var hf,mf=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){return[2,this.modelArtifacts]}))}))},t}(),vf=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){return[2,this.saveHandler(t)]}))}))},t}(),gf=Object.freeze({browserFiles:function(t){return new of(t)},browserHTTPRequest:function(t,e){return df(t,e)},concatenateArrayBuffers:Ap,decodeWeights:Ip,encodeWeights:function(t,e){return u(this,void 0,void 0,(function(){var n,r,a,o,i,s=this;return c(this,(function(l){switch(l.label){case 0:for(n=[],r=[],a=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t),o=function(o){var i=a[o],l=Array.isArray(t)?t[o].tensor:t[i];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+i+"': "+l.dtype);var p={name:i,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var f=new Promise((function(t){return u(s,void 0,void 0,(function(){var e,n,r,a,o,i,s;return c(this,(function(u){switch(u.label){case 0:return[4,l.bytes()];case 1:for(e=u.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+4*e.length,r=new Uint8Array(n),a=0,o=0;o<e.length;o++)i=e[o],s=new Uint8Array(new Uint32Array([i.length]).buffer),r.set(s,a),a+=4,r.set(i,a),a+=i.length;return t(r),[2]}}))}))}));r.push(f)}else r.push(l.data());null!=e&&(p.group=e),n.push(p)},i=0;i<a.length;++i)o(i);return[4,Promise.all(r)];case 1:return[2,{data:Rp(l.sent()),specs:n}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new mf(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new mf({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new mf({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return _p.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:Dp,getSaveHandlers:function(t){return _p.getSaveHandlers(t)},http:df,isHTTPScheme:pf,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),u(this,void 0,void 0,(function(){return c(this,(function(a){return[2,cf((function(t){return uf(t,{requestInit:r})}))(t,e,n)]}))}))},registerLoadRouter:function(t){return _p.registerLoadRouter(t)},registerSaveRouter:function(t){return _p.registerSaveRouter(t)},weightsLoaderFactory:cf,withSaveHandler:function(t){return new vf(t)},copyModel:function(t,e){return u(this,void 0,void 0,(function(){return c(this,(function(n){return[2,Pp(t,e,!1)]}))}))},listModels:function(){return u(this,void 0,void 0,(function(){var t,e,n,r,a,o,i;return c(this,(function(s){switch(s.label){case 0:t=Mp.getSchemes(),e={},n=0,r=t,s.label=1;case 1:return n<r.length?(a=r[n],[4,Mp.getManager(a).listModels()]):[3,4];case 2:for(i in o=s.sent())e[a+Fp+i]=o[i];s.label=3;case 3:return n++,[3,1];case 4:return[2,e]}}))}))},moveModel:function(t,e){return u(this,void 0,void 0,(function(){return c(this,(function(n){return[2,Pp(t,e,!0)]}))}))},removeModel:function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return e=Bp(t),[2,Mp.getManager(e.scheme).removeModel(e.path)]}))}))}}),yf=In({confusionMatrix_:function(t,e,n){var r=hn(t,"labels","confusionMatrix"),a=hn(e,"predictions","confusionMatrix");T(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),T(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),T(1===a.rank,(function(){return"Expected the rank of predictions to be 1, but got "+a.rank})),T(r.shape[0]===a.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+a.shape[0]+". Labels and predictions should have the same number of elements."})),T(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var o=Cr(r.asType("int32"),n),i=Cr(a.asType("int32"),n);return o.transpose().matMul(i).asType("int32")}}),xf=Object.freeze({confusionMatrix:yf}),bf=In({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,a=!1,o=!1,i=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)o=!0;else{if(null==t.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);i=!0}if(a&&a&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(null!=v("FromPixels",Lt.backendName))return Lt.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,c=a?[t.videoWidth,t.videoHeight]:[t.width,t.height],l=c[0],p=c[1];if(i?s=t.getContext("2d").getImageData(0,0,l,p).data:r||n?s=t.data:(o||a)&&(null==hf&&(hf=document.createElement("canvas").getContext("2d")),hf.canvas.width=l,hf.canvas.height=p,hf.drawImage(t,0,0,l,p),s=hf.getImageData(0,0,l,p).data),4===e)u=new Int32Array(s);else{var f=l*p;u=new Int32Array(f*e);for(var d=0;d<f;d++)for(var h=0;h<e;++h)u[d*e+h]=s[4*d+h]}return Mn(u,[p,l,e],"int32")}}),wf=Object.freeze({toPixels:function(t,e){return u(this,void 0,void 0,(function(){var n,r,a,o,i,s,u,l,p,f,d,h,m,v,g,y,x,b,w,C,E,S,N;return c(this,(function(c){switch(c.label){case 0:if(n=hn(t,"img","toPixels"),t instanceof wt||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],o=r[1],(i=2===n.rank?1:n.shape[2])>4||2===i)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return[4,n.data()];case 1:return s=c.sent(),u=n.min(),l=n.max(),[4,Promise.all([u.data(),l.data()])];case 2:if(p=c.sent(),f=p[0],d=p[1],h=f[0],m=d[0],u.dispose(),l.dispose(),"float32"===n.dtype){if(h<0||m>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+h+" - "+m+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(h<0||m>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+h+" - "+m+"].")}for(v="float32"===n.dtype?255:1,g=new Uint8ClampedArray(o*a*4),y=0;y<a*o;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===i?(x=s[y]*v,b=s[y]*v,w=s[y]*v,C=255):3===i?(x=s[3*y]*v,b=s[3*y+1]*v,w=s[3*y+2]*v,C=255):4===i&&(x=s[4*y]*v,b=s[4*y+1]*v,w=s[4*y+2]*v,C=s[4*y+3]*v),g[0+(E=4*y)]=Math.round(x),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=o,e.height=a,S=e.getContext("2d"),N=new ImageData(g,o,a),S.putImageData(N,0,0)),n!==t&&n.dispose(),[2,g]}}))}))},fromPixels:bf}),Cf=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Ef=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function Sf(t){T(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),T("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),T(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),Ef.register(t)}var Nf=Object.freeze({Serializable:Cf,SerializationMap:Ef,registerClass:Sf});function If(){return 32===Lt.backend.floatPrecision()?.001:.1}function Rf(t,e,n){var r=!0;if((K(t)||K(e))&&(r=!1),K(t)&&K(e)&&(r=!0),r){var a=t.constructor.name,o=e.constructor.name;if(a!==o)throw new Error("Arrays are of different type. Actual: "+a+". Expected: "+o)}if(Array.isArray(t)&&Array.isArray(e)){var i=fn(t),s=fn(e);if(!_(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=K(t)?t:O(t),c=K(e)?e:O(e);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+".\nActual: "+u+".\nExpected: "+c+".");for(var l=0;l<c.length;++l){var p=u[l],f=c[l];if(!n(p,f))throw new Error("Arrays differ: actual["+l+"] = "+p+", expected["+l+"] = "+f+".\nActual: "+u+".\nExpected: "+c+".")}}function Tf(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var kf=Object.freeze({TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(t,e,n){return null==n&&(n=If()),Rf(t,e,(function(t,e){return Tf(t,e,n)}))},testEpsilon:If,expectPromiseToFail:function(t,e){t().then((function(){return e.fail()}),(function(){return e()}))},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return $(t)||$(t[0])||$(e)||$(e[0])?Rf(t,n,(function(t,e){return t==e})):Rf(t,e,(function(t,e){return Tf(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=If()),!Tf(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),Af="1.5.1",Of=Object.freeze({gpgpu_util:Ci,webgl_util:ze,forceHalfFloat:function(){f().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Ts,setWebGLContext:qt,GPGPUContext:Ei}),Df=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),a=r.value,o=r.grads;if(null!=n){var i=n.map((function(t){return{name:t.name,tensor:o[t.name]}}));this.applyGradients(i)}else this.applyGradients(o);return Je(o),e?a:(a.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return ia(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Je(this.iterations_)},e.prototype.saveIterations=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:Dn(this.iterations_,"int32")}]}))}))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},e.prototype.extractIterations=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}}))}))},e}(Cf);Object.defineProperty(Df,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var _f=function(t){function e(e,n,r){void 0===r&&(r=null);var a=t.call(this)||this;return a.learningRate=e,a.rho=n,a.epsilon=r,a.accumulatedGrads=[],a.accumulatedUpdates=[],null==r&&(a.epsilon=Lt.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Lt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Qe((function(){return qn(a).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Qe((function(){return qn(a).variable(!1)}))});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Qe((function(){var t=i.mul(e.rho).add(o.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(o),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(a);a.assign(u)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Je(this.accumulatedGrads.map((function(t){return t.variable}))),Je(this.accumulatedUpdates.map((function(t){return t.variable}))))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedUpdates=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="Adadelta",e}(Df);Sf(_f);var Ff=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Lt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Qe((function(){return Un(a.shape,e.initialAccumulatorValue).variable(!1)}))});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var i=e.accumulatedGrads[r].variable;Qe((function(){var t=i.add(o.square());i.assign(t);var n=o.div(t.add(Lt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(a);a.assign(n)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Je(this.accumulatedGrads.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(Df);Sf(Ff);var Mf=function(t){function e(e,n,r,a){void 0===a&&(a=null);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=a,o.accumulatedFirstMoment=[],o.accumulatedSecondMoment=[],Qe((function(){o.accBeta1=Dn(n).variable(),o.accBeta2=Dn(r).variable()})),null==a&&(o.epsilon=Lt.backend.epsilon()),o}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Qe((function(){var r=$u(1,e.accBeta1),a=$u(1,e.accBeta2);n.forEach((function(n,o){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[o]&&(e.accumulatedFirstMoment[o]={originalName:n+"/m",variable:Qe((function(){return qn(i).variable(!1)}))}),null==e.accumulatedSecondMoment[o]&&(e.accumulatedSecondMoment[o]={originalName:n+"/v",variable:Qe((function(){return qn(i).variable(!1)}))});var s=Array.isArray(t)?t[o].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[o].variable,c=e.accumulatedSecondMoment[o].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),f=l.div(r),d=p.div(a);u.assign(l),c.assign(p);var h=f.div(d.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(h)}})),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))})),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Je(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&Je(this.accumulatedSecondMoment.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){var e,n=this;return c(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Qe((function(){n.accBeta1.assign(qu(n.beta1,n.iterations_+1)),n.accBeta2.assign(qu(n.beta2,n.iterations_+1))})),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedSecondMoment=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(Df);Sf(Mf);var Bf=function(t){function e(e,n,r,a,o){void 0===a&&(a=null),void 0===o&&(o=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=a,i.decay=o,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Qe((function(){i.iteration=Dn(0).variable(),i.accBeta1=Dn(n).variable()})),null==a&&(i.epsilon=Lt.backend.epsilon()),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Qe((function(){var r=$u(1,e.accBeta1),a=Fu(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,o){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[o]&&(e.accumulatedFirstMoment[o]={originalName:n+"/m",variable:qn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[o]&&(e.accumulatedWeightedInfNorm[o]={originalName:n+"/v",variable:qn(i).variable(!1)});var s=Array.isArray(t)?t[o].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[o].variable,c=e.accumulatedWeightedInfNorm[o].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=c.mul(e.beta2),f=s.abs(),d=p.maximum(f);u.assign(l),c.assign(d);var h=a.div(r).mul(l.div(d.add(e.epsilon))).add(i);i.assign(h)}})),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))})),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Je(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&Je(this.accumulatedWeightedInfNorm.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("setWeights() is not implemented for Adamax yet.")}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(Df);Sf(Bf);var Pf=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var o=Lt.registeredVariables[n];Qe((function(){var t=e.c.mul(a).add(o);o.assign(t)}))}})),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Ze(Dn(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(Df);Sf(Pf);var Lf=function(t){function e(e,n,r){void 0===r&&(r=!1);var a=t.call(this,e)||this;return a.learningRate=e,a.momentum=n,a.useNesterov=r,a.accumulations=[],a.m=Dn(a.momentum),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Lt.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:Qe((function(){return qn(a).variable(!1)}))});var o=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Qe((function(){var t,n=e.m.mul(o).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(a):e.c.mul(n).add(a),o.assign(n),a.assign(t)}))})),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Je(this.accumulations.map((function(t){return t.variable})))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="Momentum",e}(Pf);Sf(Lf);var Vf=function(t){function e(e,n,r,a,o){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=null),void 0===o&&(o=!1);var i=t.call(this)||this;return i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=a,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=o,null==a&&(i.epsilon=Lt.backend.epsilon()),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Lt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Qe((function(){return qn(a).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Qe((function(){return qn(a).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Qe((function(){return qn(a).variable(!1)}))});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Qe((function(){var t=i.mul(e.decay).add(o.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(o.mul(1-e.decay)),c=s.mul(e.momentum).add(o.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(c);var l=a.sub(c);a.assign(l)}else{var p=i.mul(e.decay).add(o.square().mul(1-e.decay));c=s.mul(e.momentum).add(o.mul(e.learningRate).div(p.add(e.epsilon).sqrt())),i.assign(p),s.assign(c),l=a.sub(c),a.assign(l)}}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Je(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&Je(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&Je(this.accumulatedMoments.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedMoments=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}))),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(Df);Sf(Vf);var Wf=function(){function t(){}return t.sgd=function(t){return new Pf(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Lf(t,e,n)},t.rmsprop=function(t,e,n,r,a){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new Vf(t,e,n,r,a)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new Mf(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new _f(t,e,n)},t.adamax=function(t,e,n,r,a){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new Bf(t,e,n,r,a)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new Ff(t,e)},t}(),zf={sgd:Wf.sgd,momentum:Wf.momentum,adadelta:Wf.adadelta,adagrad:Wf.adagrad,rmsprop:Wf.rmsprop,adamax:Wf.adamax,adam:Wf.adam},Uf="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:void 0!==o?o:function(t){return t()};function jf(){return new Promise((function(t){return Uf((function(){return t()}))}))}xt=mp}.call(this,n(1),n(3),n(4).Buffer,n(8).setImmediate)},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){"use strict";(function(t){n.d(e,"a",(function(){return ot}));var r,a,o,i=n(0),s=function(){return(s=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t}).apply(this,arguments)};
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/function u(t,e,n,r){return new(n||(n=Promise))((function(a,o){function i(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(i,s)}u((r=r.apply(t,e||[])).next())}))}function c(t,e){var n,r,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=e.call(t,i)}catch(t){o=[6,t],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}(o=r||(r={}))[o.DT_INVALID=0]="DT_INVALID",o[o.DT_FLOAT=1]="DT_FLOAT",o[o.DT_DOUBLE=2]="DT_DOUBLE",o[o.DT_INT32=3]="DT_INT32",o[o.DT_UINT8=4]="DT_UINT8",o[o.DT_INT16=5]="DT_INT16",o[o.DT_INT8=6]="DT_INT8",o[o.DT_STRING=7]="DT_STRING",o[o.DT_COMPLEX64=8]="DT_COMPLEX64",o[o.DT_INT64=9]="DT_INT64",o[o.DT_BOOL=10]="DT_BOOL",o[o.DT_QINT8=11]="DT_QINT8",o[o.DT_QUINT8=12]="DT_QUINT8",o[o.DT_QINT32=13]="DT_QINT32",o[o.DT_BFLOAT16=14]="DT_BFLOAT16",o[o.DT_FLOAT_REF=101]="DT_FLOAT_REF",o[o.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",o[o.DT_INT32_REF=103]="DT_INT32_REF",o[o.DT_UINT8_REF=104]="DT_UINT8_REF",o[o.DT_INT16_REF=105]="DT_INT16_REF",o[o.DT_INT8_REF=106]="DT_INT8_REF",o[o.DT_STRING_REF=107]="DT_STRING_REF",o[o.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",o[o.DT_INT64_REF=109]="DT_INT64_REF",o[o.DT_BOOL_REF=110]="DT_BOOL_REF",o[o.DT_QINT8_REF=111]="DT_QINT8_REF",o[o.DT_QUINT8_REF=112]="DT_QUINT8_REF",o[o.DT_QINT32_REF=113]="DT_QINT32_REF",o[o.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",function(t){!function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(t.CheckpointFormatVersion||(t.CheckpointFormatVersion={}))}(a||(a={}));var l={};function p(t){return l[t]}function f(t,e,n,r){var a=e.inputParams[t];if(a&&void 0!==a.inputIndexStart){var o=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?o+1:a.inputIndexEnd;if("tensor"===a.type)return d(e.inputNames[a.inputIndexStart],n,r);if("tensors"===a.type)return e.inputNames.slice(o,i).map((function(t){return d(t,n,r)}));var s=Array.prototype.slice.call(d(e.inputNames.slice(o)[0],n,r).dataSync());return"number"===a.type?s[0]:s}var u=e.attrParams[t];return u&&u.value}function d(t,e,n){var r=v(t),a=r[0],o=r[1],i=n.currentContextIds.find((function(t){return!!e[m(a,t)]}));return void 0!==i?e[m(a,i)][o]:void 0}function h(t,e){var n=v(t),r=n[0],a=n[1];return[m(r,e&&e.currentContextId),a]}function m(t,e){return e?t+"-"+e:t}function v(t){var e=t.lastIndexOf(":");return-1===e?[t,0]:[t.substring(0,e),Number(t.substring(e+1))]}function g(t,e){for(var n=[],r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}var y=Object.freeze({json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),x=Object.freeze({json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),b=Object.freeze({json:[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"}]}]}),w=Object.freeze({json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]}]}),C=Object.freeze({json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]}),E=Object.freeze({json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),S=Object.freeze({json:[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}]}),N=Object.freeze({json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),I=Object.freeze({json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}]}),R=Object.freeze({json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),T=Object.freeze({json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),k=Object.freeze({json:[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),A=Object.freeze({json:[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]}]}),O=Object.freeze({json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),D=Object.freeze({json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),_=Object.freeze({json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]}]}),F=function(){function t(){var t=[y,x,b,w,C,E,S,R,I,N,T,k,A,O,D,_],e=[].concat.apply([],t.map((function(t){return t.json})));this.opMappers=e.reduce((function(t,e){return t[e.tfOpName]=e,t}),{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.transformGraph=function(t,e){var n=this;void 0===e&&(e={});var r=[],a=[],o=t.node.reduce((function(t,e){return t[e.name]=n.mapNode(e),e.op.startsWith("Placeholder")&&r.push(t[e.name]),"Const"===e.op&&a.push(t[e.name]),t}),{}),i=[],s=[],u={},c={};null!=e&&(u=this.mapSignatureEntries(e.inputs),c=this.mapSignatureEntries(e.outputs));var l=Object.keys(o);return l.forEach((function(t){var e=o[t];e.inputNames.forEach((function(t){var n=h(t)[0];e.inputs.push(o[n]),o[n].children.push(e)}))})),0===Object.keys(c).length?l.forEach((function(t){var e=o[t];0===e.children.length&&s.push(e)})):Object.keys(c).forEach((function(t){var e=h(t)[0],n=o[e];null!=n&&(n.signatureKey=c[t],s.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((function(t){var e=h(t)[0],n=o[e];n&&(n.signatureKey=u[t],i.push(n))})):i=r,{nodes:o,inputs:i,outputs:s,weights:a,placeholders:r,signature:e}},t.prototype.mapSignatureEntries=function(t){return Object.keys(t||{}).reduce((function(e,n){return e[t[n].name]=n,e}),{})},t.prototype.mapNode=function(t){var e=p(t.op)||this.opMappers[t.op]||{};null==t.attr&&(t.attr={});var n={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map((function(t){return t.startsWith("^")?t.substr(1):t})),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return null!=e.inputs&&(n.inputParams=e.inputs.reduce((function(t,e){return t[e.name]={type:e.type,inputIndexStart:e.start,inputIndexEnd:e.end},t}),{})),null!=e.attrs&&(n.attrParams=e.attrs.reduce((function(e,n){var r=n.type,a=void 0;switch(n.type){case"string":void 0===(a=B(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=B(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":void 0===(a=H(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=H(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":void 0===(a=L(t.attr,n.tfName,n.defaultValue||0))&&n.tfDeprecatedName&&(a=L(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":void 0===(a=G(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=G(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":void 0===(a=P(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=P(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":void 0===(a=K(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=K(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":void 0===(a=j(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=j(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":void 0===(a=q(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=q(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":void 0===(a=W(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=W(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":void 0===(a=z(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=z(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+n.type+" for op: "+t.op)}return e[n.name]={value:a,type:r},e}),{})),n},t}();function M(e,n){var r=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){var n=Object(i.env)().global;if(void 0!==n.atob)return n.atob(e);if(void 0!==t)return new t(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return n?r:r.toLowerCase()}function B(t,e,n,r){void 0===r&&(r=!1);var a=t[e];return null!=a?M(a.s,r):n}function P(t,e,n){var r=t[e];return r?r.b:n}function L(t,e,n){var r=t[e]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof a?a:parseInt(a,10)}function V(t){switch("string"==typeof t&&(t=r[t]),t){case r.DT_FLOAT:return"float32";case r.DT_INT32:case r.DT_INT64:return"int32";case r.DT_BOOL:return"bool";case r.DT_DOUBLE:return"float32";case r.DT_STRING:return"string";default:return null}}function W(t,e,n){var r=t[e];return r&&r.type?V(r.type):n}function z(t,e,n){var r=t[e];return r&&r.list&&r.list.type?r.list.type.map((function(t){return V(t)})):n}function U(t){if(!t.unknownRank)return null!=t.dim?t.dim.map((function(t){return"number"==typeof t.size?t.size:parseInt(t.size,10)})):[]}function j(t,e,n){var r=t[e];return r&&r.shape?U(r.shape):n}function G(t,e,n){var r=t[e];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((function(t){return"number"==typeof t?t:parseInt(t,10)})):n}function H(t,e,n,r){void 0===r&&(r=!1);var a=t[e];return a&&a.list&&a.list.s?a.list.s.map((function(t){return M(t,r)})):n}function q(t,e,n){var r=t[e];return r&&r.list&&r.list.shape?r.list.shape.map((function(t){return U(t)})):n}function K(t,e,n){var r=t[e];return r&&r.list&&r.list.b?r.list.b:n}var X=function(){function t(t,e,n){var r=this;this.node=t,this.tensorMap=e,this.context=n,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map((function(t){return r.getInput(t)})),null!=t.rawAttrs&&(this.attrs=Object.keys(t.rawAttrs).reduce((function(t,e){return t[e]=r.getAttr(e),t}),{}))}return t.prototype.getInput=function(t){return d(t,this.tensorMap,this.context)},t.prototype.getAttr=function(t,e){var n=this.node.rawAttrs[t];if(null!=n.tensor)return d(t,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return L(this.node.rawAttrs,t,e);if(null!=n.s)return B(this.node.rawAttrs,t,e);if(null!=n.b)return P(this.node.rawAttrs,t,e);if(null!=n.shape)return j(this.node.rawAttrs,t,e);if(null!=n.type)return W(this.node.rawAttrs,t,e);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return G(this.node.rawAttrs,t,e);if(null!=n.list.s)return H(this.node.rawAttrs,t,e);if(null!=n.list.shape)return q(this.node.rawAttrs,t,e);if(null!=n.list.b)return K(this.node.rawAttrs,t,e);if(null!=n.list.type)return z(this.node.rawAttrs,t,e)}return e},t}(),Y=function(){function t(e,n,r,a,o,i,s){this.name=e,this.dtype=n,this.maxSize=r,this.elementShape=a,this.identicalElementShapes=o,this.dynamicSize=i,this.clearAfterRead=s,this.tensors=[],this.closed_=!1,this.id=t.nextId++}return Object.defineProperty(t.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),t.prototype.clearAndClose=function(){this.tensors.forEach((function(t){return t.tensor.dispose()})),this.tensors=[],this.closed_=!0},t.prototype.size=function(){return this.tensors.length},t.prototype.read=function(t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||t>=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map((function(t){return e.read(t)}))},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach((function(t,r){return n.write(t,e[r])}))},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n<this.size();n++)t.push(n)}if(0===t.length)return Object(i.tensor)([],[0].concat(this.elementShape));var r=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),Object(i.stack)(r,0)},t.prototype.concat=function(t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+t);if(0===this.size())return Object(i.tensor)([],[0].concat(this.elementShape));for(var e=[],n=0;n<this.size();n++)e.push(n);var r=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),Object(i.concat)(r,0)},t.prototype.scatter=function(t,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(t.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+e.shape[0]);var n=Math.max.apply(Math,t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error("Max index must be < array size ("+n+" vs. "+this.maxSize+")");this.writeMany(t,Object(i.unstack)(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,a=t.map((function(t){return r+=t}));if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var o=0===r?0:e.size/r,s=[];Object(i.tidy)((function(){e=e.reshape([1,r,o]);for(var u=0;u<t.length;++u){var c=[0,0===u?0:a[u-1],0],l=[1,t[u],o];s[u]=Object(i.slice)(e,c,l).reshape(n.elementShape)}return s}));for(var u=[],c=0;c<t.length;c++)u[c]=c;this.writeMany(u,s)},t.prototype.assertShapesMatchAllowUndefinedSize=function(t,e,n){void 0===n&&(n=""),i.util.assert(this.shapesEqualAllowUndefinedSize(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))},t.prototype.shapesEqualAllowUndefinedSize=function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(-1!==t[n]&&-1!==e[n]&&t[n]!==e[n])return!1;return!0},t.nextId=0,t}();function $(t,e,n){var r=function(t,e,n){switch(t.category){case"arithmetic":return function(t,e,n){switch(t.op){case"BiasAdd":case"AddV2":case"Add":return[Object(i.add)(f("a",t,e,n),f("b",t,e,n))];case"AddN":return[Object(i.addN)(f("tensors",t,e,n))];case"FloorMod":case"Mod":return[Object(i.mod)(f("a",t,e,n),f("b",t,e,n))];case"Mul":return[Object(i.mul)(f("a",t,e,n),f("b",t,e,n))];case"RealDiv":case"Div":return[Object(i.div)(f("a",t,e,n),f("b",t,e,n))];case"DivNoNan":return[Object(i.divNoNan)(f("a",t,e,n),f("b",t,e,n))];case"FloorDiv":return[Object(i.floorDiv)(f("a",t,e,n),f("b",t,e,n))];case"Sub":return[Object(i.sub)(f("a",t,e,n),f("b",t,e,n))];case"Minimum":return[Object(i.minimum)(f("a",t,e,n),f("b",t,e,n))];case"Maximum":return[Object(i.maximum)(f("a",t,e,n),f("b",t,e,n))];case"Pow":return[Object(i.pow)(f("a",t,e,n),f("b",t,e,n))];case"SquaredDifference":return[Object(i.squaredDifference)(f("a",t,e,n),f("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"basic_math":return function(t,e,n){switch(t.op){case"Abs":case"ComplexAbs":return[Object(i.abs)(f("x",t,e,n))];case"Acos":return[Object(i.acos)(f("x",t,e,n))];case"Acosh":return[Object(i.acosh)(f("x",t,e,n))];case"Asin":return[Object(i.asin)(f("x",t,e,n))];case"Asinh":return[Object(i.asinh)(f("x",t,e,n))];case"Atan":return[Object(i.atan)(f("x",t,e,n))];case"Atan2":return[Object(i.atan2)(f("x",t,e,n),f("y",t,e,n))];case"Atanh":return[Object(i.atanh)(f("x",t,e,n))];case"Ceil":return[Object(i.ceil)(f("x",t,e,n))];case"Complex":return[Object(i.complex)(f("real",t,e,n),f("imag",t,e,n))];case"Cos":return[Object(i.cos)(f("x",t,e,n))];case"Cosh":return[Object(i.cosh)(f("x",t,e,n))];case"Elu":return[Object(i.elu)(f("x",t,e,n))];case"Erf":return[Object(i.erf)(f("x",t,e,n))];case"Exp":return[Object(i.exp)(f("x",t,e,n))];case"Expm1":return[Object(i.expm1)(f("x",t,e,n))];case"Floor":return[Object(i.floor)(f("x",t,e,n))];case"Log":return[Object(i.log)(f("x",t,e,n))];case"Log1p":return[Object(i.log1p)(f("x",t,e,n))];case"Imag":return[Object(i.imag)(f("x",t,e,n))];case"Neg":return[Object(i.neg)(f("x",t,e,n))];case"Reciprocal":return[Object(i.reciprocal)(f("x",t,e,n))];case"Real":return[Object(i.real)(f("x",t,e,n))];case"Relu":return[Object(i.relu)(f("x",t,e,n))];case"Round":return[Object(i.round)(f("x",t,e,n))];case"Selu":return[Object(i.selu)(f("x",t,e,n))];case"Sigmoid":return[Object(i.sigmoid)(f("x",t,e,n))];case"Sin":return[Object(i.sin)(f("x",t,e,n))];case"Sign":return[Object(i.sign)(f("x",t,e,n))];case"Sinh":return[Object(i.sinh)(f("x",t,e,n))];case"Softplus":return[Object(i.softplus)(f("x",t,e,n))];case"Sqrt":return[Object(i.sqrt)(f("x",t,e,n))];case"Square":return[Object(i.square)(f("x",t,e,n))];case"Tanh":return[Object(i.tanh)(f("x",t,e,n))];case"Tan":return[Object(i.tan)(f("x",t,e,n))];case"Relu6":case"ClipByValue":return[Object(i.clipByValue)(f("x",t,e,n),f("clipValueMin",t,e,n),f("clipValueMax",t,e,n))];case"Rsqrt":return[Object(i.rsqrt)(d(t.inputNames[0],e,n))];case"Prod":return[Object(i.prod)(f("x",t,e,n),f("axes",t,e,n))];case"LeakyRelu":return[Object(i.leakyRelu)(f("x",t,e,n),f("alpha",t,e,n))];case"Prelu":return[Object(i.prelu)(f("x",t,e,n),f("alpha",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"control":return function(t,e,n){return u(this,void 0,void 0,(function(){var r,a,o,s,u,l,p,h,m,v,g,y,x,b,w,C,E,S,N,I,R,T,k,A,O,D,_,F,M,B,P,L,V,W,z;return c(this,(function(c){switch(c.label){case 0:switch(t.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[f("pred",t,e,n).clone()]];case 2:return r=f("pred",t,e,n),a=f("data",t,e,n),[4,r.data()];case 3:return[2,c.sent()[0]?[void 0,a.clone()]:[a.clone(),void 0]];case 4:return[2,(o=t.inputNames.find((function(t){return void 0!==d(t,e,n)})))?[d(o,e,n).clone()]:void 0];case 5:return s=f("frameName",t,e,n),u=f("tensor",t,e,n),n.enterFrame(s),[2,[u.clone()]];case 6:return l=f("tensor",t,e,n),n.exitFrame(),[2,[l.clone()]];case 7:return p=f("tensor",t,e,n),n.nextIteration(),[2,[p.clone()]];case 8:return h=f("size",t,e,n),m=f("dtype",t,e,n),v=f("elementShape",t,e,n),g=f("dynamicSize",t,e,n),y=f("clearAfterRead",t,e,n),x=f("identicalElementShapes",t,e,n),b=f("name",t,e,n),w=new Y(b,m,h,v,x,g,y),n.addTensorArray(w),[2,[Object(i.scalar)(w.id),Object(i.scalar)(1)]];case 9:return C=f("tensorArrayId",t,e,n),E=f("index",t,e,n),S=f("tensor",t,e,n),n.getTensorArray(C).write(E,S),[2,[Object(i.scalar)(1)]];case 10:return N=f("tensorArrayId",t,e,n),I=f("index",t,e,n),[2,[n.getTensorArray(N).read(I)]];case 11:return R=f("tensorArrayId",t,e,n),T=f("indices",t,e,n),k=f("dtype",t,e,n),[2,[n.getTensorArray(R).gather(T,k)]];case 12:return A=f("tensorArrayId",t,e,n),O=f("indices",t,e,n),D=f("tensor",t,e,n),n.getTensorArray(A).scatter(O,D),[2,[Object(i.scalar)(1)]];case 13:return _=f("tensorArrayId",t,e,n),F=n.getTensorArray(_),M=f("dtype",t,e,n),[2,[F.concat(M)]];case 14:return B=f("tensorArrayId",t,e,n),P=f("tensor",t,e,n),L=f("lengths",t,e,n),n.getTensorArray(B).split(L,P),[2,[Object(i.scalar)(1)]];case 15:return V=f("tensorArrayId",t,e,n),W=n.getTensorArray(V),[2,[Object(i.scalar)(W.size(),"int32")]];case 16:return z=f("tensorArrayId",t,e,n),n.getTensorArray(z).clearAndClose(),[2,[Object(i.scalar)(0)]];case 17:throw TypeError("Node type "+t.op+" is not implemented")}}))}))}(t,e,n);case"convolution":return function(t,e,n){switch(t.op){case"Conv1D":var r=f("stride",t,e,n),a=f("pad",t,e,n),o=f("dataFormat",t,e,n).toUpperCase(),s=f("dilation",t,e,n);return[Object(i.conv1d)(f("x",t,e,n),f("filter",t,e,n),r,a,o,s)];case"Conv2D":r=f("strides",t,e,n),a=f("pad",t,e,n),o=f("dataFormat",t,e,n).toUpperCase();var u=f("dilations",t,e,n);return[Object(i.conv2d)(f("x",t,e,n),f("filter",t,e,n),[r[1],r[2]],a,o,[u[1],u[2]])];case"_FusedConv2D":case"FusedDepthwiseConv2dNative":var c=f("fusedOps",t,e,n),l=c[0],p=c[1],d="biasadd"===l,h="prelu"===p,m="fusedbatchnorm"===l,v=f("numArgs",t,e,n);if(d){if(h&&2!==v)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!h&&1!==v)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(m)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");r=f("strides",t,e,n),a=f("pad",t,e,n),o=f("dataFormat",t,e,n).toUpperCase(),u=f("dilations",t,e,n);var g=f("args",t,e,n),y=g[0],x=g[1];return[("_FusedConv2D"===t.op?i.fused.conv2d:i.fused.depthwiseConv2d)({x:f("x",t,e,n),filter:f("filter",t,e,n),strides:[r[1],r[2]],pad:a,dataFormat:o,dilations:[u[1],u[2]],bias:y,activation:p,preluActivationWeights:x})];case"Conv2DBackpropInput":case"Conv2dTranspose":var b=f("outputShape",t,e,n);return r=f("strides",t,e,n),a=f("pad",t,e,n),[Object(i.conv2dTranspose)(f("x",t,e,n),f("filter",t,e,n),b,[r[1],r[2]],a)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return r=f("strides",t,e,n),a=f("pad",t,e,n),u=f("dilations",t,e,n),o=f("dataFormat",t,e,n).toUpperCase(),[Object(i.depthwiseConv2d)(f("input",t,e,n),f("filter",t,e,n),[r[1],r[2]],a,o,[u[1],u[2]])];case"Conv3D":return r=f("strides",t,e,n),a=f("pad",t,e,n),o=f("dataFormat",t,e,n).toUpperCase(),u=f("dilations",t,e,n),[Object(i.conv3d)(f("x",t,e,n),f("filter",t,e,n),[r[1],r[2],r[3]],a,o,[u[1],u[2],u[3]])];case"AvgPool":r=f("strides",t,e,n),a=f("pad",t,e,n);var w=f("kernelSize",t,e,n);return[Object(i.avgPool)(f("x",t,e,n),[w[1],w[2]],[r[1],r[2]],a)];case"MaxPool":return r=f("strides",t,e,n),a=f("pad",t,e,n),w=f("kernelSize",t,e,n),[Object(i.maxPool)(f("x",t,e,n),[w[1],w[2]],[r[1],r[2]],a)];case"AvgPool3D":return r=f("strides",t,e,n),a=f("pad",t,e,n),w=f("kernelSize",t,e,n),[Object(i.avgPool3d)(f("x",t,e,n),[w[1],w[2],w[3]],[r[1],r[2],r[3]],a)];case"MaxPool3D":return r=f("strides",t,e,n),a=f("pad",t,e,n),w=f("kernelSize",t,e,n),[Object(i.maxPool3d)(f("x",t,e,n),[w[1],w[2],w[3]],[r[1],r[2],r[3]],a)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"creation":return function(t,e,n){switch(t.op){case"Fill":var r=f("shape",t,e,n),a=f("dtype",t,e,n),o=f("value",t,e,n);return[Object(i.fill)(r,o,a)];case"LinSpace":var s=f("start",t,e,n),u=f("stop",t,e,n),c=f("num",t,e,n);return[Object(i.linspace)(s,u,c)];case"Multinomial":var l=f("logits",t,e,n),p=f("numSamples",t,e,n),d=f("seed",t,e,n);return[Object(i.multinomial)(l,p,d)];case"OneHot":var h=f("indices",t,e,n),m=f("depth",t,e,n),v=f("onValue",t,e,n),g=f("offValue",t,e,n);return[Object(i.oneHot)(h,m,v,g)];case"Ones":return[Object(i.ones)(f("shape",t,e,n),f("dtype",t,e,n))];case"OnesLike":return[Object(i.onesLike)(f("x",t,e,n))];case"RandomUniform":return[Object(i.randomUniform)(f("shape",t,e,n),f("minval",t,e,n),f("maxval",t,e,n),f("dtype",t,e,n))];case"Range":s=f("start",t,e,n);var y=f("stop",t,e,n),x=f("step",t,e,n);return[Object(i.range)(s,y,x,f("dtype",t,e,n))];case"TruncatedNormal":r=f("shape",t,e,n);var b=f("mean",t,e,n),w=f("stdDev",t,e,n);return d=f("seed",t,e,n),[Object(i.truncatedNormal)(r,b,w,f("dtype",t,e,n),d)];case"Zeros":return[Object(i.zeros)(f("shape",t,e,n),f("dtype",t,e,n))];case"ZerosLike":return[Object(i.zerosLike)(f("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"dynamic":return function(t,e,n){return u(this,void 0,void 0,(function(){var r,a,o,s,u;return c(this,(function(c){switch(c.label){case 0:switch(t.op){case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,3];case"ListDiff":return[3,5]}return[3,6];case 1:return r=f("boxes",t,e,n),a=f("scores",t,e,n),o=f("maxOutputSize",t,e,n),s=f("iouThreshold",t,e,n),u=f("scoreThreshold",t,e,n),[4,i.image.nonMaxSuppressionAsync(r,a,o,s,u)];case 2:return[2,[c.sent()]];case 3:return[4,Object(i.whereAsync)(f("condition",t,e,n).asType("bool"))];case 4:return[2,[c.sent()]];case 5:return[2,Object(i.setdiff1dAsync)(f("x",t,e,n),f("y",t,e,n))];case 6:throw TypeError("Node type "+t.op+" is not implemented")}}))}))}(t,e,n);case"evaluation":return function(t,e,n){switch(t.op){case"TopKV2":var r=f("x",t,e,n),a=f("k",t,e,n),o=f("sorted",t,e,n),s=Object(i.topk)(r,a,o);return[s.values,s.indices];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"image":return function(t,e,n){switch(t.op){case"ResizeBilinear":var r=f("images",t,e,n),a=f("size",t,e,n),o=f("alignCorners",t,e,n);return[i.image.resizeBilinear(r,[a[0],a[1]],o)];case"ResizeNearestNeighbor":return r=f("images",t,e,n),a=f("size",t,e,n),o=f("alignCorners",t,e,n),[i.image.resizeNearestNeighbor(r,[a[0],a[1]],o)];case"CropAndResize":var s=f("image",t,e,n),u=f("boxes",t,e,n),c=f("boxInd",t,e,n),l=f("cropSize",t,e,n),p=f("method",t,e,n),d=f("extrapolationValue",t,e,n);return[i.image.cropAndResize(s,u,c,l,p,d)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"graph":return function(t,e,n){switch(t.op){case"Const":return e[t.name];case"PlaceholderWithDefault":var r=f("default",t,e,n);return[d(t.name,e,n)||r];case"Placeholder":return[d(t.name,e,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[f("x",t,e,n).clone()];case"IdentityN":return f("x",t,e,n).map((function(t){return t.clone()}));case"Snapshot":return[f("x",t,e,n).clone()];case"Shape":return[Object(i.tensor1d)(f("x",t,e,n).shape,"int32")];case"ShapeN":return f("x",t,e,n).map((function(t){return Object(i.tensor1d)(t.shape)}));case"Size":return[Object(i.scalar)(f("x",t,e,n).size,"int32")];case"Rank":return[Object(i.scalar)(f("x",t,e,n).rank,"int32")];case"NoOp":return[Object(i.scalar)(1)];case"Print":var a=f("x",t,e,n),o=f("data",t,e,n),s=f("message",t,e,n),u=f("summarize",t,e,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(s);for(var c=0;c<o.length;c++)console.log(Array.prototype.slice.call(o[c].dataSync()).slice(0,u));return[a];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"logical":return function(t,e,n){switch(t.op){case"Equal":return[Object(i.equal)(f("a",t,e,n),f("b",t,e,n))];case"NotEqual":return[Object(i.notEqual)(f("a",t,e,n),f("b",t,e,n))];case"Greater":return[Object(i.greater)(f("a",t,e,n),f("b",t,e,n))];case"GreaterEqual":return[Object(i.greaterEqual)(f("a",t,e,n),f("b",t,e,n))];case"Less":return[Object(i.less)(f("a",t,e,n),f("b",t,e,n))];case"LessEqual":return[Object(i.lessEqual)(f("a",t,e,n),f("b",t,e,n))];case"LogicalAnd":return[Object(i.logicalAnd)(f("a",t,e,n),f("b",t,e,n))];case"LogicalNot":return[Object(i.logicalNot)(f("a",t,e,n))];case"LogicalOr":return[Object(i.logicalOr)(f("a",t,e,n),f("b",t,e,n))];case"Select":return[Object(i.where)(f("condition",t,e,n),f("a",t,e,n),f("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"matrices":return function(t,e,n){switch(t.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Object(i.matMul)(f("a",t,e,n),f("b",t,e,n),f("transposeA",t,e,n),f("transposeB",t,e,n))];case"Transpose":return[Object(i.transpose)(f("x",t,e,n),f("perm",t,e,n))];case"_FusedMatMul":var r=f("fusedOps",t,e,n),a=r[0],o=r[1],s="biasadd"===a,u="prelu"===o,c=f("numArgs",t,e,n);if(s){if(u&&2!==c)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!u&&1!==c)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}var l=f("args",t,e,n),p=l[0],d=l[1];return[i.fused.matMul({a:f("a",t,e,n),b:f("b",t,e,n),transposeA:f("transposeA",t,e,n),transposeB:f("transposeB",t,e,n),bias:p,activation:o,preluActivationWeights:d})];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"normalization":return function(t,e,n){switch(t.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[Object(i.batchNorm)(f("x",t,e,n),f("mean",t,e,n),f("variance",t,e,n),f("offset",t,e,n),f("scale",t,e,n),f("epsilon",t,e,n))];case"LRN":return[Object(i.localResponseNormalization)(f("x",t,e,n),f("radius",t,e,n),f("bias",t,e,n),f("alpha",t,e,n),f("beta",t,e,n))];case"Softmax":return[Object(i.softmax)(f("x",t,e,n))];case"LogSoftmax":return[Object(i.logSoftmax)(f("x",t,e,n))];case"SparseToDense":return[Object(i.sparseToDense)(f("sparseIndices",t,e,n),f("outputShape",t,e,n),f("sparseValues",t,e,n),f("defaultValue",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"reduction":return function(t,e,n){switch(t.op){case"Max":var r=f("axis",t,e,n),a=f("keepDims",t,e,n);return[Object(i.max)(f("x",t,e,n),r,a)];case"Mean":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.mean)(f("x",t,e,n),r,a)];case"Min":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.min)(f("x",t,e,n),r,a)];case"Sum":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.sum)(f("x",t,e,n),r,a)];case"All":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.all)(f("x",t,e,n),r,a)];case"Any":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.any)(f("x",t,e,n),r,a)];case"ArgMax":return r=f("axis",t,e,n),[Object(i.argMax)(f("x",t,e,n),r)];case"ArgMin":return r=f("axis",t,e,n),[Object(i.argMin)(f("x",t,e,n),r)];case"Prod":return r=f("axis",t,e,n),a=f("keepDims",t,e,n),[Object(i.prod)(f("x",t,e,n),r,a)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"slice_join":return function(t,e,n){switch(t.op){case"ConcatV2":case"Concat":var r=f("n",t,e,n),a=f("axis",t,e,n),o=f("tensors",t,e,n);return o=o.slice(0,r),[Object(i.concat)(o,a)];case"GatherV2":case"Gather":a=f("axis",t,e,n);var s=f("x",t,e,n),u=f("indices",t,e,n);return[Object(i.gather)(s,u.asType("int32"),a)];case"ReverseV2":case"Reverse":return a=f("axis",t,e,n),s=f("x",t,e,n),[Object(i.reverse)(s,a)];case"Slice":var c=f("begin",t,e,n),l=f("size",t,e,n);return[Object(i.slice)(f("x",t,e,n),c,l)];case"StridedSlice":c=f("begin",t,e,n);var p=f("end",t,e,n),d=f("strides",t,e,n),h=f("beginMask",t,e,n),m=f("endMask",t,e,n),v=f("ellipsisMask",t,e,n),g=f("newAxisMask",t,e,n),y=f("shrinkAxisMask",t,e,n),x=f("x",t,e,n);if(1===c.length&&x.shape.length>1)for(var b=1;b<x.shape.length;b++)c.push(0),p.push(x.shape[b]),d.push(d[0]);return[Object(i.stridedSlice)(x,c,p,d,h,m,v,g,y)];case"Pack":return Object(i.tidy)((function(){var r=f("axis",t,e,n),a=f("tensors",t,e,n),o=a[0].shape,s=a[0].squeeze().shape,u=a.map((function(t){var e=i.util.arraysEqual(t.shape,o);if(!e&&!i.util.arraysEqual(t.squeeze().shape,s))throw new Error("the input tensors shape does not match");return e?t:t.reshape(o)}));return[Object(i.stack)(u,r)]}));case"Unpack":return Object(i.tidy)((function(){var r=f("axis",t,e,n),a=f("tensor",t,e,n);return Object(i.unstack)(a,r)}));case"Tile":var w=f("reps",t,e,n);return[Object(i.tile)(f("x",t,e,n),w)];case"Split":case"SplitV":a=f("axis",t,e,n);var C=f("numOrSizeSplits",t,e,n);return Object(i.split)(f("x",t,e,n),C,a);case"ScatterNd":u=f("indices",t,e,n);var E=f("values",t,e,n),S=f("shape",t,e,n);return[Object(i.scatterND)(u,E,S)];case"GatherNd":var N=f("x",t,e,n);return u=f("indices",t,e,n),[Object(i.gatherND)(N,u)];case"SparseToDense":u=f("sparseIndices",t,e,n),S=f("outputShape",t,e,n);var I=f("sparseValues",t,e,n),R=f("defaultValue",t,e,n);return[Object(i.sparseToDense)(u,I,S,I.dtype===R.dtype?R:R.asType(I.dtype))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"spectral":return function(t,e,n){switch(t.op){case"FFT":return[Object(i.fft)(f("x",t,e,n))];case"IFFT":return[Object(i.ifft)(f("x",t,e,n))];case"RFFT":return[Object(i.rfft)(f("x",t,e,n))];case"IRFFT":return[Object(i.irfft)(f("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"transformation":return function(t,e,n){switch(t.op){case"Cast":return[Object(i.cast)(f("x",t,e,n),f("dtype",t,e,n))];case"ExpandDims":var r=f("axis",t,e,n);return[Object(i.expandDims)(f("x",t,e,n),r)];case"Squeeze":return r=f("axis",t,e,n),[Object(i.squeeze)(f("x",t,e,n),r)];case"Reshape":return[Object(i.reshape)(f("x",t,e,n),f("shape",t,e,n))];case"PadV2":case"Pad":return[Object(i.pad)(f("x",t,e,n),g(f("padding",t,e,n),2),f("constantValue",t,e,n))];case"SpaceToBatchND":var a=f("blockShape",t,e,n),o=g(f("paddings",t,e,n),2);return[Object(i.spaceToBatchND)(f("x",t,e,n),a,o)];case"BatchToSpaceND":a=f("blockShape",t,e,n);var s=g(f("crops",t,e,n),2);return[Object(i.batchToSpaceND)(f("x",t,e,n),a,s)];case"DepthToSpace":var u=f("blockSize",t,e,n),c=f("dataFormat",t,e,n).toUpperCase();return[Object(i.depthToSpace)(f("x",t,e,n),u,c)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);case"custom":var r=p(t.op);if(r&&r.customExecutor)return r.customExecutor(new X(t,e,n));throw TypeError("Custom op "+t.op+" is not registered.");default:throw TypeError("Unknown op '"+t.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()")}}(t,e,n);return r instanceof Promise?r.then((function(t){return[].concat(t)})):[].concat(r)}var Q=function(){function t(t,e){this.weightMap=t,this.tensorArrayMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return t.prototype.newFrame=function(t,e){return{id:t,frameName:e,iterationId:0}},Object.defineProperty(t.prototype,"currentContext",{get:function(){return this.contexts},set:function(t){this.contexts!==t&&(this.contexts=t,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),t.prototype.generateCurrentContextIds=function(){for(var t=[],e=0;e<this.contexts.length-1;e++){var n=this.contexts.slice(0,this.contexts.length-e);t.push(this.contextIdforContexts(n))}t.push(""),this._currentContextIds=t},t.prototype.contextIdforContexts=function(t){return t?t.map((function(t){return 0===t.id&&0===t.iterationId?"":t.frameName+"-"+t.iterationId})).join("/"):""},t.prototype.enterFrame=function(t){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,t)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},t.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}();function J(t,e,n){for(var r=new Set,a=[],o=null,i=null,s=new Set,u=Object.keys(t).map((function(t){return v(t)[0]})),c=e.slice();c.length>0;){var l=c.pop();(et(l)||nt(l))&&null==o&&(i=(o=l).children.map((function(t){return t.name})).filter((function(t){return r.has(t)}))),r.add(l.name),null==n[l.name]&&-1===u.indexOf(l.name)&&(0!==l.inputs.length?l.inputs.forEach((function(t){s.has(t.name)||(s.add(t.name),c.push(t))})):a.push(l.name))}return{inputs:t,outputs:e,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}var Z=["Switch","Merge","Enter","Exit","NextIteration"],tt=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function et(t){return Z.indexOf(t.op)>=0}function nt(t){return tt.indexOf(t.op)>=0}var rt=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._outputs=t.outputs,this._inputs=t.inputs,this._signature=t.signature}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map((function(e){return t[e].map((function(t){return t.id}))}));this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this._inputs.map((function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map((function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this._inputs.map((function(t){return t.signatureKey||t.name}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this._outputs.map((function(t){return t.signatureKey||t.name}))},enumerable:!0,configurable:!0}),t.prototype.getCompilationKey=function(t,e){var n=t.map((function(t){return t.name})).sort(),r=e.map((function(t){return t.name})).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},t.prototype.compile=function(t,e){var n=J(t,e,this.weightMap),r=n.missingInputs,a=n.dynamicNode,o=n.syncInputs;if(null!=a)throw new Error("This execution contains the node '"+a.name+"', which has the dynamic op '"+a.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+o+"]");if(r.length>0){var i=e.map((function(t){return t.name})),s=Object.keys(t);throw new Error("Cannot compute the outputs ["+i+"] from the provided inputs ["+s+"]. Missing the following inputs: ["+r+"]")}return function(t,e,n){var r=n.usedNodes,a=n.inputs,o=[];Object.keys(a).map((function(t){return v(t)[0]})).map((function(e){return t.nodes[e]})).forEach((function(t){r.has(t.name)&&o.push(t)})),t.weights.forEach((function(t){r.has(t.name)&&o.push(t)}));for(var i=new Set,s=[];o.length>0;){var u=o.pop();i.add(u.name),e[u.name]||s.push(u),u.children.forEach((function(t){!i.has(t.name)&&r.has(t.name)&&t.inputs.every((function(t){return i.has(t.name)}))&&o.push(t)}))}return s}(this.graph,this.weightMap,n)},t.prototype.execute=function(t,e){var n=this;t=this.mapInputs(t);var r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e);var a=r.map((function(t){return n.graph.nodes[v(t)[0]]})),o=e.map((function(t){return n.graph.nodes[v(t)[0]]})),u=this.getCompilationKey(a,o),c=this.compiledMap.get(u);null==c&&(c=this.compile(t,o),this.compiledMap.set(u,c));var l={};return Object(i.tidy)((function(){var r=new Q(n._weightMap,l),a=s({},n.weightMap);Object.keys(t).forEach((function(e){var n=v(e),r=n[0],o=[];o[n[1]]=t[e],a[r]=o}));for(var o=n.getFrozenTensorIds(a),i={},u=0;u<c.length;u++){var p=c[u];if(!a[p.name]){var f=$(p,a,r);if(f instanceof Promise)throw new Error("The execution of the op '"+p.op+"' returned a promise. Please use model.executeAsync() instead.");a[p.name]=f,n.checkTensorForDisposal(p.name,p,a,r,o,e,i)}}return e.map((function(t){return d(t,a,r)}))}))},t.prototype.getFrozenTensorIds=function(t){var e=[].concat.apply([],Object.keys(t).map((function(e){return t[e]})).map((function(t){return t.map((function(t){return t.id}))})));return new Set(e)},t.prototype.checkTensorForDisposal=function(t,e,n,r,a,o,i){"control"!==e.category&&-1===o.indexOf(t)&&(n[t].forEach((function(t){null!=t&&(i[t.id]=(i[t.id]||0)+e.children.length)})),e.inputs.forEach((function(t){if("control"!==t.category){var e=function(t,e,n){return e[m(t,n.currentContextId)]}(t.name,n,r);null!=e&&e.forEach((function(t){if(t&&!a.has(t.id)){var e=i[t.id];1===e?(t.dispose(),delete i[t.id]):null!=e&&i[t.id]--}}))}})))},t.prototype.executeAsync=function(t,e){return u(this,void 0,void 0,(function(){var n,r,a,o,i,s,u=this;return c(this,(function(c){switch(c.label){case 0:return t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e),n={},r=new Q(this._weightMap,n),[4,this.executeWithControlFlow(t,r,e)];case 1:return a=c.sent(),o=e.map((function(t){return d(t,a,r)})),i=new Set(o.map((function(t){return t.id}))),s=new Set(Object.keys(t).map((function(e){return t[e].id}))),Object.keys(a).forEach((function(t){a[t].forEach((function(t){!t||t.isDisposed||i.has(t.id)||s.has(t.id)||-1!==u.weightIds.indexOf(t.id)||t.dispose()}))})),[2,o]}}))}))},t.prototype.executeWithControlFlow=function(t,e,n){return u(this,void 0,void 0,(function(){var r,a,o,i,u,l,p,f,h,m,g,y,x,b,w,C,E=this;return c(this,(function(c){switch(c.label){case 0:r=Object.keys(t),a=r.map((function(t){return E.graph.nodes[v(t)[0]]})),o=n.map((function(t){return E.graph.nodes[v(t)[0]]})),i=J(t,o,this.weightMap),u=i.usedNodes,l=i.missingInputs,p=i.dynamicNode,f=i.syncInputs,h=a.concat(this.graph.weights).map((function(t){return{node:t,contexts:e.currentContext}})),m=s({},this.weightMap),Object.keys(t).forEach((function(e){var n=v(e),r=n[0],a=[];a[n[1]]=t[e],m[r]=a})),g={},y=this.getFrozenTensorIds(m),x={},c.label=1;case 1:return h.length>0?(b=this.processStack(a,h,e,m,x,y,n,g,u),[4,Promise.all(b)]):[3,3];case 2:return c.sent(),[3,1];case 3:if(null==p&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(w=o.filter((function(t){return!et(t)&&!d(t.name,m,e)})).map((function(t){return t.name}))).length>0)throw C="",null!=p&&(C="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+f+"]"),new Error("Cannot compute the outputs ["+w+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+l+"]. "+C);return[2,m]}}))}))},t.prototype.processStack=function(t,e,n,r,a,o,i,s,u){for(var c=this,l=[],p=function(){var p=e.pop();n.currentContext=p.contexts;var m="";if("Enter"===p.node.op&&f("isConstant",p.node,r,n)&&(m=h(p.node.name,n)[0]),-1===t.indexOf(p.node)){var v=$(p.node,r,n);m||(m=h(p.node.name,n)[0]);var g=n.currentContext;v instanceof Promise?l.push(v.then((function(t){return r[m]=t,n.currentContext=g,c.checkTensorForDisposal(m,p.node,r,n,o,i,s),c.processChildNodes(p.node,e,n,r,a,u),t}))):(r[m]=v,d.checkTensorForDisposal(m,p.node,r,n,o,i,s),d.processChildNodes(p.node,e,n,r,a,u))}else d.processChildNodes(p.node,e,n,r,a,u)},d=this;e.length>0;)p();return l},t.prototype.processChildNodes=function(t,e,n,r,a,o){t.children.forEach((function(t){var i=h(t.name,n)[0];!a[i]&&o.has(t.name)&&("Merge"===t.op?t.inputNames.some((function(t){return!!d(t,r,n)}))&&(a[i]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every((function(t){return!!d(t,r,n)}))&&(a[i]=!0,e.push({contexts:n.currentContext,node:t})))}))},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach((function(e){return t.weightMap[e].forEach((function(t){return t.dispose()}))}))},t.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach((function(n){var r=t[n],a=v(n)[0],o=e.graph.nodes[a];if(o.attrParams.shape&&o.attrParams.shape.value){var s=o.attrParams.shape.value,u=s.length===r.shape.length&&r.shape.every((function(t,e){return-1===s[e]||s[e]===t}));i.util.assert(u,(function(){return"The shape of dict['"+o.name+"'] provided in model.execute(dict) must be ["+s+"], but was ["+r.shape+"]"}))}o.attrParams.dtype&&o.attrParams.dtype.value&&i.util.assert(r.dtype===o.attrParams.dtype.value,(function(){return"The dtype of dict['"+o.name+"'] provided in model.execute(dict) must be "+o.attrParams.dtype.value+", but was "+r.dtype}))}))},t.prototype.mapInputs=function(t){var e={};for(var n in t)null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[n]?e[this._signature.inputs[n].name]=t[n]:e[n]=t[n];return e},t.prototype.checkInputs=function(t){var e=this,n=Object.keys(t).filter((function(t){var n=v(t)[0];return null==e.graph.nodes[n]}));if(n.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+n+"] that are not part of graph")},t.prototype.mapOutputs=function(t){var e=this;return t.map((function(t){return null!=e._signature&&null!=e._signature.outputs&&null!=e._signature.outputs[t]?e._signature.outputs[t].name:t}),{})},t.prototype.checkOutputs=function(t){var e=this;t.forEach((function(t){var n=v(t)[0];if(!e.graph.nodes[n])throw new Error("The output '"+t+"' is not found in the graph")}))},t}(),at=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=i.io.browserHTTPRequest(t,this.loadOptions);else{var e=i.io.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(i.io.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return u(this,void 0,void 0,(function(){var t,e,n,r;return c(this,(function(a){switch(a.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=a.sent(),e=t.modelTopology,n={},null!=t.userDefinedMetadata&&(n=t.userDefinedMetadata.signature),this.version=e.versions.producer+"."+e.versions.minConsumer,r=i.io.decodeWeights(t.weightData,t.weightSpecs),this.executor=new rt(F.Instance.transformGraph(e,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),[2,!0]}}))}))},t.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},t.prototype.normalizeInputs=function(t){if(!(t instanceof i.Tensor||Array.isArray(t)))return t;if((t=Array.isArray(t)?t:[t]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce((function(e,n,r){return e[n]=t[r],e}),{})},t.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},t.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var n=this.executor.execute(t,e);return n.length>1?n:n[0]},t.prototype.executeAsync=function(t,e){return u(this,void 0,void 0,(function(){var n;return c(this,(function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return[2,(n=r.sent()).length>1?n:n[0]]}}))}))},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce((function(e,n){return e[n]=[t[n]],e}),{})},t.prototype.dispose=function(){this.executor.dispose()},t}();function ot(t,e){return void 0===e&&(e={}),u(this,void 0,void 0,(function(){var n;return c(this,(function(r){switch(r.label){case 0:if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==e&&(e={}),e.fromTFHub&&null==t.load&&(t.endsWith("/")||(t+="/"),t+="model.json?tfjs-format=file"),[4,(n=new at(t,e)).load()];case 1:return r.sent(),[2,n]}}))}))}}).call(this,n(4).Buffer)},function(t,e){var n,r,a=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(t){r=i}}();var u,c=[],l=!1,p=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):p=-1,c.length&&d())}function d(){if(!l){var t=s(f);l=!0;for(var e=c.length;e;){for(u=c,c=[];++p<e;)u&&u[p].run();p=-1,e=c.length}u=null,l=!1,function(t){if(r===clearTimeout)return clearTimeout(t);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(t);try{r(t)}catch(e){try{return r.call(null,t)}catch(e){return r.call(this,t)}}}(t)}}function h(t,e){this.fun=t,this.array=e}function m(){}a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new h(t,e)),1!==c.length||l||s(d)},h.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=m,a.addListener=m,a.once=m,a.off=m,a.removeListener=m,a.removeAllListeners=m,a.emit=m,a.prependListener=m,a.prependOnceListener=m,a.listeners=function(t){return[]},a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(t,e,n){"use strict";(function(t){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
var r=n(5),a=n(6),o=n(7);function i(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(t,e){if(i()<e)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=u.prototype:(null===t&&(t=new u(e)),t.length=e),t}function u(t,e,n){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return p(this,t)}return c(this,t,e,n)}function c(t,e,n,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,n,r){if(e.byteLength,n<0||e.byteLength<n)throw new RangeError("'offset' is out of bounds");if(e.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");e=void 0===n&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,n):new Uint8Array(e,n,r);u.TYPED_ARRAY_SUPPORT?(t=e).__proto__=u.prototype:t=f(t,e);return t}(t,e,n,r):"string"==typeof e?function(t,e,n){"string"==typeof n&&""!==n||(n="utf8");if(!u.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|h(e,n),a=(t=s(t,r)).write(e,n);a!==r&&(t=t.slice(0,a));return t}(t,e,n):function(t,e){if(u.isBuffer(e)){var n=0|d(e.length);return 0===(t=s(t,n)).length||e.copy(t,0,0,n),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(r=e.length)!=r?s(t,0):f(t,e);if("Buffer"===e.type&&o(e.data))return f(t,e.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function l(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function p(t,e){if(l(e),t=s(t,e<0?0:0|d(e)),!u.TYPED_ARRAY_SUPPORT)for(var n=0;n<e;++n)t[n]=0;return t}function f(t,e){var n=e.length<0?0:0|d(e.length);t=s(t,n);for(var r=0;r<n;r+=1)t[r]=255&e[r];return t}function d(t){if(t>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function h(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return W(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(t).length;default:if(r)return W(t).length;e=(""+e).toLowerCase(),r=!0}}function m(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return k(this,e,n);case"utf8":case"utf-8":return I(this,e,n);case"ascii":return R(this,e,n);case"latin1":case"binary":return T(this,e,n);case"base64":return N(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function v(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function g(t,e,n,r,a){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(a)return-1;n=t.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof e&&(e=u.from(e,r)),u.isBuffer(e))return 0===e.length?-1:y(t,e,n,r,a);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):y(t,[e],n,r,a);throw new TypeError("val must be string, number or Buffer")}function y(t,e,n,r,a){var o,i=1,s=t.length,u=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;i=2,s/=2,u/=2,n/=2}function c(t,e){return 1===i?t[e]:t.readUInt16BE(e*i)}if(a){var l=-1;for(o=n;o<s;o++)if(c(t,o)===c(e,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===u)return l*i}else-1!==l&&(o-=o-l),l=-1}else for(n+u>s&&(n=s-u),o=n;o>=0;o--){for(var p=!0,f=0;f<u;f++)if(c(t,o+f)!==c(e,f)){p=!1;break}if(p)return o}return-1}function x(t,e,n,r){n=Number(n)||0;var a=t.length-n;r?(r=Number(r))>a&&(r=a):r=a;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var i=0;i<r;++i){var s=parseInt(e.substr(2*i,2),16);if(isNaN(s))return i;t[n+i]=s}return i}function b(t,e,n,r){return U(W(e,t.length-n),t,n,r)}function w(t,e,n,r){return U(function(t){for(var e=[],n=0;n<t.length;++n)e.push(255&t.charCodeAt(n));return e}(e),t,n,r)}function C(t,e,n,r){return w(t,e,n,r)}function E(t,e,n,r){return U(z(e),t,n,r)}function S(t,e,n,r){return U(function(t,e){for(var n,r,a,o=[],i=0;i<t.length&&!((e-=2)<0);++i)n=t.charCodeAt(i),r=n>>8,a=n%256,o.push(a),o.push(r);return o}(e,t.length-n),t,n,r)}function N(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function I(t,e,n){n=Math.min(t.length,n);for(var r=[],a=e;a<n;){var o,i,s,u,c=t[a],l=null,p=c>239?4:c>223?3:c>191?2:1;if(a+p<=n)switch(p){case 1:c<128&&(l=c);break;case 2:128==(192&(o=t[a+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=t[a+1],i=t[a+2],128==(192&o)&&128==(192&i)&&(u=(15&c)<<12|(63&o)<<6|63&i)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=t[a+1],i=t[a+2],s=t[a+3],128==(192&o)&&128==(192&i)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),a+=p}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=4096));return n}(r)}e.Buffer=u,e.SlowBuffer=function(t){+t!=t&&(t=0);return u.alloc(+t)},e.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=i(),u.poolSize=8192,u._augment=function(t){return t.__proto__=u.prototype,t},u.from=function(t,e,n){return c(null,t,e,n)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(t,e,n){return function(t,e,n,r){return l(e),e<=0?s(t,e):void 0!==n?"string"==typeof r?s(t,e).fill(n,r):s(t,e).fill(n):s(t,e)}(null,t,e,n)},u.allocUnsafe=function(t){return p(null,t)},u.allocUnsafeSlow=function(t){return p(null,t)},u.isBuffer=function(t){return!(null==t||!t._isBuffer)},u.compare=function(t,e){if(!u.isBuffer(t)||!u.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,a=0,o=Math.min(n,r);a<o;++a)if(t[a]!==e[a]){n=t[a],r=e[a];break}return n<r?-1:r<n?1:0},u.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(t,e){if(!o(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return u.alloc(0);var n;if(void 0===e)for(e=0,n=0;n<t.length;++n)e+=t[n].length;var r=u.allocUnsafe(e),a=0;for(n=0;n<t.length;++n){var i=t[n];if(!u.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,a),a+=i.length}return r},u.byteLength=h,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)v(this,e,e+1);return this},u.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)v(this,e,e+3),v(this,e+1,e+2);return this},u.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)v(this,e,e+7),v(this,e+1,e+6),v(this,e+2,e+5),v(this,e+3,e+4);return this},u.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?I(this,0,t):m.apply(this,arguments)},u.prototype.equals=function(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u.compare(this,t)},u.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),"<Buffer "+t+">"},u.prototype.compare=function(t,e,n,r,a){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),e<0||n>t.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&e>=n)return 0;if(r>=a)return-1;if(e>=n)return 1;if(this===t)return 0;for(var o=(a>>>=0)-(r>>>=0),i=(n>>>=0)-(e>>>=0),s=Math.min(o,i),c=this.slice(r,a),l=t.slice(e,n),p=0;p<s;++p)if(c[p]!==l[p]){o=c[p],i=l[p];break}return o<i?-1:i<o?1:0},u.prototype.includes=function(t,e,n){return-1!==this.indexOf(t,e,n)},u.prototype.indexOf=function(t,e,n){return g(this,t,e,n,!0)},u.prototype.lastIndexOf=function(t,e,n){return g(this,t,e,n,!1)},u.prototype.write=function(t,e,n,r){if(void 0===e)r="utf8",n=this.length,e=0;else if(void 0===n&&"string"==typeof e)r=e,n=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-e;if((void 0===n||n>a)&&(n=a),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return x(this,t,e,n);case"utf8":case"utf-8":return b(this,t,e,n);case"ascii":return w(this,t,e,n);case"latin1":case"binary":return C(this,t,e,n);case"base64":return E(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function R(t,e,n){var r="";n=Math.min(t.length,n);for(var a=e;a<n;++a)r+=String.fromCharCode(127&t[a]);return r}function T(t,e,n){var r="";n=Math.min(t.length,n);for(var a=e;a<n;++a)r+=String.fromCharCode(t[a]);return r}function k(t,e,n){var r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);for(var a="",o=e;o<n;++o)a+=V(t[o]);return a}function A(t,e,n){for(var r=t.slice(e,n),a="",o=0;o<r.length;o+=2)a+=String.fromCharCode(r[o]+256*r[o+1]);return a}function O(t,e,n){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}function D(t,e,n,r,a,o){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>a||e<o)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}function _(t,e,n,r){e<0&&(e=65535+e+1);for(var a=0,o=Math.min(t.length-n,2);a<o;++a)t[n+a]=(e&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function F(t,e,n,r){e<0&&(e=4294967295+e+1);for(var a=0,o=Math.min(t.length-n,4);a<o;++a)t[n+a]=e>>>8*(r?a:3-a)&255}function M(t,e,n,r,a,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(t,e,n,r,o){return o||M(t,0,n,4),a.write(t,e,n,r,23,4),n+4}function P(t,e,n,r,o){return o||M(t,0,n,8),a.write(t,e,n,r,52,8),n+8}u.prototype.slice=function(t,e){var n,r=this.length;if((t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t),u.TYPED_ARRAY_SUPPORT)(n=this.subarray(t,e)).__proto__=u.prototype;else{var a=e-t;n=new u(a,void 0);for(var o=0;o<a;++o)n[o]=this[o+t]}return n},u.prototype.readUIntLE=function(t,e,n){t|=0,e|=0,n||O(t,e,this.length);for(var r=this[t],a=1,o=0;++o<e&&(a*=256);)r+=this[t+o]*a;return r},u.prototype.readUIntBE=function(t,e,n){t|=0,e|=0,n||O(t,e,this.length);for(var r=this[t+--e],a=1;e>0&&(a*=256);)r+=this[t+--e]*a;return r},u.prototype.readUInt8=function(t,e){return e||O(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||O(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||O(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||O(t,e,this.length);for(var r=this[t],a=1,o=0;++o<e&&(a*=256);)r+=this[t+o]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*e)),r},u.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||O(t,e,this.length);for(var r=e,a=1,o=this[t+--r];r>0&&(a*=256);)o+=this[t+--r]*a;return o>=(a*=128)&&(o-=Math.pow(2,8*e)),o},u.prototype.readInt8=function(t,e){return e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||O(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(t,e){e||O(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(t,e){return e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||O(t,4,this.length),a.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||O(t,4,this.length),a.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||O(t,8,this.length),a.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||O(t,8,this.length),a.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||D(this,t,e,n,Math.pow(2,8*n)-1,0);var a=1,o=0;for(this[e]=255&t;++o<n&&(a*=256);)this[e+o]=t/a&255;return e+n},u.prototype.writeUIntBE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||D(this,t,e,n,Math.pow(2,8*n)-1,0);var a=n-1,o=1;for(this[e+a]=255&t;--a>=0&&(o*=256);)this[e+a]=t/o&255;return e+n},u.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):_(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):_(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):F(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):F(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e|=0,!r){var a=Math.pow(2,8*n-1);D(this,t,e,n,a-1,-a)}var o=0,i=1,s=0;for(this[e]=255&t;++o<n&&(i*=256);)t<0&&0===s&&0!==this[e+o-1]&&(s=1),this[e+o]=(t/i>>0)-s&255;return e+n},u.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e|=0,!r){var a=Math.pow(2,8*n-1);D(this,t,e,n,a-1,-a)}var o=n-1,i=1,s=0;for(this[e+o]=255&t;--o>=0&&(i*=256);)t<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(t/i>>0)-s&255;return e+n},u.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):_(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):_(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):F(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||D(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):F(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,n){return B(this,t,e,!0,n)},u.prototype.writeFloatBE=function(t,e,n){return B(this,t,e,!1,n)},u.prototype.writeDoubleLE=function(t,e,n){return P(this,t,e,!0,n)},u.prototype.writeDoubleBE=function(t,e,n){return P(this,t,e,!1,n)},u.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e<r-n&&(r=t.length-e+n);var a,o=r-n;if(this===t&&n<e&&e<r)for(a=o-1;a>=0;--a)t[a+e]=this[a+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(a=0;a<o;++a)t[a+e]=this[a+n];else Uint8Array.prototype.set.call(t,this.subarray(n,n+o),e);return o},u.prototype.fill=function(t,e,n,r){if("string"==typeof t){if("string"==typeof e?(r=e,e=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===t.length){var a=t.charCodeAt(0);a<256&&(t=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!u.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<n)throw new RangeError("Out of range index");if(n<=e)return this;var o;if(e>>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(o=e;o<n;++o)this[o]=t;else{var i=u.isBuffer(t)?t:W(new u(t,r).toString()),s=i.length;for(o=0;o<n-e;++o)this[o+e]=i[o%s]}return this};var L=/[^+\/0-9A-Za-z-_]/g;function V(t){return t<16?"0"+t.toString(16):t.toString(16)}function W(t,e){var n;e=e||1/0;for(var r=t.length,a=null,o=[],i=0;i<r;++i){if((n=t.charCodeAt(i))>55295&&n<57344){if(!a){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(i+1===r){(e-=3)>-1&&o.push(239,191,189);continue}a=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(e-=3)>-1&&o.push(239,191,189);if(a=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(t){return r.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(L,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function U(t,e,n,r){for(var a=0;a<r&&!(a+n>=e.length||a>=t.length);++a)e[a+n]=t[a];return a}}).call(this,n(1))},function(t,e,n){"use strict";e.byteLength=function(t){var e=c(t),n=e[0],r=e[1];return 3*(n+r)/4-r},e.toByteArray=function(t){var e,n,r=c(t),i=r[0],s=r[1],u=new o(function(t,e,n){return 3*(e+n)/4-n}(0,i,s)),l=0,p=s>0?i-4:i;for(n=0;n<p;n+=4)e=a[t.charCodeAt(n)]<<18|a[t.charCodeAt(n+1)]<<12|a[t.charCodeAt(n+2)]<<6|a[t.charCodeAt(n+3)],u[l++]=e>>16&255,u[l++]=e>>8&255,u[l++]=255&e;2===s&&(e=a[t.charCodeAt(n)]<<2|a[t.charCodeAt(n+1)]>>4,u[l++]=255&e);1===s&&(e=a[t.charCodeAt(n)]<<10|a[t.charCodeAt(n+1)]<<4|a[t.charCodeAt(n+2)]>>2,u[l++]=e>>8&255,u[l++]=255&e);return u},e.fromByteArray=function(t){for(var e,n=t.length,a=n%3,o=[],i=0,s=n-a;i<s;i+=16383)o.push(l(t,i,i+16383>s?s:i+16383));1===a?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===a&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],a=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=i.length;s<u;++s)r[s]=i[s],a[i.charCodeAt(s)]=s;function c(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");return-1===n&&(n=e),[n,n===e?0:4-n%4]}function l(t,e,n){for(var a,o,i=[],s=e;s<n;s+=3)a=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),i.push(r[(o=a)>>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return i.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,n,r,a){var o,i,s=8*a-r-1,u=(1<<s)-1,c=u>>1,l=-7,p=n?a-1:0,f=n?-1:1,d=t[e+p];for(p+=f,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+t[e+p],p+=f,l-=8);for(i=o&(1<<-l)-1,o>>=-l,l+=r;l>0;i=256*i+t[e+p],p+=f,l-=8);if(0===o)o=1-c;else{if(o===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),o-=c}return(d?-1:1)*i*Math.pow(2,o-r)},e.write=function(t,e,n,r,a,o){var i,s,u,c=8*o-a-1,l=(1<<c)-1,p=l>>1,f=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,h=r?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,i=l):(i=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-i))<1&&(i--,u*=2),(e+=i+p>=1?f/u:f*Math.pow(2,1-p))*u>=2&&(i++,u/=2),i+p>=l?(s=0,i=l):i+p>=1?(s=(e*u-1)*Math.pow(2,a),i+=p):(s=e*Math.pow(2,p-1)*Math.pow(2,a),i=0));a>=8;t[n+d]=255&s,d+=h,s/=256,a-=8);for(i=i<<a|s,c+=a;c>0;t[n+d]=255&i,d+=h,i/=256,c-=8);t[n+d-h]|=128*m}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){(function(t){var r=void 0!==t&&t||"undefined"!=typeof self&&self||window,a=Function.prototype.apply;function o(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new o(a.call(setTimeout,r,arguments),clearTimeout)},e.setInterval=function(){return new o(a.call(setInterval,r,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(r,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout((function(){t._onTimeout&&t._onTimeout()}),e))},n(9),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,n(1))},function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var r,a,o,i,s,u=1,c={},l=!1,p=t.document,f=Object.getPrototypeOf&&Object.getPrototypeOf(t);f=f&&f.setTimeout?f:t,"[object process]"==={}.toString.call(t.process)?r=function(t){e.nextTick((function(){h(t)}))}:!function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?t.MessageChannel?((o=new MessageChannel).port1.onmessage=function(t){h(t.data)},r=function(t){o.port2.postMessage(t)}):p&&"onreadystatechange"in p.createElement("script")?(a=p.documentElement,r=function(t){var e=p.createElement("script");e.onreadystatechange=function(){h(t),e.onreadystatechange=null,a.removeChild(e),e=null},a.appendChild(e)}):r=function(t){setTimeout(h,0,t)}:(i="setImmediate$"+Math.random()+"$",s=function(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(i)&&h(+e.data.slice(i.length))},t.addEventListener?t.addEventListener("message",s,!1):t.attachEvent("onmessage",s),r=function(e){t.postMessage(i+e,"*")}),f.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var a={callback:t,args:e};return c[u]=a,r(u),u++},f.clearImmediate=d}function d(t){delete c[t]}function h(t){if(l)setTimeout(h,0,t);else{var e=c[t];if(e){l=!0;try{!function(t){var e=t.callback,n=t.args;switch(n.length){case 0:e();break;case 1:e(n[0]);break;case 2:e(n[0],n[1]);break;case 3:e(n[0],n[1],n[2]);break;default:e.apply(void 0,n)}}(e)}finally{d(t),l=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,n(1),n(3))},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";n.r(e),n.d(e,"createBlurEffect",(function(){return Et}));var r=n(0),a=n(2),o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var s=function(){return(s=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t}).apply(this,arguments)};function u(t,e,n,r){return new(n||(n=Promise))((function(a,o){function i(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(i,s)}u((r=r.apply(t,e||[])).next())}))}function c(t,e){var n,r,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=e.call(t,i)}catch(t){o=[6,t],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function l(t){var e=t.shape[2],n=t.argMax(2).reshape([-1]);return Object(r.oneHot)(n,e)}function p(t,e){return Object(r.tidy)((function(){return t.greater(Object(r.scalar)(e)).toInt()}))}function f(t,e){var n=e.shape,a=n[0],o=n[1],i=n[2];return Object(r.tidy)((function(){var n=l(e),s=Object(r.range)(0,i,1,"int32").expandDims(1);return function(t,e){return t.mul(e)}(n.matMul(s).toInt().reshape([a,o]).add(Object(r.scalar)(1,"int32")),t).sub(Object(r.scalar)(1,"int32"))}))}function d(t){var e=t.shape,n=e[0],a=e[1],o=e[2];return Object(r.tidy)((function(){var e=l(t),i=Object(r.range)(0,o,1,"int32").expandDims(1);return e.matMul(i).toInt().reshape([n,a])}))}var h=function(){function t(t,e){this.model=t,this.outputStride=e;var n=this.model.inputs[0].shape;r.util.assert(-1===n[1]&&-1===n[2],(function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"}))}return t.prototype.predict=function(t){var e=this;return Object(r.tidy)((function(){var n=e.preprocessInput(t.toFloat()).expandDims(0),r=e.model.predict(n).map((function(t){return t.squeeze([0])})),a=e.nameOutputResults(r);return{heatmapScores:a.heatmap.sigmoid(),offsets:a.offsets,displacementFwd:a.displacementFwd,displacementBwd:a.displacementBwd,segmentation:a.segmentation,partHeatmaps:a.partHeatmaps,longOffsets:a.longOffsets,partOffsets:a.partOffsets}}))},t.prototype.dispose=function(){this.model.dispose()},t}(),m=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.preprocessInput=function(t){return Object(r.tidy)((function(){return Object(r.div)(t,127.5).sub(1)}))},e.prototype.nameOutputResults=function(t){return{offsets:t[0],segmentation:t[1],partHeatmaps:t[2],longOffsets:t[3],heatmap:t[4],displacementFwd:t[5],displacementBwd:t[6],partOffsets:t[7]}},e}(h),v=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],g=v.length,y=v.reduce((function(t,e,n){return t[e]=n,t}),{});[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]].map((function(t){var e=t[0],n=t[1];return[y[e],y[n]]}));function x(t,e,n){var r=t[0],a=t[1],o=e[0],i=e[1],s=n.top,u=n.bottom;return[i/(n.left+n.right+a),o/(s+u+r)]}function b(t,e,n,r){return{y:r.get(t,e,n),x:r.get(t,e,n+g)}}function w(t,e,n){var r=b(t.heatmapY,t.heatmapX,t.id,n),a=r.y,o=r.x;return{x:t.heatmapX*e+o,y:t.heatmapY*e+a}}function C(t,e,n){return t<e?e:t>n?n:t}function E(t,e){return{x:t.x+e.x,y:t.y+e.y}}function S(t,e,n){void 0===n&&(n=.3);for(var r=0,a=0,o=0;o<t.length;o++)e.keypoints[o].score>n&&(a+=1,r+=Math.pow(t[o].x-e.keypoints[o].position.x,2)+Math.pow(t[o].y-e.keypoints[o].position.y,2));return 0===a?r=1/0:r/=a,r}function N(t,e,n,r,a,o,i){for(var s=i[0],u=i[1],c=n(t),l=c.y*r+c.x,p=a[g*(2*l)+e],f=a[g*(2*l+1)+e],d=t.y+p,h=t.x+f,m=0;m<o;m++){d=Math.min(d,s-1);var v=n({x:h=Math.min(h,u-1),y:d}),y=v.y*r+v.x;d+=p=a[g*(2*y)+e],h+=f=a[g*(2*y+1)+e]}return{x:h,y:d}}function I(t,e,n,r,a,o,i,s,u,c){for(var l=a[0],p=a[1],f=o[0],d=o[1],h=s[0],m=s[1],v=[],g=function(t){return function(t,e,n,r){var a=e[0],o=e[1],i=n[0],s=n[1],u=Math.round(((a+t.y+1)*s-1)/r);return{x:Math.round(((o+t.x+1)*i-1)/r),y:u}}(t,[l,p],[f,d],u)},y=0;y<r;y++){var x=N(t,y,g,i,e,c,[h,m]);v.push(x)}for(var b=-1,w=1/0,C=0;C<n.length;C++){var E=S(v,n[C]);E<w&&(b=C,w=E)}return b}function R(t,e){var n=t[0],r=t[1];return[Math.round((r-1)/e+1),Math.round((n-1)/e+1)]}function T(t,e,n,a,o,i,s,u,c,l,p){for(var f=s[0],d=s[1],h=t.shape,m=h[0],v=h[1],y=e.shape.slice(0,2),b=y[0],w=y[1],C=e.reshape([b,w,2,g]),E=new Float32Array(p*g*3).fill(0),S=0;S<n.length;S++)for(var N=S*g*3,I=n[S],R=0;R<g;R++){var T=I.keypoints[R],k=N+3*R;E[k]=T.score,E[k+1]=T.position.y,E[k+2]=T.position.x}var A=x([a,o],[f,d],u),O=A[0],D=A[1],_=Object(r.tensor)(E,[p,g,3]),F=u.top,M=u.left,B={variableNames:["segmentation","longOffsets","poses"],outputShape:[m,v],userCode:"\n int convertToPositionInOutput(int pos, int pad, float scale, int stride) {\n return round(((float(pos + pad) + 1.0) * scale - 1.0) / float(stride));\n }\n\n float convertToPositionInOutputFloat(\n int pos, int pad, float scale, int stride) {\n return ((float(pos + pad) + 1.0) * scale - 1.0) / float(stride);\n }\n\n float dist(float x1, float y1, float x2, float y2) {\n return pow(x1 - x2, 2.0) + pow(y1 - y2, 2.0);\n }\n\n float sampleLongOffsets(float h, float w, int d, int k) {\n float fh = fract(h);\n float fw = fract(w);\n int clH = int(ceil(h));\n int clW = int(ceil(w));\n int flH = int(floor(h));\n int flW = int(floor(w));\n float o11 = getLongOffsets(flH, flW, d, k);\n float o12 = getLongOffsets(flH, clW, d, k);\n float o21 = getLongOffsets(clH, flW, d, k);\n float o22 = getLongOffsets(clH, clW, d, k);\n float o1 = mix(o11, o12, fw);\n float o2 = mix(o21, o22, fw);\n return mix(o1, o2, fh);\n }\n\n int findNearestPose(int h, int w) {\n float prob = getSegmentation(h, w);\n if (prob < 1.0) {\n return -1;\n }\n\n // Done(Tyler): convert from output space h/w to strided space.\n float stridedH = convertToPositionInOutputFloat(\n h, "+F+", "+D+", "+i+");\n float stridedW = convertToPositionInOutputFloat(\n w, "+M+", "+O+", "+i+");\n\n float minDist = 1000000.0;\n int iMin = -1;\n for (int i = 0; i < "+p+"; i++) {\n float curDistSum = 0.0;\n int numKpt = 0;\n for (int k = 0; k < "+g+"; k++) {\n float dy = sampleLongOffsets(stridedH, stridedW, 0, k);\n float dx = sampleLongOffsets(stridedH, stridedW, 1, k);\n\n float y = float(h) + dy;\n float x = float(w) + dx;\n\n for (int s = 0; s < "+c+"; s++) {\n int yRounded = round(min(y, float("+(a-1)+")));\n int xRounded = round(min(x, float("+(o-1)+")));\n\n float yStrided = convertToPositionInOutputFloat(\n yRounded, "+F+", "+D+", "+i+");\n float xStrided = convertToPositionInOutputFloat(\n xRounded, "+M+", "+O+", "+i+");\n\n float dy = sampleLongOffsets(yStrided, xStrided, 0, k);\n float dx = sampleLongOffsets(yStrided, xStrided, 1, k);\n\n y = y + dy;\n x = x + dx;\n }\n\n float poseScore = getPoses(i, k, 0);\n float poseY = getPoses(i, k, 1);\n float poseX = getPoses(i, k, 2);\n if (poseScore > "+l+") {\n numKpt = numKpt + 1;\n curDistSum = curDistSum + dist(x, y, poseX, poseY);\n }\n }\n if (numKpt > 0 && curDistSum / float(numKpt) < minDist) {\n minDist = curDistSum / float(numKpt);\n iMin = i;\n }\n }\n return iMin;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int nearestPose = findNearestPose(coords[0], coords[1]);\n setOutput(float(nearestPose));\n }\n "};return Object(r.backend)().compileAndRun(B,[t,C,_])}function k(){return"webgl"===Object(r.getBackend)()}function A(t,e,n,a,o,i,s,l,p,f,d,h){var m=s[0],v=s[1];return void 0===p&&(p=.2),void 0===f&&(f=8),void 0===d&&(d=.3),void 0===h&&(h=10),u(this,void 0,void 0,(function(){var s,u,g,y,b;return c(this,(function(c){switch(c.label){case 0:return s=n.filter((function(t){return t.score>=p})),k()?(g=Object(r.tidy)((function(){var n=T(t,e,s,a,o,i,[m,v],l,f,d,h);return s.map((function(t,e){return function(t,e){return Object(r.tidy)((function(){return t.equal(Object(r.scalar)(e)).toInt()}))}(n,e)}))})),[4,Promise.all(g.map((function(t){return t.data()})))]):[3,2];case 1:return u=c.sent(),g.forEach((function(t){return t.dispose()})),[3,5];case 2:return[4,t.data()];case 3:return y=c.sent(),[4,e.data()];case 4:b=c.sent(),u=function(t,e,n,r,a,o,i,s,u,c){var l=i[0],p=i[1];void 0===c&&(c=5);for(var f=n.map((function(t){return new Uint8Array(r*a).fill(0)})),d=s.top,h=s.left,m=x([r,a],[l,p],s),v=m[0],g=m[1],y=R([l,p],o)[0],b=0;b<r;b+=1)for(var w=0;w<a;w+=1){var C=b*a+w;if(1===t[C]){var E=I({x:w,y:b},e,n,c,[d,h],[v,g],y,[r,a],o,u);E>=0&&(f[E][C]=1)}}return f}(y,b,s,a,o,i,[m,v],l,f),c.label=5;case 5:return[2,u.map((function(t,e){return{data:t,pose:s[e],width:o,height:a}}))]}}))}))}function O(t,e,n,a,o,i,s,l,p,f,d,h,m){var v=l[0],g=l[1];return void 0===f&&(f=.2),void 0===d&&(d=8),void 0===h&&(h=.3),void 0===m&&(m=10),u(this,void 0,void 0,(function(){var u,l,y,b,w,C;return c(this,(function(c){switch(c.label){case 0:return u=a.filter((function(t){return t.score>=f})),k()?(y=Object(r.tidy)((function(){var a=T(t,e,u,o,i,s,[v,g],p,d,h,m);return u.map((function(t,e){return function(t,e,n){return Object(r.tidy)((function(){return t.equal(Object(r.scalar)(n)).toInt().mul(e.add(1)).sub(1)}))}(a,n,e)}))})),[4,Promise.all(y.map((function(t){return t.data()})))]):[3,2];case 1:return l=c.sent(),y.forEach((function(t){return t.dispose()})),[3,6];case 2:return[4,t.data()];case 3:return b=c.sent(),[4,e.data()];case 4:return w=c.sent(),[4,n.data()];case 5:C=c.sent(),l=function(t,e,n,r,a,o,i,s,u,c,l){var p=s[0],f=s[1];void 0===l&&(l=5);for(var d=r.map((function(t){return new Int32Array(a*o).fill(-1)})),h=u.top,m=u.left,v=x([a,o],[p,f],u),g=v[0],y=v[1],b=R([p,f],i)[0],w=0;w<a;w+=1)for(var C=0;C<o;C+=1){var E=w*o+C;if(1===t[E]){var S=I({x:C,y:w},e,r,l,[h,m],[g,y],b,[a,o],i,c);S>=0&&(d[S][E]=n[E])}}return d}(b,w,C,u,o,i,s,[v,g],p,d),c.label=6;case 6:return[2,l.map((function(t,e){return{pose:u[e],data:t,height:o,width:i}}))]}}))}))}function D(t){return Math.floor(t/2)}var _=function(){function t(t,e){this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=e}return t.prototype.enqueue=function(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)},t.prototype.dequeue=function(){var t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t},t.prototype.empty=function(){return-1===this.numberOfElements},t.prototype.size=function(){return this.numberOfElements+1},t.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},t.prototype.max=function(){return this.priorityQueue[0]},t.prototype.swim=function(t){for(;t>0&&this.less(D(t),t);)this.exchange(t,D(t)),t=D(t)},t.prototype.sink=function(t){for(;2*t<=this.numberOfElements;){var e=2*t;if(e<this.numberOfElements&&this.less(e,e+1)&&e++,!this.less(t,e))break;this.exchange(t,e),t=e}},t.prototype.getValueAt=function(t){return this.getElementValue(this.priorityQueue[t])},t.prototype.less=function(t,e){return this.getValueAt(t)<this.getValueAt(e)},t.prototype.exchange=function(t,e){var n=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[e],this.priorityQueue[e]=n},t}();function F(t,e,n,r,a,o){for(var i=o.shape,s=i[0],u=i[1],c=!0,l=Math.max(n-a,0),p=Math.min(n+a+1,s),f=l;f<p;++f){for(var d=Math.max(r-a,0),h=Math.min(r+a+1,u),m=d;m<h;++m)if(o.get(f,m,t)>e){c=!1;break}if(!c)break}return c}var M=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]].map((function(t){var e=t[0],n=t[1];return[y[e],y[n]]})),B=M.map((function(t){return t[1]})),P=M.map((function(t){return t[0]}));function L(t,e,n,r){return{y:C(Math.round(t.y/e),0,n-1),x:C(Math.round(t.x/e),0,r-1)}}function V(t,e,n,r,a,o,i,s){void 0===s&&(s=2);for(var u=r.shape,c=u[0],l=u[1],p=function(t,e,n){var r=n.shape[2]/2;return{y:n.get(e.y,e.x,t),x:n.get(e.y,e.x,r+t)}}(t,L(e.position,o,c,l),i),f=E(e.position,p),d=0;d<s;d++){var h=L(f,o,c,l),m=b(h.y,h.x,n,a);f=E({x:h.x*o,y:h.y*o},{x:m.x,y:m.y})}var g=L(f,o,c,l),y=r.get(g.y,g.x,n);return{position:f,part:v[n],score:y}}function W(t,e,n,r,a,o){var i=e.shape[2],s=B.length,u=new Array(i),c=t.part,l=t.score,p=w(c,r,n);u[c.id]={score:l,part:v[c.id],position:p};for(var f=s-1;f>=0;--f){var d=B[f],h=P[f];u[d]&&!u[h]&&(u[h]=V(f,u[d],h,e,n,r,o))}for(f=0;f<s;++f)d=P[f],h=B[f],u[d]&&!u[h]&&(u[h]=V(f,u[d],h,e,n,r,a));return u}function z(t,e,n,r){var a=n.x,o=n.y;return t.some((function(t){var n=t.keypoints[r].position;return function(t,e,n,r){var a=n-t,o=r-e;return a*a+o*o}(o,a,n.y,n.x)<=e}))}function U(t,e,n){return n.reduce((function(n,r,a){var o=r.position,i=r.score;return z(t,e,o,a)||(n+=i),n}),0)/n.length}function j(t,e,n,r,a,o,i,s){void 0===i&&(i=.5),void 0===s&&(s=20);for(var u=[],c=function(t,e,n){for(var r=n.shape,a=r[0],o=r[1],i=r[2],s=new _(a*o*i,(function(t){return t.score})),u=0;u<a;++u)for(var c=0;c<o;++c)for(var l=0;l<i;++l){var p=n.get(u,c,l);p<t||F(l,p,u,c,e,n)&&s.enqueue({score:p,part:{heatmapY:u,heatmapX:c,id:l}})}return s}(i,1,t),l=s*s;u.length<o&&!c.empty();){var p=c.dequeue();if(!z(u,l,w(p.part,a,e),p.part.id)){var f=W(p,t,e,a,n,r),d=U(u,l,f);u.push({keypoints:f,score:d})}}return u}var G,H=[-123.15,-115.9,-103.06],q=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.preprocessInput=function(t){return t.add(H)},e.prototype.nameOutputResults=function(t){var e=t[0],n=t[1],r=t[2],a=t[3],o=t[4],i=t[5];return{offsets:o,segmentation:t[6],partHeatmaps:i,longOffsets:a,heatmap:r,displacementFwd:n,displacementBwd:e,partOffsets:t[7]}},e}(h),K="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/",X="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/mobilenet/";function Y(t){if("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)return function(t){if(0!==t.offsetHeight&&0!==t.offsetWidth)return[t.offsetHeight,t.offsetWidth];if(null!=t.height&&null!=t.width)return[t.height,t.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(t);if("undefined"!=typeof ImageData&&t instanceof ImageData)return[t.height,t.width];if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)return function(t){return null!=t.height&&null!=t.width?[t.height,t.width]:[t.videoHeight,t.videoWidth]}(t);if(t instanceof r.Tensor)return[t.shape[0],t.shape[1]];throw new Error("error: Unknown input type: "+t+".")}function $(t,e){return function(t,e){return(t-1)%e==0}(t,e)?t:Math.floor(t/e)*e+1}var Q={low:"low",medium:"medium",high:"high",full:"full"},J=((G={})[Q.low]=.25,G[Q.medium]=.5,G[Q.high]=.75,G[Q.full]=1,G);function Z(t,e,n){var a=n[0],o=n[1],i=function(t){if("string"==typeof t){var e=J[t];return r.util.assert("number"==typeof e,(function(){return"string value of inputResolution must be one of "+Object.values(Q).join(",")+" but was "+t+"."})),e}return r.util.assert("number"==typeof t&&t<=2&&t>=.1,(function(){return"inputResolution must be a string or number between 0.1 and 2, but was "+t})),t}(t);return[$(a*i,e),$(o*i,e)]}function tt(t,e,n,a,o){var i=e[0],s=e[1],u=n[0],c=n[1],l=a[0],p=l[0],f=l[1],d=a[1],h=d[0],m=d[1];return void 0===o&&(o=!1),Object(r.tidy)((function(){var e=t.resizeBilinear([u,c],!0);return o&&(e=e.sigmoid()),function(t,e,n){var a=e[0],o=e[1],i=n[0],s=i[0],u=i[1],c=n[1],l=c[0],p=c[1];return Object(r.tidy)((function(){return r.image.cropAndResize(t.expandDims(),[[s/(a+s+u-1),l/(o+l+p-1),(s+a-1)/(a+s+u-1),(l+o-1)/(o+l+p-1)]],[0],[a,o]).squeeze([0])}))}(e,[i,s],[[p,f],[h,m]])}))}function et(t,e){var n=e[0],a=e[1],o=Y(t),i=o[0],s=o[1],u=a/n,c=[0,0,0,0],l=c[0],p=c[1],f=c[2],d=c[3];return s/i<u?(l=0,p=0,f=Math.round(.5*(u*i-s)),d=Math.round(.5*(u*i-s))):(l=Math.round(.5*(1/u*s-i)),p=Math.round(.5*(1/u*s-i)),f=0,d=0),{resized:Object(r.tidy)((function(){var e=function(t){return t instanceof r.Tensor?t:r.browser.fromPixels(t)}(t);return(e=Object(r.pad3d)(e,[[l,p],[f,d],[0,0]])).resizeBilinear([n,a])})),padding:{top:l,left:f,right:d,bottom:p}}}function nt(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){return[2,Promise.all(t.map((function(t){return t.buffer()})))]}))}))}function rt(t,e,n,r,a){var o=e[0],i=e[1],s=n[0],u=n[1],c=function(t,e,n,r,a){return void 0===r&&(r=0),void 0===a&&(a=0),1===n&&1===e&&0===r&&0===a?t:t.map((function(t){return function(t,e,n,r,a){return void 0===r&&(r=0),void 0===a&&(a=0),{score:t.score,keypoints:t.keypoints.map((function(t){var o=t.score,i=t.part,s=t.position;return{score:o,part:i,position:{x:s.x*n+a,y:s.y*e+r}}}))}}(t,e,n,r,a)}))}(t,(o+r.top+r.bottom)/s,(i+r.left+r.right)/u,-r.top,-r.left);return a?function(t,e){return e<=0?t:t.map((function(t){return function(t,e){return{score:t.score,keypoints:t.keypoints.map((function(t){var n=t.score,r=t.part,a=t.position;return{score:n,part:r,position:{x:e-1-a.x,y:a.y}}}))}}(t,e)}))}(c,i):c}var at={architecture:"MobileNetV1",outputStride:16,quantBytes:4,multiplier:.75},ot=["MobileNetV1","ResNet50"],it={MobileNetV1:[8,16,32],ResNet50:[32,16]},st={MobileNetV1:[.5,.75,1],ResNet50:[1]},ut=[1,2,4];var ct={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20},lt={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20,minKeypointScore:.3,refineSteps:10};function pt(t){var e=t.segmentationThreshold,n=t.maxDetections,r=t.scoreThreshold,a=t.nmsRadius;if(e<0||e>1)throw new Error("segmentationThreshold "+e+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".")}function ft(t){var e=t.segmentationThreshold,n=t.maxDetections,r=t.scoreThreshold,a=t.nmsRadius,o=t.minKeypointScore,i=t.refineSteps;if(e<0||e>1)throw new Error("segmentationThreshold "+e+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".");if(o<0||o>1)throw new Error("Invalid minKeypointScore "+o+".Should be in range [0.0, 1.0]");if(i<=0||i>20)throw new Error("Invalid refineSteps "+i+".Should be in range [1, 20]")}var dt=function(){function t(t){this.baseModel=t}return t.prototype.predictForPersonSegmentation=function(t){var e=this.baseModel.predict(t);return{segmentLogits:e.segmentation,heatmapScores:e.heatmapScores,offsets:e.offsets,displacementFwd:e.displacementFwd,displacementBwd:e.displacementBwd}},t.prototype.predictForPersonSegmentationAndPart=function(t){var e=this.baseModel.predict(t);return{segmentLogits:e.segmentation,partHeatmapLogits:e.partHeatmaps,heatmapScores:e.heatmapScores,offsets:e.offsets,displacementFwd:e.displacementFwd,displacementBwd:e.displacementBwd}},t.prototype.predictForMultiPersonInstanceSegmentationAndPart=function(t){var e=this.baseModel.predict(t);return{segmentLogits:e.segmentation,longOffsets:e.longOffsets,heatmapScores:e.heatmapScores,offsets:e.offsets,displacementFwd:e.displacementFwd,displacementBwd:e.displacementBwd,partHeatmaps:e.partHeatmaps}},t.prototype.segmentPersonActivation=function(t,e,n){var a=this;void 0===n&&(n=.5);var o=Y(t),i=o[0],s=o[1],u=Z(e,this.baseModel.outputStride,[i,s]),c=et(t,u),l=c.resized,f=c.padding,d=Object(r.tidy)((function(){var t=a.predictForPersonSegmentation(l),e=t.segmentLogits,r=t.heatmapScores,o=t.offsets,u=t.displacementFwd,c=t.displacementBwd,d=l.shape,h=d[0],m=d[1];return{segmentation:p(tt(e,[i,s],[h,m],[[f.top,f.bottom],[f.left,f.right]],!0).squeeze(),n),heatmapScores:r,offsets:o,displacementFwd:u,displacementBwd:c}})),h=d.segmentation,m=d.heatmapScores,v=d.offsets,g=d.displacementFwd,y=d.displacementBwd;return l.dispose(),{segmentation:h,heatmapScores:m,offsets:v,displacementFwd:g,displacementBwd:y,padding:f,internalResolutionHeightAndWidth:u}},t.prototype.segmentPerson=function(t,e){return void 0===e&&(e=ct),u(this,void 0,void 0,(function(){var n,r,a,o,i,u,l,p,f,d,h,m,v,g,y,x,b,w;return c(this,(function(c){switch(c.label){case 0:return pt(e=s({},ct,e)),n=this.segmentPersonActivation(t,e.internalResolution,e.segmentationThreshold),r=n.segmentation,a=n.heatmapScores,o=n.offsets,i=n.displacementFwd,u=n.displacementBwd,l=n.padding,p=n.internalResolutionHeightAndWidth,f=r.shape,d=f[0],h=f[1],[4,r.data()];case 1:return m=c.sent(),r.dispose(),[4,nt([a,o,i,u])];case 2:return v=c.sent(),g=v[0],y=v[1],x=v[2],b=v[3],w=rt(w=j(g,y,x,b,this.baseModel.outputStride,e.maxDetections,e.scoreThreshold,e.nmsRadius),[d,h],p,l,!1),a.dispose(),o.dispose(),i.dispose(),u.dispose(),[2,{height:d,width:h,data:m,allPoses:w}]}}))}))},t.prototype.segmentMultiPerson=function(t,e){return void 0===e&&(e=lt),u(this,void 0,void 0,(function(){var n,a,o,i,u,l,f,d,h,m,v,g,y,x,b,w,C,E,S,N,I,R=this;return c(this,(function(c){switch(c.label){case 0:return ft(e=s({},lt,e)),n=Y(t),a=n[0],o=n[1],i=Z(e.internalResolution,this.baseModel.outputStride,[a,o]),u=et(t,i),l=u.resized,f=u.padding,d=Object(r.tidy)((function(){var t,n=R.predictForMultiPersonInstanceSegmentationAndPart(l),r=n.segmentLogits,s=n.longOffsets,u=n.heatmapScores,c=n.offsets,d=n.displacementFwd,h=n.displacementBwd;return t=s,{segmentation:p(tt(r,[a,o],i,[[f.top,f.bottom],[f.left,f.right]],!0).squeeze(),e.segmentationThreshold),longOffsets:t,heatmapScoresRaw:u,offsetsRaw:c,displacementFwdRaw:d,displacementBwdRaw:h}})),h=d.segmentation,m=d.longOffsets,v=d.heatmapScoresRaw,g=d.offsetsRaw,y=d.displacementFwdRaw,x=d.displacementBwdRaw,[4,nt([v,g,y,x])];case 1:return b=c.sent(),w=b[0],C=b[1],E=b[2],S=b[3],N=rt(N=j(w,C,E,S,this.baseModel.outputStride,e.maxDetections,e.scoreThreshold,e.nmsRadius),[a,o],i,f,!1),[4,A(h,m,N,a,o,this.baseModel.outputStride,i,f,e.scoreThreshold,e.refineSteps,e.minKeypointScore,e.maxDetections)];case 2:return I=c.sent(),l.dispose(),h.dispose(),m.dispose(),v.dispose(),g.dispose(),y.dispose(),x.dispose(),[2,I]}}))}))},t.prototype.segmentPersonPartsActivation=function(t,e,n){var a=this;void 0===n&&(n=.5);var o=Y(t),i=o[0],s=o[1],u=Z(e,this.baseModel.outputStride,[i,s]),c=et(t,u),l=c.resized,d=c.padding,h=Object(r.tidy)((function(){var t=a.predictForPersonSegmentationAndPart(l),e=t.segmentLogits,r=t.partHeatmapLogits,o=t.heatmapScores,u=t.offsets,c=t.displacementFwd,h=t.displacementBwd,m=l.shape,v=m[0],g=m[1],y=tt(e,[i,s],[v,g],[[d.top,d.bottom],[d.left,d.right]],!0),x=tt(r,[i,s],[v,g],[[d.top,d.bottom],[d.left,d.right]],!0);return{partSegmentation:f(p(y.squeeze(),n),x),heatmapScores:o,offsets:u,displacementFwd:c,displacementBwd:h}})),m=h.partSegmentation,v=h.heatmapScores,g=h.offsets,y=h.displacementFwd,x=h.displacementBwd;return l.dispose(),{partSegmentation:m,heatmapScores:v,offsets:g,displacementFwd:y,displacementBwd:x,padding:d,internalResolutionHeightAndWidth:u}},t.prototype.segmentPersonParts=function(t,e){return void 0===e&&(e=ct),u(this,void 0,void 0,(function(){var n,r,a,o,i,u,l,p,f,d,h,m,v,g,y,x,b,w;return c(this,(function(c){switch(c.label){case 0:return pt(e=s({},ct,e)),n=this.segmentPersonPartsActivation(t,e.internalResolution,e.segmentationThreshold),r=n.partSegmentation,a=n.heatmapScores,o=n.offsets,i=n.displacementFwd,u=n.displacementBwd,l=n.padding,p=n.internalResolutionHeightAndWidth,f=r.shape,d=f[0],h=f[1],[4,r.data()];case 1:return m=c.sent(),r.dispose(),[4,nt([a,o,i,u])];case 2:return v=c.sent(),g=v[0],y=v[1],x=v[2],b=v[3],w=rt(w=j(g,y,x,b,this.baseModel.outputStride,e.maxDetections,e.scoreThreshold,e.nmsRadius),[d,h],p,l,!1),a.dispose(),o.dispose(),i.dispose(),u.dispose(),[2,{height:d,width:h,data:m,allPoses:w}]}}))}))},t.prototype.segmentMultiPersonParts=function(t,e){return void 0===e&&(e=lt),u(this,void 0,void 0,(function(){var n,a,o,i,u,l,f,h,m,v,g,y,x,b,w,C,E,S,N,I,R,T,k=this;return c(this,(function(c){switch(c.label){case 0:return ft(e=s({},lt,e)),n=Y(t),a=n[0],o=n[1],i=Z(e.internalResolution,this.baseModel.outputStride,[a,o]),u=et(t,i),l=u.resized,f=u.padding,h=Object(r.tidy)((function(){var t=k.predictForMultiPersonInstanceSegmentationAndPart(l),n=t.segmentLogits,r=t.longOffsets,s=t.heatmapScores,u=t.offsets,c=t.displacementFwd,h=t.displacementBwd,m=t.partHeatmaps,v=tt(n,[a,o],i,[[f.top,f.bottom],[f.left,f.right]],!0),g=tt(m,[a,o],i,[[f.top,f.bottom],[f.left,f.right]],!0),y=r;return{segmentation:p(v.squeeze(),e.segmentationThreshold),longOffsets:y,heatmapScoresRaw:s,offsetsRaw:u,displacementFwdRaw:c,displacementBwdRaw:h,partSegmentation:d(g)}})),m=h.segmentation,v=h.longOffsets,g=h.heatmapScoresRaw,y=h.offsetsRaw,x=h.displacementFwdRaw,b=h.displacementBwdRaw,w=h.partSegmentation,[4,nt([g,y,x,b])];case 1:return C=c.sent(),E=C[0],S=C[1],N=C[2],I=C[3],R=rt(R=j(E,S,N,I,this.baseModel.outputStride,e.maxDetections,e.scoreThreshold,e.nmsRadius),[a,o],i,f,!1),[4,O(m,v,w,R,a,o,this.baseModel.outputStride,i,f,e.scoreThreshold,e.refineSteps,e.minKeypointScore,e.maxDetections)];case 2:return T=c.sent(),l.dispose(),m.dispose(),v.dispose(),g.dispose(),y.dispose(),x.dispose(),b.dispose(),w.dispose(),[2,T]}}))}))},t.prototype.dispose=function(){this.baseModel.dispose()},t}();function ht(t){return u(this,void 0,void 0,(function(){var e,n,o,i,s,u;return c(this,(function(c){switch(c.label){case 0:if(e=t.outputStride,n=t.quantBytes,o=t.multiplier,null==r)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return i=function(t,e,n){var r={1:"100",.75:"075",.5:"050"},a="model-stride"+t+".json";return 4===n?X+"float/"+r[e]+"/"+a:X+"quant"+n+"/"+r[e]+"/"+a}(e,o,n),[4,Object(a.a)(t.modelUrl||i)];case 1:return s=c.sent(),u=new m(s,e),[2,new dt(u)]}}))}))}function mt(t){return u(this,void 0,void 0,(function(){var e,n,o,i,s;return c(this,(function(u){switch(u.label){case 0:if(e=t.outputStride,n=t.quantBytes,null==r)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return o=function(t,e){var n="model-stride"+t+".json";return 4===e?K+"float/"+n:K+"quant"+e+"/"+n}(e,n),[4,Object(a.a)(t.modelUrl||o)];case 1:return i=u.sent(),s=new q(i,e),[2,new dt(s)]}}))}))}function vt(t){return void 0===t&&(t=at),u(this,void 0,void 0,(function(){return c(this,(function(e){return"ResNet50"===(t=function(t){if(null==(t=t||at).architecture&&(t.architecture="MobileNetV1"),ot.indexOf(t.architecture)<0)throw new Error("Invalid architecture "+t.architecture+". Should be one of "+ot);if(null==t.outputStride&&(t.outputStride=16),it[t.architecture].indexOf(t.outputStride)<0)throw new Error("Invalid outputStride "+t.outputStride+". Should be one of "+it[t.architecture]+" for architecture "+t.architecture+".");if(null==t.multiplier&&(t.multiplier=1),st[t.architecture].indexOf(t.multiplier)<0)throw new Error("Invalid multiplier "+t.multiplier+". Should be one of "+st[t.architecture]+" for architecture "+t.architecture+".");if(null==t.quantBytes&&(t.quantBytes=4),ut.indexOf(t.quantBytes)<0)throw new Error("Invalid quantBytes "+t.quantBytes+". Should be one of "+ut+" for architecture "+t.architecture+".");return t}(t)).architecture?[2,mt(t)]:"MobileNetV1"===t.architecture?[2,ht(t)]:[2,null]}))}))}var gt=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],yt=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function xt(t,e,n,r,a,o){var i,s,u,c,l,p,f,d,h,m,v,g,y,x,b,w,C,E,S,N,I,R=t.data,T=2*o+1,k=r-1,A=a-1,O=o+1,D=O*(O+1)/2,_=new bt,F=_;for(u=1;u<T;u++)F=F.next=new bt,u===O&&(I=F);F.next=_;var M=null,B=null;f=p=0;var P=gt[o],L=yt[o];for(s=0;s<a;s++){for(x=b=w=d=h=m=0,v=O*(C=R[p]),g=O*(E=R[p+1]),y=O*(S=R[p+2]),d+=D*C,h+=D*E,m+=D*S,F=_,u=0;u<O;u++)F.r=C,F.g=E,F.b=S,F=F.next;for(u=1;u<O;u++)c=p+((k<u?k:u)<<2),d+=(F.r=C=R[c])*(N=O-u),h+=(F.g=E=R[c+1])*N,m+=(F.b=S=R[c+2])*N,x+=C,b+=E,w+=S,F=F.next;for(M=_,B=I,i=0;i<r;i++)R[p]=d*P>>L,R[p+1]=h*P>>L,R[p+2]=m*P>>L,d-=v,h-=g,m-=y,v-=M.r,g-=M.g,y-=M.b,c=f+((c=i+o+1)<k?c:k)<<2,d+=x+=M.r=R[c],h+=b+=M.g=R[c+1],m+=w+=M.b=R[c+2],M=M.next,v+=C=B.r,g+=E=B.g,y+=S=B.b,x-=C,b-=E,w-=S,B=B.next,p+=4;f+=r}for(i=0;i<r;i++){for(b=w=x=h=m=d=0,v=O*(C=R[p=i<<2]),g=O*(E=R[p+1]),y=O*(S=R[p+2]),d+=D*C,h+=D*E,m+=D*S,F=_,u=0;u<O;u++)F.r=C,F.g=E,F.b=S,F=F.next;for(l=r,u=1;u<=o;u++)p=l+i<<2,d+=(F.r=C=R[p])*(N=O-u),h+=(F.g=E=R[p+1])*N,m+=(F.b=S=R[p+2])*N,x+=C,b+=E,w+=S,F=F.next,u<A&&(l+=r);for(p=i,M=_,B=I,s=0;s<a;s++)R[c=p<<2]=d*P>>L,R[c+1]=h*P>>L,R[c+2]=m*P>>L,d-=v,h-=g,m-=y,v-=M.r,g-=M.g,y-=M.b,c=i+((c=s+O)<A?c:A)*r<<2,d+=x+=M.r=R[c],h+=b+=M.g=R[c+1],m+=w+=M.b=R[c+2],M=M.next,v+=C=B.r,g+=E=B.g,y+=S=B.b,x-=C,b-=E,w-=S,B=B.next,p+=r}return t}var bt=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.r=0,this.g=0,this.b=0,this.a=0,this.next=null};const wt=URL.createObjectURL(new Blob(["\n var timer;\n\n onmessage = function(request) {\n switch (request.data.id) {\n case 1: {\n timer = setTimeout(() => {\n postMessage({ id: 3 });\n }, request.data.timeMs);\n break;\n }\n case 2: {\n if (timer) {\n clearTimeout(timer);\n }\n break;\n }\n }\n };\n"],{type:"application/javascript"}));class Ct{constructor(t){this._bpModel=t,this._onMaskFrameTimer=this._onMaskFrameTimer.bind(this),this._outputCanvasElement=document.createElement("canvas"),this._outputCanvasElement.getContext("2d"),this._inputVideoElement=document.createElement("video"),this._inputVideoCanvasElement=document.createElement("canvas")}async _onMaskFrameTimer(t){3===t.data.id&&await this._renderMask()}async _renderMask(){this._maskInProgress||(this._maskInProgress=!0,this._bpModel.segmentPerson(this._inputVideoElement,{internalResolution:"low",maxDetections:1,segmentationThreshold:.7,flipHorizontal:!1,scoreThreshold:.2}).then(t=>{this._segmentationData=t,this._maskInProgress=!1}));const t=this._inputVideoCanvasElement.getContext("2d");t.drawImage(this._inputVideoElement,0,0);const e=t.getImageData(0,0,this._inputVideoCanvasElement.width,this._inputVideoCanvasElement.height);if(this._segmentationData){const t=new ImageData(e.data.slice(),e.width,e.height);xt(t,0,0,e.width,e.height,12);for(let n=0;n<this._outputCanvasElement.width;n++)for(let r=0;r<this._outputCanvasElement.height;r++){const a=r*this._outputCanvasElement.width+n;0===this._segmentationData.data[a]&&(e.data[4*a]=t.data[4*a],e.data[4*a+1]=t.data[4*a+1],e.data[4*a+2]=t.data[4*a+2],e.data[4*a+3]=t.data[4*a+3])}}this._outputCanvasElement.getContext("2d").putImageData(e,0,0),this._maskFrameTimerWorker.postMessage({id:1,timeMs:1e3/30})}isEnabled(t){return t.isVideoTrack()&&"camera"===t.videoType}startEffect(t){this._maskFrameTimerWorker=new Worker(wt,{name:"Blur effect worker"}),this._maskFrameTimerWorker.onmessage=this._onMaskFrameTimer;const e=t.getVideoTracks()[0],{height:n,frameRate:r,width:a}=e.getSettings?e.getSettings():e.getConstraints();return this._outputCanvasElement.width=parseInt(a,10),this._outputCanvasElement.height=parseInt(n,10),this._inputVideoCanvasElement.width=parseInt(a,10),this._inputVideoCanvasElement.height=parseInt(n,10),this._inputVideoElement.width=parseInt(a,10),this._inputVideoElement.height=parseInt(n,10),this._inputVideoElement.autoplay=!0,this._inputVideoElement.srcObject=t,this._inputVideoElement.onloadeddata=()=>{this._maskFrameTimerWorker.postMessage({id:1,timeMs:1e3/30})},this._outputCanvasElement.captureStream(parseInt(r,10))}stopEffect(){this._maskFrameTimerWorker.postMessage({id:2}),this._maskFrameTimerWorker.terminate()}}async function Et(){if(!MediaStreamTrack.prototype.getSettings&&!MediaStreamTrack.prototype.getConstraints)throw new Error("JitsiStreamBlurEffect not supported!");const t=await vt({architecture:"MobileNetV1",outputStride:16,multiplier:.5,quantBytes:2});return new Ct(t)}}]);
//# sourceMappingURL=video-blur-effect.min.map
|
import vue from 'rollup-plugin-vue';
import buble from 'rollup-plugin-buble';
import filesize from 'rollup-plugin-filesize';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import replace from 'rollup-plugin-replace';
import json from 'rollup-plugin-json';
const processEnv = conf => ({
// parenthesis to avoid syntax errors in places where {} is interpreted as a block
'process.env': `(${JSON.stringify(conf)})`,
});
export default [
{
input: 'src/instantsearch.js',
external: [
'algoliasearch-helper',
'instantsearch.js/es',
'instantsearch.js/es/connectors',
'vue',
],
output: [
{
sourcemap: true,
file: `dist/vue-instantsearch.common.js`,
format: 'cjs',
exports: 'named',
},
{
sourcemap: true,
file: `dist/vue-instantsearch.esm.js`,
format: 'es',
},
],
plugins: [
commonjs(),
vue({ compileTemplate: true, css: false }),
json(),
buble({
transforms: {
dangerousForOf: true,
},
}),
terser({
sourcemap: true,
}),
filesize(),
],
},
{
input: 'src/instantsearch.umd.js',
external: ['vue'],
output: [
{
sourcemap: true,
file: `dist/vue-instantsearch.js`,
format: 'umd',
name: 'VueInstantSearch',
exports: 'named',
globals: {
vue: 'Vue',
},
},
],
plugins: [
vue({ compileTemplate: true, css: false }),
json(),
resolve({
browser: true,
preferBuiltins: false,
}),
buble({
transforms: {
dangerousForOf: true,
},
}),
replace(processEnv({ NODE_ENV: 'production' })),
commonjs(),
terser({
sourcemap: true,
}),
filesize(),
],
},
];
|
"""
Convenient shortcuts to manage or check object permissions.
"""
from __future__ import unicode_literals
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Count, Q
from django.shortcuts import _get_queryset
from itertools import groupby
from guardian.compat import get_user_model
from guardian.compat import basestring
from guardian.core import ObjectPermissionChecker
from guardian.exceptions import MixedContentTypeError
from guardian.exceptions import WrongAppError
from guardian.utils import get_anonymous_user
from guardian.utils import get_identity
from guardian.utils import get_user_obj_perms_model
from guardian.utils import get_group_obj_perms_model
import warnings
def assign_perm(perm, user_or_group, obj=None):
"""
Assigns permission to user/group and object pair.
:param perm: proper permission for given ``obj``, as string (in format:
``app_label.codename`` or ``codename``). If ``obj`` is not given, must
be in format ``app_label.codename``.
:param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
passing any other object would raise
``guardian.exceptions.NotUserNorGroup`` exception
:param obj: persisted Django's ``Model`` instance or ``None`` if assigning
global permission. Default is ``None``.
We can assign permission for ``Model`` instance for specific user:
>>> from django.contrib.sites.models import Site
>>> from guardian.models import User
>>> from guardian.shortcuts import assign_perm
>>> site = Site.objects.get_current()
>>> user = User.objects.create(username='joe')
>>> assign_perm("change_site", user, site)
<UserObjectPermission: example.com | joe | change_site>
>>> user.has_perm("change_site", site)
True
... or we can assign permission for group:
>>> group = Group.objects.create(name='joe-group')
>>> user.groups.add(group)
>>> assign_perm("delete_site", group, site)
<GroupObjectPermission: example.com | joe-group | delete_site>
>>> user.has_perm("delete_site", site)
True
**Global permissions**
This function may also be used to assign standard, *global* permissions if
``obj`` parameter is omitted. Added Permission would be returned in that
case:
>>> assign_perm("sites.change_site", user)
<Permission: sites | site | Can change site>
"""
user, group = get_identity(user_or_group)
# If obj is None we try to operate on global permissions
if obj is None:
try:
app_label, codename = perm.split('.', 1)
except ValueError:
raise ValueError("For global permissions, first argument must be in"
" format: 'app_label.codename' (is %r)" % perm)
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
if user:
user.user_permissions.add(perm)
return perm
if group:
group.permissions.add(perm)
return perm
perm = perm.split('.')[-1]
if user:
model = get_user_obj_perms_model(obj)
return model.objects.assign_perm(perm, user, obj)
if group:
model = get_group_obj_perms_model(obj)
return model.objects.assign_perm(perm, group, obj)
def assign(perm, user_or_group, obj=None):
""" Depreciated function name left in for compatibility"""
warnings.warn("Shortcut function 'assign' is being renamed to 'assign_perm'. Update your code accordingly as old name will be depreciated in 2.0 version.", DeprecationWarning)
return assign_perm(perm, user_or_group, obj)
def remove_perm(perm, user_or_group=None, obj=None):
"""
Removes permission from user/group and object pair.
:param perm: proper permission for given ``obj``, as string (in format:
``app_label.codename`` or ``codename``). If ``obj`` is not given, must
be in format ``app_label.codename``.
:param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
passing any other object would raise
``guardian.exceptions.NotUserNorGroup`` exception
:param obj: persisted Django's ``Model`` instance or ``None`` if assigning
global permission. Default is ``None``.
"""
user, group = get_identity(user_or_group)
if obj is None:
try:
app_label, codename = perm.split('.', 1)
except ValueError:
raise ValueError("For global permissions, first argument must be in"
" format: 'app_label.codename' (is %r)" % perm)
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
if user:
user.user_permissions.remove(perm)
return
elif group:
group.permissions.remove(perm)
return
perm = perm.split('.')[-1]
if user:
model = get_user_obj_perms_model(obj)
model.objects.remove_perm(perm, user, obj)
if group:
model = get_group_obj_perms_model(obj)
model.objects.remove_perm(perm, group, obj)
def get_perms(user_or_group, obj):
"""
Returns permissions for given user/group and object pair, as list of
strings.
"""
check = ObjectPermissionChecker(user_or_group)
return check.get_perms(obj)
def get_perms_for_model(cls):
"""
Returns queryset of all Permission objects for the given class. It is
possible to pass Model as class or instance.
"""
if isinstance(cls, basestring):
app_label, model_name = cls.split('.')
model = models.get_model(app_label, model_name)
else:
model = cls
ctype = ContentType.objects.get_for_model(model)
return Permission.objects.filter(content_type=ctype)
def get_users_with_perms(obj, attach_perms=False, with_superusers=False,
with_group_users=True):
"""
Returns queryset of all ``User`` objects with *any* object permissions for
the given ``obj``.
:param obj: persisted Django's ``Model`` instance
:param attach_perms: Default: ``False``. If set to ``True`` result would be
dictionary of ``User`` instances with permissions' codenames list as
values. This would fetch users eagerly!
:param with_superusers: Default: ``False``. If set to ``True`` result would
contain all superusers.
:param with_group_users: Default: ``True``. If set to ``False`` result would
**not** contain those users who have only group permissions for given
``obj``.
Example::
>>> from django.contrib.flatpages.models import FlatPage
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import assign_perm, get_users_with_perms
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
>>> assign_perm('change_flatpage', joe, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage']}
"""
ctype = ContentType.objects.get_for_model(obj)
if not attach_perms:
# It's much easier without attached perms so we do it first if that is
# the case
user_model = get_user_obj_perms_model(obj)
related_name = user_model.user.field.related_query_name()
if user_model.objects.is_generic():
user_filters = {
'%s__content_type' % related_name: ctype,
'%s__object_pk' % related_name: obj.pk,
}
else:
user_filters = {'%s__content_object' % related_name: obj}
qset = Q(**user_filters)
if with_group_users:
group_model = get_group_obj_perms_model(obj)
group_rel_name = group_model.group.field.related_query_name()
if group_model.objects.is_generic():
group_filters = {
'groups__%s__content_type' % group_rel_name: ctype,
'groups__%s__object_pk' % group_rel_name: obj.pk,
}
else:
group_filters = {
'groups__%s__content_object' % group_rel_name: obj,
}
qset = qset | Q(**group_filters)
if with_superusers:
qset = qset | Q(is_superuser=True)
return get_user_model().objects.filter(qset).distinct()
else:
# TODO: Do not hit db for each user!
users = {}
for user in get_users_with_perms(obj,
with_group_users=with_group_users):
users[user] = sorted(get_perms(user, obj))
return users
def get_groups_with_perms(obj, attach_perms=False):
"""
Returns queryset of all ``Group`` objects with *any* object permissions for
the given ``obj``.
:param obj: persisted Django's ``Model`` instance
:param attach_perms: Default: ``False``. If set to ``True`` result would be
dictionary of ``Group`` instances with permissions' codenames list as
values. This would fetch groups eagerly!
Example::
>>> from django.contrib.flatpages.models import FlatPage
>>> from guardian.shortcuts import assign_perm, get_groups_with_perms
>>> from guardian.models import Group
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> admins = Group.objects.create(name='Admins')
>>> assign_perm('change_flatpage', admins, page)
>>>
>>> get_groups_with_perms(page)
[<Group: admins>]
>>>
>>> get_groups_with_perms(page, attach_perms=True)
{<Group: admins>: [u'change_flatpage']}
"""
ctype = ContentType.objects.get_for_model(obj)
if not attach_perms:
# It's much easier without attached perms so we do it first if that is
# the case
group_model = get_group_obj_perms_model(obj)
group_rel_name = group_model.group.field.related_query_name()
if group_model.objects.is_generic():
group_filters = {
'%s__content_type' % group_rel_name: ctype,
'%s__object_pk' % group_rel_name: obj.pk,
}
else:
group_filters = {'%s__content_object' % group_rel_name: obj}
groups = Group.objects.filter(**group_filters).distinct()
return groups
else:
# TODO: Do not hit db for each group!
groups = {}
for group in get_groups_with_perms(obj):
if not group in groups:
groups[group] = sorted(get_perms(group, obj))
return groups
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
with_superuser=True):
"""
Returns queryset of objects for which a given ``user`` has *all*
permissions present at ``perms``.
:param user: ``User`` or ``AnonymousUser`` instance for which objects would
be returned.
:param perms: single permission string, or sequence of permission strings
which should be checked.
If ``klass`` parameter is not given, those should be full permission
names rather than only codenames (i.e. ``auth.change_user``). If more than
one permission is present within sequence, their content type **must** be
the same or ``MixedContentTypeError`` exception would be raised.
:param klass: may be a Model, Manager or QuerySet object. If not given
this parameter would be computed based on given ``params``.
:param use_groups: if ``False``, wouldn't check user's groups object
permissions. Default is ``True``.
:param any_perm: if True, any of permission in sequence is accepted
:param with_superuser: if ``True`` returns the entire queryset if not it will
only return objects the user has explicit permissions.
:raises MixedContentTypeError: when computed content type for ``perms``
and/or ``klass`` clashes.
:raises WrongAppError: if cannot compute app label for given ``perms``/
``klass``.
Example::
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import get_objects_for_user
>>> joe = User.objects.get(username='joe')
>>> get_objects_for_user(joe, 'auth.change_group')
[]
>>> from guardian.shortcuts import assign_perm
>>> group = Group.objects.create('some group')
>>> assign_perm('auth.change_group', joe, group)
>>> get_objects_for_user(joe, 'auth.change_group')
[<Group some group>]
The permission string can also be an iterable. Continuing with the previous example:
>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
[]
>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
[<Group some group>]
>>> assign_perm('auth.delete_group', joe, group)
>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
[<Group some group>]
"""
if isinstance(perms, basestring):
perms = [perms]
ctype = None
app_label = None
codenames = set()
# Compute codenames set and ctype if possible
for perm in perms:
if '.' in perm:
new_app_label, codename = perm.split('.', 1)
if app_label is not None and app_label != new_app_label:
raise MixedContentTypeError("Given perms must have same app "
"label (%s != %s)" % (app_label, new_app_label))
else:
app_label = new_app_label
else:
codename = perm
codenames.add(codename)
if app_label is not None:
new_ctype = ContentType.objects.get(app_label=app_label,
permission__codename=codename)
if ctype is not None and ctype != new_ctype:
raise MixedContentTypeError("ContentType was once computed "
"to be %s and another one %s" % (ctype, new_ctype))
else:
ctype = new_ctype
# Compute queryset and ctype if still missing
if ctype is None and klass is None:
raise WrongAppError("Cannot determine content type")
elif ctype is None and klass is not None:
queryset = _get_queryset(klass)
ctype = ContentType.objects.get_for_model(queryset.model)
elif ctype is not None and klass is None:
queryset = _get_queryset(ctype.model_class())
else:
queryset = _get_queryset(klass)
if ctype.model_class() != queryset.model:
raise MixedContentTypeError("Content type for given perms and "
"klass differs")
# At this point, we should have both ctype and queryset and they should
# match which means: ctype.model_class() == queryset.model
# we should also have ``codenames`` list
# First check if user is superuser and if so, return queryset immediately
if with_superuser and user.is_superuser:
return queryset
# Check if the user is anonymous. The
# django.contrib.auth.models.AnonymousUser object doesn't work for queries
# and it's nice to be able to pass in request.user blindly.
if user.is_anonymous():
user = get_anonymous_user()
# Now we should extract list of pk values for which we would filter queryset
user_model = get_user_obj_perms_model(queryset.model)
user_obj_perms_queryset = (user_model.objects
.filter(user=user)
.filter(permission__content_type=ctype)
.filter(permission__codename__in=codenames))
if user_model.objects.is_generic():
fields = ['object_pk', 'permission__codename']
else:
fields = ['content_object__pk', 'permission__codename']
if use_groups:
group_model = get_group_obj_perms_model(queryset.model)
group_filters = {
'permission__content_type': ctype,
'permission__codename__in': codenames,
'group__%s' % get_user_model().groups.field.related_query_name(): user,
}
groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
if group_model.objects.is_generic():
fields = ['object_pk', 'permission__codename']
else:
fields = ['content_object__pk', 'permission__codename']
if not any_perm:
user_obj_perms = user_obj_perms_queryset.values_list(*fields)
groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
data = list(user_obj_perms) + list(groups_obj_perms)
keyfunc = lambda t: t[0] # sorting/grouping by pk (first in result tuple)
data = sorted(data, key=keyfunc)
pk_list = []
for pk, group in groupby(data, keyfunc):
obj_codenames = set((e[1] for e in group))
if codenames.issubset(obj_codenames):
pk_list.append(pk)
objects = queryset.filter(pk__in=pk_list)
return objects
if not any_perm and len(codenames) > 1:
counts = user_obj_perms_queryset.values(fields[0]).annotate(object_pk_count=Count(fields[0]))
user_obj_perms_queryset = counts.filter(object_pk_count__gte=len(codenames))
values = user_obj_perms_queryset.values_list(fields[0], flat=True)
if user_model.objects.is_generic():
values = list(values)
objects = queryset.filter(pk__in=values)
if use_groups:
values = groups_obj_perms_queryset.values_list(fields[0], flat=True)
if group_model.objects.is_generic():
values = list(values)
objects |= queryset.filter(pk__in=values)
return objects
def get_objects_for_group(group, perms, klass=None, any_perm=False):
"""
Returns queryset of objects for which a given ``group`` has *all*
permissions present at ``perms``.
:param group: ``Group`` instance for which objects would be returned.
:param perms: single permission string, or sequence of permission strings
which should be checked.
If ``klass`` parameter is not given, those should be full permission
names rather than only codenames (i.e. ``auth.change_user``). If more than
one permission is present within sequence, their content type **must** be
the same or ``MixedContentTypeError`` exception would be raised.
:param klass: may be a Model, Manager or QuerySet object. If not given
this parameter would be computed based on given ``params``.
:param any_perm: if True, any of permission in sequence is accepted
:raises MixedContentTypeError: when computed content type for ``perms``
and/or ``klass`` clashes.
:raises WrongAppError: if cannot compute app label for given ``perms``/
``klass``.
Example:
Let's assume we have a ``Task`` model belonging to the ``tasker`` app with
the default add_task, change_task and delete_task permissions provided
by Django::
>>> from guardian.shortcuts import get_objects_for_group
>>> from tasker import Task
>>> group = Group.objects.create('some group')
>>> task = Task.objects.create('some task')
>>> get_objects_for_group(group, 'tasker.add_task')
[]
>>> from guardian.shortcuts import assign_perm
>>> assign_perm('tasker.add_task', group, task)
>>> get_objects_for_group(group, 'tasker.add_task')
[<Task some task>]
The permission string can also be an iterable. Continuing with the previous example:
>>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
[]
>>> assign_perm('tasker.delete_task', group, task)
>>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
[<Task some task>]
"""
if isinstance(perms, basestring):
perms = [perms]
ctype = None
app_label = None
codenames = set()
# Compute codenames set and ctype if possible
for perm in perms:
if '.' in perm:
new_app_label, codename = perm.split('.', 1)
if app_label is not None and app_label != new_app_label:
raise MixedContentTypeError("Given perms must have same app "
"label (%s != %s)" % (app_label, new_app_label))
else:
app_label = new_app_label
else:
codename = perm
codenames.add(codename)
if app_label is not None:
new_ctype = ContentType.objects.get(app_label=app_label,
permission__codename=codename)
if ctype is not None and ctype != new_ctype:
raise MixedContentTypeError("ContentType was once computed "
"to be %s and another one %s" % (ctype, new_ctype))
else:
ctype = new_ctype
# Compute queryset and ctype if still missing
if ctype is None and klass is None:
raise WrongAppError("Cannot determine content type")
elif ctype is None and klass is not None:
queryset = _get_queryset(klass)
ctype = ContentType.objects.get_for_model(queryset.model)
elif ctype is not None and klass is None:
queryset = _get_queryset(ctype.model_class())
else:
queryset = _get_queryset(klass)
if ctype.model_class() != queryset.model:
raise MixedContentTypeError("Content type for given perms and "
"klass differs")
# At this point, we should have both ctype and queryset and they should
# match which means: ctype.model_class() == queryset.model
# we should also have ``codenames`` list
# Now we should extract list of pk values for which we would filter queryset
group_model = get_group_obj_perms_model(queryset.model)
groups_obj_perms_queryset = (group_model.objects
.filter(group=group)
.filter(permission__content_type=ctype)
.filter(permission__codename__in=codenames))
if group_model.objects.is_generic():
fields = ['object_pk', 'permission__codename']
else:
fields = ['content_object__pk', 'permission__codename']
groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
data = list(groups_obj_perms)
keyfunc = lambda t: t[0] # sorting/grouping by pk (first in result tuple)
data = sorted(data, key=keyfunc)
pk_list = []
for pk, group in groupby(data, keyfunc):
obj_codenames = set((e[1] for e in group))
if any_perm or codenames.issubset(obj_codenames):
pk_list.append(pk)
objects = queryset.filter(pk__in=pk_list)
return objects
|
/** @fileOverview Random number generator.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace Random number generator
*
* @description
* <p>
* This random number generator is a derivative of Ferguson and Schneier's
* generator Fortuna. It collects entropy from various events into several
* pools, implemented by streaming SHA-256 instances. It differs from
* ordinary Fortuna in a few ways, though.
* </p>
*
* <p>
* Most importantly, it has an entropy estimator. This is present because
* there is a strong conflict here between making the generator available
* as soon as possible, and making sure that it doesn't "run on empty".
* In Fortuna, there is a saved state file, and the system is likely to have
* time to warm up.
* </p>
*
* <p>
* Second, because users are unlikely to stay on the page for very long,
* and to speed startup time, the number of pools increases logarithmically:
* a new pool is created when the previous one is actually used for a reseed.
* This gives the same asymptotic guarantees as Fortuna, but gives more
* entropy to early reseeds.
* </p>
*
* <p>
* The entire mechanism here feels pretty klunky. Furthermore, there are
* several improvements that should be made, including support for
* dedicated cryptographic functions that may be present in some browsers;
* state files in local storage; cookies containing randomness; etc. So
* look for improvements in future versions.
* </p>
*/
sjcl.random = {
/** Generate several random words, and return them in an array
* @param {Number} nwords The number of words to generate.
*/
randomWords: function (nwords, paranoia) {
var out = [], i, readiness = this.isReady(paranoia), g;
if (readiness === this._NOT_READY) {
throw new sjcl.exception.notReady("generator isn't seeded");
} else if (readiness & this._REQUIRES_RESEED) {
this._reseedFromPools(!(readiness & this._READY));
}
for (i=0; i<nwords; i+= 4) {
if ((i+1) % this._MAX_WORDS_PER_BURST === 0) {
this._gate();
}
g = this._gen4words();
out.push(g[0],g[1],g[2],g[3]);
}
this._gate();
return out.slice(0,nwords);
},
setDefaultParanoia: function (paranoia) {
this._defaultParanoia = paranoia;
},
/**
* Add entropy to the pools.
* @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string
* @param {Number} estimatedEntropy The estimated entropy of data, in bits
* @param {String} source The source of the entropy, eg "mouse"
*/
addEntropy: function (data, estimatedEntropy, source) {
source = source || "user";
var id,
i, ty = 0, tmp,
t = (new Date()).valueOf(),
robin = this._robins[source],
oldReady = this.isReady();
id = this._collectorIds[source];
if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }
if (robin === undefined) { robin = this._robins[source] = 0; }
this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length;
switch(typeof(data)) {
case "number":
data=[data];
ty=1;
break;
case "object":
if (estimatedEntropy === undefined) {
/* horrible entropy estimator */
estimatedEntropy = 0;
for (i=0; i<data.length; i++) {
tmp= data[i];
while (tmp>0) {
estimatedEntropy++;
tmp = tmp >>> 1;
}
}
}
this._pools[robin].update([id,this._eventId++,ty||2,estimatedEntropy,t,data.length].concat(data));
break;
case "string":
if (estimatedEntropy === undefined) {
/* English text has just over 1 bit per character of entropy.
* But this might be HTML or something, and have far less
* entropy than English... Oh well, let's just say one bit.
*/
estimatedEntropy = data.length;
}
this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]);
this._pools[robin].update(data);
break;
default:
throw new sjcl.exception.bug("random: addEntropy only supports number, array or string");
}
/* record the new strength */
this._poolEntropy[robin] += estimatedEntropy;
this._poolStrength += estimatedEntropy;
/* fire off events */
if (oldReady === this._NOT_READY) {
if (this.isReady() !== this._NOT_READY) {
this._fireEvent("seeded", Math.max(this._strength, this._poolStrength));
}
this._fireEvent("progress", this.getProgress());
}
},
/** Is the generator ready? */
isReady: function (paranoia) {
var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];
if (this._strength && this._strength >= entropyRequired) {
return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?
this._REQUIRES_RESEED | this._READY :
this._READY;
} else {
return (this._poolStrength >= entropyRequired) ?
this._REQUIRES_RESEED | this._NOT_READY :
this._NOT_READY;
}
},
/** Get the generator's progress toward readiness, as a fraction */
getProgress: function (paranoia) {
var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];
if (this._strength >= entropyRequired) {
return 1.0;
} else {
return (this._poolStrength > entropyRequired) ?
1.0 :
this._poolStrength / entropyRequired;
}
},
/** start the built-in entropy collectors */
startCollectors: function () {
if (this._collectorsStarted) { return; }
if (window.addEventListener) {
window.addEventListener("load", this._loadTimeCollector, false);
window.addEventListener("mousemove", this._mouseCollector, false);
} else if (document.attachEvent) {
document.attachEvent("onload", this._loadTimeCollector);
document.attachEvent("onmousemove", this._mouseCollector);
}
else {
throw new sjcl.exception.bug("can't attach event");
}
this._collectorsStarted = true;
},
/** stop the built-in entropy collectors */
stopCollectors: function () {
if (!this._collectorsStarted) { return; }
if (window.removeEventListener) {
window.removeEventListener("load", this._loadTimeCollector, false);
window.removeEventListener("mousemove", this._mouseCollector, false);
} else if (window.detachEvent) {
window.detachEvent("onload", this._loadTimeCollector);
window.detachEvent("onmousemove", this._mouseCollector);
}
this._collectorsStarted = false;
},
/* use a cookie to store entropy.
useCookie: function (all_cookies) {
throw new sjcl.exception.bug("random: useCookie is unimplemented");
},*/
/** add an event listener for progress or seeded-ness. */
addEventListener: function (name, callback) {
this._callbacks[name][this._callbackI++] = callback;
},
/** remove an event listener for progress or seeded-ness */
removeEventListener: function (name, cb) {
var i, j, cbs=this._callbacks[name], jsTemp=[];
/* I'm not sure if this is necessary; in C++, iterating over a
* collection and modifying it at the same time is a no-no.
*/
for (j in cbs) {
if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
jsTemp.push(j);
}
}
for (i=0; i<jsTemp.length; i++) {
j = jsTemp[i];
delete cbs[j];
}
},
/* private */
_pools : [new sjcl.hash.sha256()],
_poolEntropy : [0],
_reseedCount : 0,
_robins : {},
_eventId : 0,
_collectorIds : {},
_collectorIdNext : 0,
_strength : 0,
_poolStrength : 0,
_nextReseed : 0,
_key : [0,0,0,0,0,0,0,0],
_counter : [0,0,0,0],
_cipher : undefined,
_defaultParanoia : 6,
/* event listener stuff */
_collectorsStarted : false,
_callbacks : {progress: {}, seeded: {}},
_callbackI : 0,
/* constants */
_NOT_READY : 0,
_READY : 1,
_REQUIRES_RESEED : 2,
_MAX_WORDS_PER_BURST : 65536,
_PARANOIA_LEVELS : [0,48,64,96,128,192,256,384,512,768,1024],
_MILLISECONDS_PER_RESEED : 30000,
_BITS_PER_RESEED : 80,
/** Generate 4 random words, no reseed, no gate.
* @private
*/
_gen4words: function () {
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
return this._cipher.encrypt(this._counter);
},
/* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.
* @private
*/
_gate: function () {
this._key = this._gen4words().concat(this._gen4words());
this._cipher = new sjcl.cipher.aes(this._key);
},
/** Reseed the generator with the given words
* @private
*/
_reseed: function (seedWords) {
this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
this._cipher = new sjcl.cipher.aes(this._key);
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
},
/** reseed the data from the entropy pools
* @param full If set, use all the entropy pools in the reseed.
*/
_reseedFromPools: function (full) {
var reseedData = [], strength = 0, i;
this._nextReseed = reseedData[0] =
(new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
for (i=0; i<16; i++) {
/* On some browsers, this is cryptographically random. So we might
* as well toss it in the pot and stir...
*/
reseedData.push(Math.random()*0x100000000|0);
}
for (i=0; i<this._pools.length; i++) {
reseedData = reseedData.concat(this._pools[i].finalize());
strength += this._poolEntropy[i];
this._poolEntropy[i] = 0;
if (!full && (this._reseedCount & (1<<i))) { break; }
}
/* if we used the last pool, push a new one onto the stack */
if (this._reseedCount >= 1 << this._pools.length) {
this._pools.push(new sjcl.hash.sha256());
this._poolEntropy.push(0);
}
/* how strong was this reseed? */
this._poolStrength -= strength;
if (strength > this._strength) {
this._strength = strength;
}
this._reseedCount ++;
this._reseed(reseedData);
},
_mouseCollector: function (ev) {
var x = ev.x || ev.clientX || ev.offsetX, y = ev.y || ev.clientY || ev.offsetY;
sjcl.random.addEntropy([x,y], 2, "mouse");
},
_loadTimeCollector: function (ev) {
var d = new Date();
sjcl.random.addEntropy(d, 2, "loadtime");
},
_fireEvent: function (name, arg) {
var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];
/* TODO: there is a race condition between removing collectors and firing them */
/* I'm not sure if this is necessary; in C++, iterating over a
* collection and modifying it at the same time is a no-no.
*/
for (j in cbs) {
if (cbs.hasOwnProperty(j)) {
cbsTemp.push(cbs[j]);
}
}
for (j=0; j<cbsTemp.length; j++) {
cbsTemp[j](arg);
}
}
};
(function(){
try {
// get cryptographically strong entropy in Webkit
var ab = new Uint32Array(32);
crypto.getRandomValues(ab);
sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues");
} catch (e) {
// no getRandomValues :-(
}
})();
|
'use strict'
const {MariaDbManager} = require('../src')
const cfg = require('./cfg')
const manager = new MariaDbManager(cfg)
manager.healthcheck()
.then(() => console.log('OK'))
.catch(err => console.log('NOT OK\n', err))
|
/*
** Copyright 2005-2018 Solarflare Communications Inc.
** 7505 Irvine Center Drive, Irvine, CA 92618, USA
** Copyright 2002-2005 Level 5 Networks Inc.
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of version 2 of the GNU General Public License as
** published by the Free Software Foundation.
**
** 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.
*/
/**************************************************************************\
*//*! \file
** <L5_PRIVATE L5_SOURCE>
** \author
** \brief
** \date
** \cop (c) Level 5 Networks Limited.
** </L5_PRIVATE>
*//*
\**************************************************************************/
/*! \cidoxg_lib_ciapp */
#include <ci/app.h>
void ci_iarray_median(const int* start, const int* end, int* median_out)
{
ci_iarray_assert_valid(start, end);
ci_assert(end - start > 0);
ci_iarray_assert_sorted(start, end);
if( (end - start) & 1 )
*median_out = start[(end - start) / 2];
else
*median_out = (start[(end-start)/2] + start[(end-start)/2-1]) / 2;
}
/*! \cidoxg_end */
|
import React from 'react';
import { useSelector } from 'react-redux';
import { StatusBar, YellowBox } from 'react-native';
import FlashMessage from 'react-native-flash-message';
import createRouter from './routes';
YellowBox.ignoreWarnings(['Unrecognized WebSocket']);
export default function App() {
const signed = useSelector(state => state.student.signed);
const Routes = createRouter(signed);
return (
<>
<StatusBar backgroundColor="#fff" />
<Routes />
<FlashMessage icon="auto" duration={3000} style={{ marginTop: 25 }} />
</>
);
}
StatusBar.setTranslucent(true);
StatusBar.setBarStyle('dark-content');
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:50:46 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <UIKitCore/UIKitCore-Structs.h>
#import <libobjc.A.dylib/NSSecureCoding.h>
@protocol UICoordinateSpace;
@interface _UIBoundingPath : NSObject <NSSecureCoding> {
id<UICoordinateSpace> _coordinateSpace;
}
@property (assign,nonatomic,__weak) id<UICoordinateSpace> coordinateSpace; //@synthesize coordinateSpace=_coordinateSpace - In the implementation block
@property (nonatomic,readonly) BOOL isNonRectangular;
+(BOOL)supportsSecureCoding;
-(void)encodeWithCoder:(id)arg1 ;
-(id)initWithCoder:(id)arg1 ;
-(id<UICoordinateSpace>)coordinateSpace;
-(id)initWithCoordinateSpace:(id)arg1 ;
-(void)setCoordinateSpace:(id<UICoordinateSpace>)arg1 ;
-(CGRect)_inscribedRectInBoundingRect:(CGRect)arg1 byInsettingRect:(CGRect)arg2 onEdges:(unsigned long long)arg3 ;
-(CGRect)_largestInscribedRectInBoundingRect:(CGRect)arg1 withCenter:(CGPoint)arg2 aspectRatio:(double)arg3 ;
-(id)boundingPathForCoordinateSpace:(id)arg1 ;
-(BOOL)validateForCoordinateSpace;
-(BOOL)isNonRectangular;
-(CGRect)_inscribedRectInBoundingPathAndRect:(CGRect)arg1 byInsettingRect:(CGRect)arg2 onEdges:(unsigned long long)arg3 withOptions:(unsigned long long)arg4 ;
-(CGRect)_largestInscribedRectInBoundingPathAndRect:(CGRect)arg1 withCenter:(CGPoint)arg2 aspectRatio:(double)arg3 ;
@end
|
/**
* @file 处理文档的修改按钮
* @author xuexb <fe.xiaowu@gmail.com>
*/
/* global hexo */
'use strict';
const components = require('../tools/components.js');
hexo.extend.helper.register('raw_link', path => {
// 单独处理组件文档
if (path.indexOf('examples/') === 0) {
const name = path.slice(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
// 如果是核心组件
if (components.isCore(name)) {
return `https://github.com/mipengine/mip/edit/master/src/components/${name}.md`;
}
// 处理广告,因为广告是多个 markdown 在一个组件内
if (path === 'examples/mip-ad/mip-ad.md') {
return 'https://github.com/mipengine/mip-extensions/edit/master/mip-ad/README.md';
}
else if (path.replace('examples/', '').indexOf('mip-ad/') === 0) {
return `https://github.com/mipengine/mip-extensions/edit/master/${path.replace('examples/', '')}`;
}
return `https://github.com/mipengine/mip-extensions/edit/master/${name}/README.md`;
}
return `https://github.com/mipengine/www.mipengine.org/edit/master/source/${path}`;
});
|
from WGALP.workflow import Workflow
from WGALP.blocks.BWA import BWA
from WGALP.blocks.samtools_VSI import samtools_VSI
from WGALP.blocks.recycler import recycler
from WGALP.blocks.bwa_index import bwa_index
# prepare the steps necessary to correctly run recycler
class Recycler(Workflow):
def task(self, args_dict):
fastq_fwd = args_dict["fastq_fwd"]
fastq_rev = args_dict["fastq_rev"]
contigs = args_dict["contigs"]
assembly_graph = args_dict["assembly_graph"]
kmer_length = args_dict["kmer_length"]
# FastQC initial
bwa_index("bwa_index_recycler", self.root, contigs)
out_bwa = BWA("bwa_realign_contigs", self.root, contigs, fastq1=fastq_fwd, fastq2=fastq_rev)
out_vsi = samtools_VSI("vsi_realign_contigs", self.root, out_bwa["samfile"], index=True)
out_bwa.delete()
out_recycler = recycler("recycler", self.root, out_vsi["bamfile"], assembly_graph, kmer_length)
out_vsi.delete()
# return
return out_recycler.get_files()
|
void foobar ( int size, int array[*] );
void foobar ( int sizeXX, int array[sizeXX] )
{
}
void foo ( int sizeYY, int array[sizeYY] )
{
}
|
const express = require('express');
const router = express.Router();
const ArticleState = require("../../models/ArticleState");
router.patch("/", async (req, res) => {
const {validation, trim} = require("../../app/principals");
let param = req.body;
if (!param._id) {
res.send({
code: 500,
message: 'No se encontro el estado a modificar'
});
return;
}
try {
param.nombre = trim(param.nombre);
} catch (e) {
throw new Error(`Error detectando nombre: ${e}`);
}
let validate = validation({
nombre: {
value: param.nombre,
type: String
}
});
if (!validate.rsp) {
res.send({
code: 500,
message: validate.data
})
return;
}
let exists = "";
try {
exists = await ArticleState.findOne({
nombre: {
$regex: `^${param.nombre}$`,
$options: 'i'
},
_id: {
$ne: param._id
}
});
} catch (e) {
res.send({
code: 500,
message: `Error: ${e}`
})
return;
}
if (exists) {
res.send({
code: 500,
message: 'Este estado ya se encuentra en el sistema'
});
return;
}
const state = {
nombre: param.nombre
};
ArticleState.updateOne({
_id: param._id
}, state, {
upsert: false
}, (err, update) => {
if (err) {
res.send({
code: 500,
message: err
});
return;
}
if (!update.ok) {
res.send({
code: 500,
message: 'No se pudo actualizar el estado'
});
return;
}
res.send({
code: 200,
message: true
})
});
});
module.exports = router;
|
/*! For license information please see lab.js.LICENSE.txt */
!function(t,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define("lab",[],n):"object"==typeof exports?exports.lab=n():t.lab=n()}(window,(function(){return function(t){var n={};function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{enumerable:!0,get:r})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,n){if(1&n&&(t=e(t)),8&n)return t;if(4&n&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(e.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&n&&"string"!=typeof t)for(var o in t)e.d(r,o,function(n){return t[n]}.bind(null,o));return r},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.p="",e(e.s=305)}([function(t,n,e){var r=e(2),o=e(24).f,i=e(28),a=e(25),u=e(136),s=e(191),c=e(91);t.exports=function(t,n){var e,f,l,p,h,d=t.target,v=t.global,g=t.stat;if(e=v?r:g?r[d]||u(d,{}):(r[d]||{}).prototype)for(f in n){if(p=n[f],l=t.noTargetGet?(h=o(e,f))&&h.value:e[f],!c(v?f:d+(g?".":"#")+f,t.forced)&&void 0!==l){if(typeof p==typeof l)continue;s(p,l)}(t.sham||l&&l.sham)&&i(p,"sham",!0),a(e,f,p,t)}}},function(t,n){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,n,e){(function(n){var e=function(t){return t&&t.Math==Math&&t};t.exports=e("object"==typeof globalThis&&globalThis)||e("object"==typeof window&&window)||e("object"==typeof self&&self)||e("object"==typeof n&&n)||Function("return this")()}).call(this,e(134))},function(t,n){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,n,e){var r=e(3);t.exports=function(t){if(!r(t))throw TypeError(String(t)+" is not an object");return t}},function(t,n,e){var r=e(1);t.exports=!r((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(t,n,e){"use strict";var r,o=e(5),i=e(2),a=e(3),u=e(17),s=e(98),c=e(28),f=e(25),l=e(10).f,p=e(50),h=e(76),d=e(7),v=e(87),g=i.DataView,y=g&&g.prototype,m=i.Int8Array,b=m&&m.prototype,w=i.Uint8ClampedArray,x=w&&w.prototype,O=m&&p(m),S=b&&p(b),j=Object.prototype,E=j.isPrototypeOf,A=d("toStringTag"),k=v("TYPED_ARRAY_TAG"),T=!(!i.ArrayBuffer||!g),P=T&&!!h&&"Opera"!==s(i.opera),R=!1,_={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},M=function(t){return a(t)&&u(_,s(t))};for(r in _)i[r]||(P=!1);if((!P||"function"!=typeof O||O===Function.prototype)&&(O=function(){throw TypeError("Incorrect invocation")},P))for(r in _)i[r]&&h(i[r],O);if((!P||!S||S===j)&&(S=O.prototype,P))for(r in _)i[r]&&h(i[r].prototype,S);if(P&&p(x)!==S&&h(x,S),o&&!u(S,A))for(r in R=!0,l(S,A,{get:function(){return a(this)?this[k]:void 0}}),_)i[r]&&c(i[r],k,r);T&&h&&p(y)!==j&&h(y,j),t.exports={NATIVE_ARRAY_BUFFER:T,NATIVE_ARRAY_BUFFER_VIEWS:P,TYPED_ARRAY_TAG:R&&k,aTypedArray:function(t){if(M(t))return t;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(t){if(h){if(E.call(O,t))return t}else for(var n in _)if(u(_,r)){var e=i[n];if(e&&(t===e||E.call(e,t)))return t}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(t,n,e){if(o){if(e)for(var r in _){var a=i[r];a&&u(a.prototype,t)&&delete a.prototype[t]}S[t]&&!e||f(S,t,e?n:P&&b[t]||n)}},exportTypedArrayStaticMethod:function(t,n,e){var r,a;if(o){if(h){if(e)for(r in _)(a=i[r])&&u(a,t)&&delete a[t];if(O[t]&&!e)return;try{return f(O,t,e?n:P&&m[t]||n)}catch(t){}}for(r in _)!(a=i[r])||a[t]&&!e||f(a,t,n)}},isView:function(t){var n=s(t);return"DataView"===n||u(_,n)},isTypedArray:M,TypedArray:O,TypedArrayPrototype:S}},function(t,n,e){var r=e(2),o=e(138),i=e(17),a=e(87),u=e(142),s=e(193),c=o("wks"),f=r.Symbol,l=s?f:f&&f.withoutSetter||a;t.exports=function(t){return i(c,t)||(u&&i(f,t)?c[t]=f[t]:c[t]=l("Symbol."+t)),c[t]}},function(t,n,e){var r=e(43),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,n,e){"use strict";var r=e(34),o=e(60),i=e(96),a=e(29),u=e(152),s=a.set,c=a.getterFor("Array Iterator");t.exports=u(Array,"Array",(function(t,n){s(this,{type:"Array Iterator",target:r(t),index:0,kind:n})}),(function(){var t=c(this),n=t.target,e=t.kind,r=t.index++;return!n||r>=n.length?(t.target=void 0,{value:void 0,done:!0}):"keys"==e?{value:r,done:!1}:"values"==e?{value:n[r],done:!1}:{value:[r,n[r]],done:!1}}),"values"),i.Arguments=i.Array,o("keys"),o("values"),o("entries")},function(t,n,e){var r=e(5),o=e(188),i=e(4),a=e(46),u=Object.defineProperty;n.f=r?u:function(t,n,e){if(i(t),n=a(n,!0),i(e),o)try{return u(t,n,e)}catch(t){}if("get"in e||"set"in e)throw TypeError("Accessors not supported");return"value"in e&&(t[n]=e.value),t}},function(t,n,e){var r=e(146),o=e(25),i=e(333);r||o(Object.prototype,"toString",i,{unsafe:!0})},function(t,n,e){"use strict";var r=e(111).charAt,o=e(29),i=e(152),a=o.set,u=o.getterFor("String Iterator");i(String,"String",(function(t){a(this,{type:"String Iterator",string:String(t),index:0})}),(function(){var t,n=u(this),e=n.string,o=n.index;return o>=e.length?{value:void 0,done:!0}:(t=r(e,o),n.index+=t.length,{value:t,done:!1})}))},function(t,n,e){var r=e(2),o=e(260),i=e(9),a=e(28),u=e(7),s=u("iterator"),c=u("toStringTag"),f=i.values;for(var l in o){var p=r[l],h=p&&p.prototype;if(h){if(h[s]!==f)try{a(h,s,f)}catch(t){h[s]=f}if(h[c]||a(h,c,l),o[l])for(var d in i)if(h[d]!==i[d])try{a(h,d,i[d])}catch(t){h[d]=i[d]}}}},function(t,n,e){var r=e(27);t.exports=function(t){return Object(r(t))}},function(t,n,e){"use strict";var r=e(0),o=e(1),i=e(65),a=e(3),u=e(14),s=e(8),c=e(67),f=e(93),l=e(100),p=e(7),h=e(148),d=p("isConcatSpreadable"),v=h>=51||!o((function(){var t=[];return t[d]=!1,t.concat()[0]!==t})),g=l("concat"),y=function(t){if(!a(t))return!1;var n=t[d];return void 0!==n?!!n:i(t)};r({target:"Array",proto:!0,forced:!v||!g},{concat:function(t){var n,e,r,o,i,a=u(this),l=f(a,0),p=0;for(n=-1,r=arguments.length;n<r;n++)if(i=-1===n?a:arguments[n],y(i)){if(p+(o=s(i.length))>9007199254740991)throw TypeError("Maximum allowed index exceeded");for(e=0;e<o;e++,p++)e in i&&c(l,p,i[e])}else{if(p>=9007199254740991)throw TypeError("Maximum allowed index exceeded");c(l,p++,i)}return l.length=p,l}})},function(t,n,e){"use strict";var r=e(0),o=e(2),i=e(42),a=e(47),u=e(5),s=e(142),c=e(193),f=e(1),l=e(17),p=e(65),h=e(3),d=e(4),v=e(14),g=e(34),y=e(46),m=e(56),b=e(51),w=e(92),x=e(64),O=e(195),S=e(141),j=e(24),E=e(10),A=e(105),k=e(28),T=e(25),P=e(138),R=e(106),_=e(88),M=e(87),I=e(7),C=e(196),F=e(31),N=e(48),L=e(29),D=e(21).forEach,U=R("hidden"),q=I("toPrimitive"),B=L.set,z=L.getterFor("Symbol"),V=Object.prototype,W=o.Symbol,H=i("JSON","stringify"),$=j.f,G=E.f,Y=O.f,J=A.f,K=P("symbols"),X=P("op-symbols"),Q=P("string-to-symbol-registry"),Z=P("symbol-to-string-registry"),tt=P("wks"),nt=o.QObject,et=!nt||!nt.prototype||!nt.prototype.findChild,rt=u&&f((function(){return 7!=b(G({},"a",{get:function(){return G(this,"a",{value:7}).a}})).a}))?function(t,n,e){var r=$(V,n);r&&delete V[n],G(t,n,e),r&&t!==V&&G(V,n,r)}:G,ot=function(t,n){var e=K[t]=b(W.prototype);return B(e,{type:"Symbol",tag:t,description:n}),u||(e.description=n),e},it=c?function(t){return"symbol"==typeof t}:function(t){return Object(t)instanceof W},at=function(t,n,e){t===V&&at(X,n,e),d(t);var r=y(n,!0);return d(e),l(K,r)?(e.enumerable?(l(t,U)&&t[U][r]&&(t[U][r]=!1),e=b(e,{enumerable:m(0,!1)})):(l(t,U)||G(t,U,m(1,{})),t[U][r]=!0),rt(t,r,e)):G(t,r,e)},ut=function(t,n){d(t);var e=g(n),r=w(e).concat(lt(e));return D(r,(function(n){u&&!st.call(e,n)||at(t,n,e[n])})),t},st=function(t){var n=y(t,!0),e=J.call(this,n);return!(this===V&&l(K,n)&&!l(X,n))&&(!(e||!l(this,n)||!l(K,n)||l(this,U)&&this[U][n])||e)},ct=function(t,n){var e=g(t),r=y(n,!0);if(e!==V||!l(K,r)||l(X,r)){var o=$(e,r);return!o||!l(K,r)||l(e,U)&&e[U][r]||(o.enumerable=!0),o}},ft=function(t){var n=Y(g(t)),e=[];return D(n,(function(t){l(K,t)||l(_,t)||e.push(t)})),e},lt=function(t){var n=t===V,e=Y(n?X:g(t)),r=[];return D(e,(function(t){!l(K,t)||n&&!l(V,t)||r.push(K[t])})),r};(s||(T((W=function(){if(this instanceof W)throw TypeError("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,n=M(t),e=function(t){this===V&&e.call(X,t),l(this,U)&&l(this[U],n)&&(this[U][n]=!1),rt(this,n,m(1,t))};return u&&et&&rt(V,n,{configurable:!0,set:e}),ot(n,t)}).prototype,"toString",(function(){return z(this).tag})),T(W,"withoutSetter",(function(t){return ot(M(t),t)})),A.f=st,E.f=at,j.f=ct,x.f=O.f=ft,S.f=lt,C.f=function(t){return ot(I(t),t)},u&&(G(W.prototype,"description",{configurable:!0,get:function(){return z(this).description}}),a||T(V,"propertyIsEnumerable",st,{unsafe:!0}))),r({global:!0,wrap:!0,forced:!s,sham:!s},{Symbol:W}),D(w(tt),(function(t){F(t)})),r({target:"Symbol",stat:!0,forced:!s},{for:function(t){var n=String(t);if(l(Q,n))return Q[n];var e=W(n);return Q[n]=e,Z[e]=n,e},keyFor:function(t){if(!it(t))throw TypeError(t+" is not a symbol");if(l(Z,t))return Z[t]},useSetter:function(){et=!0},useSimple:function(){et=!1}}),r({target:"Object",stat:!0,forced:!s,sham:!u},{create:function(t,n){return void 0===n?b(t):ut(b(t),n)},defineProperty:at,defineProperties:ut,getOwnPropertyDescriptor:ct}),r({target:"Object",stat:!0,forced:!s},{getOwnPropertyNames:ft,getOwnPropertySymbols:lt}),r({target:"Object",stat:!0,forced:f((function(){S.f(1)}))},{getOwnPropertySymbols:function(t){return S.f(v(t))}}),H)&&r({target:"JSON",stat:!0,forced:!s||f((function(){var t=W();return"[null]"!=H([t])||"{}"!=H({a:t})||"{}"!=H(Object(t))}))},{stringify:function(t,n,e){for(var r,o=[t],i=1;arguments.length>i;)o.push(arguments[i++]);if(r=n,(h(n)||void 0!==t)&&!it(t))return p(n)||(n=function(t,n){if("function"==typeof r&&(n=r.call(this,t,n)),!it(n))return n}),o[1]=n,H.apply(null,o)}});W.prototype[q]||k(W.prototype,q,W.prototype.valueOf),N(W,"Symbol"),_[U]=!0},function(t,n){var e={}.hasOwnProperty;t.exports=function(t,n){return e.call(t,n)}},function(t,n,e){"use strict";var r=e(0),o=e(21).map,i=e(1),a=e(100)("map"),u=a&&!i((function(){[].map.call({length:-1,0:1},(function(t){throw t}))}));r({target:"Array",proto:!0,forced:!a||!u},{map:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(0),o=e(5),i=e(2),a=e(17),u=e(3),s=e(10).f,c=e(191),f=i.Symbol;if(o&&"function"==typeof f&&(!("description"in f.prototype)||void 0!==f().description)){var l={},p=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),n=this instanceof p?new f(t):void 0===t?f():f(t);return""===t&&(l[n]=!0),n};c(p,f);var h=p.prototype=f.prototype;h.constructor=p;var d=h.toString,v="Symbol(test)"==String(f("test")),g=/^Symbol\((.*)\)[^)]+$/;s(h,"description",{configurable:!0,get:function(){var t=u(this)?this.valueOf():this,n=d.call(t);if(a(l,t))return"";var e=v?n.slice(7,-1):n.replace(g,"$1");return""===e?void 0:e}}),r({global:!0,forced:!0},{Symbol:p})}},function(t,n,e){e(31)("iterator")},function(t,n,e){var r=e(58),o=e(86),i=e(14),a=e(8),u=e(93),s=[].push,c=function(t){var n=1==t,e=2==t,c=3==t,f=4==t,l=6==t,p=5==t||l;return function(h,d,v,g){for(var y,m,b=i(h),w=o(b),x=r(d,v,3),O=a(w.length),S=0,j=g||u,E=n?j(h,O):e?j(h,0):void 0;O>S;S++)if((p||S in w)&&(m=x(y=w[S],S,b),t))if(n)E[S]=m;else if(m)switch(t){case 3:return!0;case 5:return y;case 6:return S;case 2:s.call(E,y)}else if(f)return!1;return l?-1:c||f?f:E}};t.exports={forEach:c(0),map:c(1),filter:c(2),some:c(3),every:c(4),find:c(5),findIndex:c(6)}},function(t,n,e){"use strict";var r=e(0),o=e(206);r({target:"Array",proto:!0,forced:[].forEach!=o},{forEach:o})},function(t,n,e){var r=e(2),o=e(260),i=e(206),a=e(28);for(var u in o){var s=r[u],c=s&&s.prototype;if(c&&c.forEach!==i)try{a(c,"forEach",i)}catch(t){c.forEach=i}}},function(t,n,e){var r=e(5),o=e(105),i=e(56),a=e(34),u=e(46),s=e(17),c=e(188),f=Object.getOwnPropertyDescriptor;n.f=r?f:function(t,n){if(t=a(t),n=u(n,!0),c)try{return f(t,n)}catch(t){}if(s(t,n))return i(!o.f.call(t,n),t[n])}},function(t,n,e){var r=e(2),o=e(28),i=e(17),a=e(136),u=e(137),s=e(29),c=s.get,f=s.enforce,l=String(String).split("String");(t.exports=function(t,n,e,u){var s=!!u&&!!u.unsafe,c=!!u&&!!u.enumerable,p=!!u&&!!u.noTargetGet;"function"==typeof e&&("string"!=typeof n||i(e,"name")||o(e,"name",n),f(e).source=l.join("string"==typeof n?n:"")),t!==r?(s?!p&&t[n]&&(c=!0):delete t[n],c?t[n]=e:o(t,n,e)):c?t[n]=e:a(n,e)})(Function.prototype,"toString",(function(){return"function"==typeof this&&c(this).source||u(this)}))},function(t,n,e){"use strict";var r=e(25),o=e(4),i=e(1),a=e(102),u=RegExp.prototype,s=u.toString,c=i((function(){return"/a/b"!=s.call({source:"a",flags:"b"})})),f="toString"!=s.name;(c||f)&&r(RegExp.prototype,"toString",(function(){var t=o(this),n=String(t.source),e=t.flags;return"/"+n+"/"+String(void 0===e&&t instanceof RegExp&&!("flags"in u)?a.call(t):e)}),{unsafe:!0})},function(t,n){t.exports=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t}},function(t,n,e){var r=e(5),o=e(10),i=e(56);t.exports=r?function(t,n,e){return o.f(t,n,i(1,e))}:function(t,n,e){return t[n]=e,t}},function(t,n,e){var r,o,i,a=e(190),u=e(2),s=e(3),c=e(28),f=e(17),l=e(106),p=e(88),h=u.WeakMap;if(a){var d=new h,v=d.get,g=d.has,y=d.set;r=function(t,n){return y.call(d,t,n),n},o=function(t){return v.call(d,t)||{}},i=function(t){return g.call(d,t)}}else{var m=l("state");p[m]=!0,r=function(t,n){return c(t,m,n),n},o=function(t){return f(t,m)?t[m]:{}},i=function(t){return f(t,m)}}t.exports={set:r,get:o,has:i,enforce:function(t){return i(t)?o(t):r(t,{})},getterFor:function(t){return function(n){var e;if(!s(n)||(e=o(n)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return e}}}},function(t,n){t.exports=function(t){var n=typeof t;return null!=t&&("object"==n||"function"==n)}},function(t,n,e){var r=e(89),o=e(17),i=e(196),a=e(10).f;t.exports=function(t){var n=r.Symbol||(r.Symbol={});o(n,t)||a(n,t,{value:i.f(t)})}},function(t,n){t.exports=function(t){if("function"!=typeof t)throw TypeError(String(t)+" is not a function");return t}},function(t,n,e){var r=e(0),o=e(203);r({target:"Array",stat:!0,forced:!e(108)((function(t){Array.from(t)}))},{from:o})},function(t,n,e){var r=e(86),o=e(27);t.exports=function(t){return r(o(t))}},function(t,n,e){var r=e(0),o=e(1),i=e(34),a=e(24).f,u=e(5),s=o((function(){a(1)}));r({target:"Object",stat:!0,forced:!u||s,sham:!u},{getOwnPropertyDescriptor:function(t,n){return a(i(t),n)}})},function(t,n,e){var r=e(0),o=e(14),i=e(92);r({target:"Object",stat:!0,forced:e(1)((function(){i(1)}))},{keys:function(t){return i(o(t))}})},function(t,n,e){"use strict";var r=e(0),o=e(21).filter,i=e(1),a=e(100)("filter"),u=a&&!i((function(){[].filter.call({length:-1,0:1},(function(t){throw t}))}));r({target:"Array",proto:!0,forced:!a||!u},{filter:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){var r=e(27),o=/"/g;t.exports=function(t,n,e,i){var a=String(r(t)),u="<"+n;return""!==e&&(u+=" "+e+'="'+String(i).replace(o,""")+'"'),u+">"+a+"</"+n+">"}},function(t,n,e){var r=e(1);t.exports=function(t){return r((function(){var n=""[t]('"');return n!==n.toLowerCase()||n.split('"').length>3}))}},function(t,n,e){"use strict";var r,o,i,a,u=e(0),s=e(47),c=e(2),f=e(42),l=e(221),p=e(25),h=e(82),d=e(48),v=e(79),g=e(3),y=e(32),m=e(62),b=e(41),w=e(137),x=e(75),O=e(108),S=e(53),j=e(163).set,E=e(223),A=e(224),k=e(423),T=e(164),P=e(225),R=e(29),_=e(91),M=e(7),I=e(148),C=M("species"),F="Promise",N=R.get,L=R.set,D=R.getterFor(F),U=l,q=c.TypeError,B=c.document,z=c.process,V=f("fetch"),W=T.f,H=W,$="process"==b(z),G=!!(B&&B.createEvent&&c.dispatchEvent),Y=_(F,(function(){if(!(w(U)!==String(U))){if(66===I)return!0;if(!$&&"function"!=typeof PromiseRejectionEvent)return!0}if(s&&!U.prototype.finally)return!0;if(I>=51&&/native code/.test(U))return!1;var t=U.resolve(1),n=function(t){t((function(){}),(function(){}))};return(t.constructor={})[C]=n,!(t.then((function(){}))instanceof n)})),J=Y||!O((function(t){U.all(t).catch((function(){}))})),K=function(t){var n;return!(!g(t)||"function"!=typeof(n=t.then))&&n},X=function(t,n,e){if(!n.notified){n.notified=!0;var r=n.reactions;E((function(){for(var o=n.value,i=1==n.state,a=0;r.length>a;){var u,s,c,f=r[a++],l=i?f.ok:f.fail,p=f.resolve,h=f.reject,d=f.domain;try{l?(i||(2===n.rejection&&nt(t,n),n.rejection=1),!0===l?u=o:(d&&d.enter(),u=l(o),d&&(d.exit(),c=!0)),u===f.promise?h(q("Promise-chain cycle")):(s=K(u))?s.call(u,p,h):p(u)):h(o)}catch(t){d&&!c&&d.exit(),h(t)}}n.reactions=[],n.notified=!1,e&&!n.rejection&&Z(t,n)}))}},Q=function(t,n,e){var r,o;G?((r=B.createEvent("Event")).promise=n,r.reason=e,r.initEvent(t,!1,!0),c.dispatchEvent(r)):r={promise:n,reason:e},(o=c["on"+t])?o(r):"unhandledrejection"===t&&k("Unhandled promise rejection",e)},Z=function(t,n){j.call(c,(function(){var e,r=n.value;if(tt(n)&&(e=P((function(){$?z.emit("unhandledRejection",r,t):Q("unhandledrejection",t,r)})),n.rejection=$||tt(n)?2:1,e.error))throw e.value}))},tt=function(t){return 1!==t.rejection&&!t.parent},nt=function(t,n){j.call(c,(function(){$?z.emit("rejectionHandled",t):Q("rejectionhandled",t,n.value)}))},et=function(t,n,e,r){return function(o){t(n,e,o,r)}},rt=function(t,n,e,r){n.done||(n.done=!0,r&&(n=r),n.value=e,n.state=2,X(t,n,!0))},ot=function(t,n,e,r){if(!n.done){n.done=!0,r&&(n=r);try{if(t===e)throw q("Promise can't be resolved itself");var o=K(e);o?E((function(){var r={done:!1};try{o.call(e,et(ot,t,r,n),et(rt,t,r,n))}catch(e){rt(t,r,e,n)}})):(n.value=e,n.state=1,X(t,n,!1))}catch(e){rt(t,{done:!1},e,n)}}};Y&&(U=function(t){m(this,U,F),y(t),r.call(this);var n=N(this);try{t(et(ot,this,n),et(rt,this,n))}catch(t){rt(this,n,t)}},(r=function(t){L(this,{type:F,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=h(U.prototype,{then:function(t,n){var e=D(this),r=W(S(this,U));return r.ok="function"!=typeof t||t,r.fail="function"==typeof n&&n,r.domain=$?z.domain:void 0,e.parent=!0,e.reactions.push(r),0!=e.state&&X(this,e,!1),r.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new r,n=N(t);this.promise=t,this.resolve=et(ot,t,n),this.reject=et(rt,t,n)},T.f=W=function(t){return t===U||t===i?new o(t):H(t)},s||"function"!=typeof l||(a=l.prototype.then,p(l.prototype,"then",(function(t,n){var e=this;return new U((function(t,n){a.call(e,t,n)})).then(t,n)}),{unsafe:!0}),"function"==typeof V&&u({global:!0,enumerable:!0,forced:!0},{fetch:function(t){return A(U,V.apply(c,arguments))}}))),u({global:!0,wrap:!0,forced:Y},{Promise:U}),d(U,F,!1,!0),v(F),i=f(F),u({target:F,stat:!0,forced:Y},{reject:function(t){var n=W(this);return n.reject.call(void 0,t),n.promise}}),u({target:F,stat:!0,forced:s||Y},{resolve:function(t){return A(s&&this===i?U:this,t)}}),u({target:F,stat:!0,forced:J},{all:function(t){var n=this,e=W(n),r=e.resolve,o=e.reject,i=P((function(){var e=y(n.resolve),i=[],a=0,u=1;x(t,(function(t){var s=a++,c=!1;i.push(void 0),u++,e.call(n,t).then((function(t){c||(c=!0,i[s]=t,--u||r(i))}),o)})),--u||r(i)}));return i.error&&o(i.value),e.promise},race:function(t){var n=this,e=W(n),r=e.reject,o=P((function(){var o=y(n.resolve);x(t,(function(t){o.call(n,t).then(e.resolve,r)}))}));return o.error&&r(o.value),e.promise}})},function(t,n){var e={}.toString;t.exports=function(t){return e.call(t).slice(8,-1)}},function(t,n,e){var r=e(89),o=e(2),i=function(t){return"function"==typeof t?t:void 0};t.exports=function(t,n){return arguments.length<2?i(r[t])||i(o[t]):r[t]&&r[t][n]||o[t]&&o[t][n]}},function(t,n){var e=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:e)(t)}},function(t,n,e){"use strict";var r=e(0),o=e(114);r({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},function(t,n){var e=Array.isArray;t.exports=e},function(t,n,e){var r=e(3);t.exports=function(t,n){if(!r(t))return t;var e,o;if(n&&"function"==typeof(e=t.toString)&&!r(o=e.call(t)))return o;if("function"==typeof(e=t.valueOf)&&!r(o=e.call(t)))return o;if(!n&&"function"==typeof(e=t.toString)&&!r(o=e.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,n){t.exports=!1},function(t,n,e){var r=e(10).f,o=e(17),i=e(7)("toStringTag");t.exports=function(t,n,e){t&&!o(t=e?t:t.prototype,i)&&r(t,i,{configurable:!0,value:n})}},function(t,n,e){var r=e(0),o=e(1),i=e(14),a=e(50),u=e(147);r({target:"Object",stat:!0,forced:o((function(){a(1)})),sham:!u},{getPrototypeOf:function(t){return a(i(t))}})},function(t,n,e){var r=e(17),o=e(14),i=e(106),a=e(147),u=i("IE_PROTO"),s=Object.prototype;t.exports=a?Object.getPrototypeOf:function(t){return t=o(t),r(t,u)?t[u]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?s:null}},function(t,n,e){var r,o=e(4),i=e(143),a=e(140),u=e(88),s=e(194),c=e(135),f=e(106),l=f("IE_PROTO"),p=function(){},h=function(t){return"<script>"+t+"<\/script>"},d=function(){try{r=document.domain&&new ActiveXObject("htmlfile")}catch(t){}d=r?function(t){t.write(h("")),t.close();var n=t.parentWindow.Object;return t=null,n}(r):function(){var t,n=c("iframe");return n.style.display="none",s.appendChild(n),n.src=String("javascript:"),(t=n.contentWindow.document).open(),t.write(h("document.F=Object")),t.close(),t.F}();for(var t=a.length;t--;)delete d.prototype[a[t]];return d()};u[l]=!0,t.exports=Object.create||function(t,n){var e;return null!==t?(p.prototype=o(t),e=new p,p.prototype=null,e[l]=t):e=d(),void 0===n?e:i(e,n)}},function(t,n,e){"use strict";var r=e(1);t.exports=function(t,n){var e=[][t];return!e||!r((function(){e.call(null,n||function(){throw 1},1)}))}},function(t,n,e){var r=e(4),o=e(32),i=e(7)("species");t.exports=function(t,n){var e,a=r(t).constructor;return void 0===a||null==(e=r(a)[i])?n:o(e)}},function(t,n,e){"use strict";var r=e(0),o=e(2),i=e(5),a=e(165),u=e(6),s=e(122),c=e(62),f=e(56),l=e(28),p=e(8),h=e(232),d=e(234),v=e(46),g=e(17),y=e(98),m=e(3),b=e(51),w=e(76),x=e(64).f,O=e(235),S=e(21).forEach,j=e(79),E=e(10),A=e(24),k=e(29),T=e(119),P=k.get,R=k.set,_=E.f,M=A.f,I=Math.round,C=o.RangeError,F=s.ArrayBuffer,N=s.DataView,L=u.NATIVE_ARRAY_BUFFER_VIEWS,D=u.TYPED_ARRAY_TAG,U=u.TypedArray,q=u.TypedArrayPrototype,B=u.aTypedArrayConstructor,z=u.isTypedArray,V=function(t,n){for(var e=0,r=n.length,o=new(B(t))(r);r>e;)o[e]=n[e++];return o},W=function(t,n){_(t,n,{get:function(){return P(this)[n]}})},H=function(t){var n;return t instanceof F||"ArrayBuffer"==(n=y(t))||"SharedArrayBuffer"==n},$=function(t,n){return z(t)&&"symbol"!=typeof n&&n in t&&String(+n)==String(n)},G=function(t,n){return $(t,n=v(n,!0))?f(2,t[n]):M(t,n)},Y=function(t,n,e){return!($(t,n=v(n,!0))&&m(e)&&g(e,"value"))||g(e,"get")||g(e,"set")||e.configurable||g(e,"writable")&&!e.writable||g(e,"enumerable")&&!e.enumerable?_(t,n,e):(t[n]=e.value,t)};i?(L||(A.f=G,E.f=Y,W(q,"buffer"),W(q,"byteOffset"),W(q,"byteLength"),W(q,"length")),r({target:"Object",stat:!0,forced:!L},{getOwnPropertyDescriptor:G,defineProperty:Y}),t.exports=function(t,n,e){var i=t.match(/\d+$/)[0]/8,u=t+(e?"Clamped":"")+"Array",s="get"+t,f="set"+t,v=o[u],g=v,y=g&&g.prototype,E={},A=function(t,n){_(t,n,{get:function(){return function(t,n){var e=P(t);return e.view[s](n*i+e.byteOffset,!0)}(this,n)},set:function(t){return function(t,n,r){var o=P(t);e&&(r=(r=I(r))<0?0:r>255?255:255&r),o.view[f](n*i+o.byteOffset,r,!0)}(this,n,t)},enumerable:!0})};L?a&&(g=n((function(t,n,e,r){return c(t,g,u),T(function(){return m(n)?H(n)?void 0!==r?new v(n,d(e,i),r):void 0!==e?new v(n,d(e,i)):new v(n):z(n)?V(g,n):O.call(g,n):new v(h(n))}(),t,g)})),w&&w(g,U),S(x(v),(function(t){t in g||l(g,t,v[t])})),g.prototype=y):(g=n((function(t,n,e,r){c(t,g,u);var o,a,s,f=0,l=0;if(m(n)){if(!H(n))return z(n)?V(g,n):O.call(g,n);o=n,l=d(e,i);var v=n.byteLength;if(void 0===r){if(v%i)throw C("Wrong length");if((a=v-l)<0)throw C("Wrong length")}else if((a=p(r)*i)+l>v)throw C("Wrong length");s=a/i}else s=h(n),o=new F(a=s*i);for(R(t,{buffer:o,byteOffset:l,byteLength:a,length:s,view:new N(o)});f<s;)A(t,f++)})),w&&w(g,U),y=g.prototype=b(q)),y.constructor!==g&&l(y,"constructor",g),D&&l(y,D,u),E[u]=g,r({global:!0,forced:g!=v,sham:!L},E),"BYTES_PER_ELEMENT"in g||l(g,"BYTES_PER_ELEMENT",i),"BYTES_PER_ELEMENT"in y||l(y,"BYTES_PER_ELEMENT",i),j(u)}):t.exports=function(){}},function(t,n,e){var r=e(520)();t.exports=r},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n,e){var r=e(43),o=Math.max,i=Math.min;t.exports=function(t,n){var e=r(t);return e<0?o(e+n,0):i(e,n)}},function(t,n,e){var r=e(32);t.exports=function(t,n,e){if(r(t),void 0===n)return t;switch(e){case 0:return function(){return t.call(n)};case 1:return function(e){return t.call(n,e)};case 2:return function(e,r){return t.call(n,e,r)};case 3:return function(e,r,o){return t.call(n,e,r,o)}}return function(){return t.apply(n,arguments)}}},function(t,n,e){e(0)({target:"Object",stat:!0},{setPrototypeOf:e(76)})},function(t,n,e){var r=e(7),o=e(51),i=e(10),a=r("unscopables"),u=Array.prototype;null==u[a]&&i.f(u,a,{configurable:!0,value:o(null)}),t.exports=function(t){u[a][t]=!0}},function(t,n,e){"use strict";var r=e(0),o=e(110).left;r({target:"Array",proto:!0,forced:e(52)("reduce")},{reduce:function(t){return o(this,t,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(t,n){t.exports=function(t,n,e){if(!(t instanceof n))throw TypeError("Incorrect "+(e?e+" ":"")+"invocation");return t}},function(t,n,e){var r=e(129),o=e(30);t.exports=function(t){if(!o(t))return!1;var n=r(t);return"[object Function]"==n||"[object GeneratorFunction]"==n||"[object AsyncFunction]"==n||"[object Proxy]"==n}},function(t,n,e){var r=e(192),o=e(140).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(t){return r(t,o)}},function(t,n,e){var r=e(41);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,n,e){var r=e(88),o=e(3),i=e(17),a=e(10).f,u=e(87),s=e(95),c=u("meta"),f=0,l=Object.isExtensible||function(){return!0},p=function(t){a(t,c,{value:{objectID:"O"+ ++f,weakData:{}}})},h=t.exports={REQUIRED:!1,fastKey:function(t,n){if(!o(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!i(t,c)){if(!l(t))return"F";if(!n)return"E";p(t)}return t[c].objectID},getWeakData:function(t,n){if(!i(t,c)){if(!l(t))return!0;if(!n)return!1;p(t)}return t[c].weakData},onFreeze:function(t){return s&&h.REQUIRED&&l(t)&&!i(t,c)&&p(t),t}};r[c]=!0},function(t,n,e){"use strict";var r=e(46),o=e(10),i=e(56);t.exports=function(t,n,e){var a=r(n);a in t?o.f(t,a,i(0,e)):t[a]=e}},function(t,n,e){"use strict";var r=e(0),o=e(3),i=e(65),a=e(57),u=e(8),s=e(34),c=e(67),f=e(100),l=e(7)("species"),p=[].slice,h=Math.max;r({target:"Array",proto:!0,forced:!f("slice")},{slice:function(t,n){var e,r,f,d=s(this),v=u(d.length),g=a(t,v),y=a(void 0===n?v:n,v);if(i(d)&&("function"!=typeof(e=d.constructor)||e!==Array&&!i(e.prototype)?o(e)&&null===(e=e[l])&&(e=void 0):e=void 0,e===Array||void 0===e))return p.call(d,g,y);for(r=new(void 0===e?Array:e)(h(y-g,0)),f=0;g<y;g++,f++)g in d&&c(r,f,d[g]);return r.length=f,r}})},function(t,n,e){"use strict";var r=e(113),o=e(112),i=e(4),a=e(27),u=e(53),s=e(116),c=e(8),f=e(117),l=e(114),p=e(1),h=[].push,d=Math.min,v=!p((function(){return!RegExp(4294967295,"y")}));r("split",2,(function(t,n,e){var r;return r="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,e){var r=String(a(this)),i=void 0===e?4294967295:e>>>0;if(0===i)return[];if(void 0===t)return[r];if(!o(t))return n.call(r,t,i);for(var u,s,c,f=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),d=0,v=new RegExp(t.source,p+"g");(u=l.call(v,r))&&!((s=v.lastIndex)>d&&(f.push(r.slice(d,u.index)),u.length>1&&u.index<r.length&&h.apply(f,u.slice(1)),c=u[0].length,d=s,f.length>=i));)v.lastIndex===u.index&&v.lastIndex++;return d===r.length?!c&&v.test("")||f.push(""):f.push(r.slice(d)),f.length>i?f.slice(0,i):f}:"0".split(void 0,0).length?function(t,e){return void 0===t&&0===e?[]:n.call(this,t,e)}:n,[function(n,e){var o=a(this),i=null==n?void 0:n[t];return void 0!==i?i.call(n,o,e):r.call(String(o),n,e)},function(t,o){var a=e(r,t,this,o,r!==n);if(a.done)return a.value;var l=i(t),p=String(this),h=u(l,RegExp),g=l.unicode,y=(l.ignoreCase?"i":"")+(l.multiline?"m":"")+(l.unicode?"u":"")+(v?"y":"g"),m=new h(v?l:"^(?:"+l.source+")",y),b=void 0===o?4294967295:o>>>0;if(0===b)return[];if(0===p.length)return null===f(m,p)?[p]:[];for(var w=0,x=0,O=[];x<p.length;){m.lastIndex=v?x:0;var S,j=f(m,v?p:p.slice(x));if(null===j||(S=d(c(m.lastIndex+(v?0:x)),p.length))===w)x=s(p,x,g);else{if(O.push(p.slice(w,x)),O.length===b)return O;for(var E=1;E<=j.length-1;E++)if(O.push(j[E]),O.length===b)return O;x=w=S}}return O.push(p.slice(w)),O}]}),!v)},function(t,n,e){var r=e(170),o=e(171);t.exports=function(t,n,e,i){var a=!e;e||(e={});for(var u=-1,s=n.length;++u<s;){var c=n[u],f=i?i(e[c],t[c],c,e,t):void 0;void 0===f&&(f=t[c]),a?o(e,c,f):r(e,c,f)}return e}},function(t,n){t.exports=function(t,n){for(var e=-1,r=null==t?0:t.length,o=Array(r);++e<r;)o[e]=n(t[e],e,t);return o}},function(t,n,e){var r=e(129),o=e(269),i=e(130),a=Function.prototype,u=Object.prototype,s=a.toString,c=u.hasOwnProperty,f=s.call(Object);t.exports=function(t){if(!i(t)||"[object Object]"!=r(t))return!1;var n=o(t);if(null===n)return!0;var e=c.call(n,"constructor")&&n.constructor;return"function"==typeof e&&e instanceof e&&s.call(e)==f}},function(t,n){t.exports=function(t){for(var n=-1,e=null==t?0:t.length,r={};++n<e;){var o=t[n];r[o[0]]=o[1]}return r}},function(t,n,e){var r=e(0),o=e(197);r({target:"Object",stat:!0,forced:Object.assign!==o},{assign:o})},function(t,n,e){var r=e(4),o=e(145),i=e(8),a=e(58),u=e(97),s=e(199),c=function(t,n){this.stopped=t,this.result=n};(t.exports=function(t,n,e,f,l){var p,h,d,v,g,y,m,b=a(n,e,f?2:1);if(l)p=t;else{if("function"!=typeof(h=u(t)))throw TypeError("Target is not iterable");if(o(h)){for(d=0,v=i(t.length);v>d;d++)if((g=f?b(r(m=t[d])[0],m[1]):b(t[d]))&&g instanceof c)return g;return new c(!1)}p=h.call(t)}for(y=p.next;!(m=y.call(p)).done;)if("object"==typeof(g=s(p,b,m.value,f))&&g&&g instanceof c)return g;return new c(!1)}).stop=function(t){return new c(!0,t)}},function(t,n,e){var r=e(4),o=e(201);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,n=!1,e={};try{(t=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),n=e instanceof Array}catch(t){}return function(e,i){return r(e),o(i),n?t.call(e,i):e.__proto__=i,e}}():void 0)},function(t,n,e){"use strict";var r=e(0),o=e(90).includes,i=e(60);r({target:"Array",proto:!0},{includes:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("includes")},function(t,n,e){"use strict";var r=e(0),o=e(86),i=e(34),a=e(52),u=[].join,s=o!=Object,c=a("join",",");r({target:"Array",proto:!0,forced:s||c},{join:function(t){return u.call(i(this),void 0===t?",":t)}})},function(t,n,e){"use strict";var r=e(42),o=e(10),i=e(7),a=e(5),u=i("species");t.exports=function(t){var n=r(t),e=o.f;a&&n&&!n[u]&&e(n,u,{configurable:!0,get:function(){return this}})}},function(t,n,e){"use strict";var r=e(113),o=e(4),i=e(14),a=e(8),u=e(43),s=e(27),c=e(116),f=e(117),l=Math.max,p=Math.min,h=Math.floor,d=/\$([$&'`]|\d\d?|<[^>]*>)/g,v=/\$([$&'`]|\d\d?)/g,g=function(t){return void 0===t?t:String(t)};r("replace",2,(function(t,n,e,r){return[function(e,r){var o=s(this),i=null==e?void 0:e[t];return void 0!==i?i.call(e,o,r):n.call(String(o),e,r)},function(t,i){if(r.REPLACE_KEEPS_$0||"string"==typeof i&&-1===i.indexOf("$0")){var s=e(n,t,this,i);if(s.done)return s.value}var h=o(t),d=String(this),v="function"==typeof i;v||(i=String(i));var m=h.global;if(m){var b=h.unicode;h.lastIndex=0}for(var w=[];;){var x=f(h,d);if(null===x)break;if(w.push(x),!m)break;""===String(x[0])&&(h.lastIndex=c(d,a(h.lastIndex),b))}for(var O="",S=0,j=0;j<w.length;j++){x=w[j];for(var E=String(x[0]),A=l(p(u(x.index),d.length),0),k=[],T=1;T<x.length;T++)k.push(g(x[T]));var P=x.groups;if(v){var R=[E].concat(k,A,d);void 0!==P&&R.push(P);var _=String(i.apply(void 0,R))}else _=y(E,d,A,k,P,i);A>=S&&(O+=d.slice(S,A)+_,S=A+E.length)}return O+d.slice(S)}];function y(t,e,r,o,a,u){var s=r+t.length,c=o.length,f=v;return void 0!==a&&(a=i(a),f=d),n.call(u,f,(function(n,i){var u;switch(i.charAt(0)){case"$":return"$";case"&":return t;case"`":return e.slice(0,r);case"'":return e.slice(s);case"<":u=a[i.slice(1,-1)];break;default:var f=+i;if(0===f)return n;if(f>c){var l=h(f/10);return 0===l?n:l<=c?void 0===o[l-1]?i.charAt(1):o[l-1]+i.charAt(1):n}u=o[f-1]}return void 0===u?"":u}))}}))},function(t,n,e){var r=e(27),o="["+e(118)+"]",i=RegExp("^"+o+o+"*"),a=RegExp(o+o+"*$"),u=function(t){return function(n){var e=String(r(n));return 1&t&&(e=e.replace(i,"")),2&t&&(e=e.replace(a,"")),e}};t.exports={start:u(1),end:u(2),trim:u(3)}},function(t,n,e){var r=e(25);t.exports=function(t,n,e){for(var o in n)r(t,o,n[o],e);return t}},function(t,n,e){var r=e(45),o=e(483),i=e(484),a=e(176);t.exports=function(t,n){return r(t)?t:o(t,n)?[t]:i(a(t))}},function(t,n,e){var r=e(184),o=e(277),i=e(279);t.exports=function(t,n){return i(o(t,n,r),t+"")}},function(t,n,e){var r=e(169);t.exports=function(t){return r(t,5)}},function(t,n,e){var r=e(1),o=e(41),i="".split;t.exports=r((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?i.call(t,""):Object(t)}:Object},function(t,n){var e=0,r=Math.random();t.exports=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++e+r).toString(36)}},function(t,n){t.exports={}},function(t,n,e){var r=e(2);t.exports=r},function(t,n,e){var r=e(34),o=e(8),i=e(57),a=function(t){return function(n,e,a){var u,s=r(n),c=o(s.length),f=i(a,c);if(t&&e!=e){for(;c>f;)if((u=s[f++])!=u)return!0}else for(;c>f;f++)if((t||f in s)&&s[f]===e)return t||f||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},function(t,n,e){var r=e(1),o=/#|\.prototype\./,i=function(t,n){var e=u[a(t)];return e==c||e!=s&&("function"==typeof n?r(n):!!n)},a=i.normalize=function(t){return String(t).replace(o,".").toLowerCase()},u=i.data={},s=i.NATIVE="N",c=i.POLYFILL="P";t.exports=i},function(t,n,e){var r=e(192),o=e(140);t.exports=Object.keys||function(t){return r(t,o)}},function(t,n,e){var r=e(3),o=e(65),i=e(7)("species");t.exports=function(t,n){var e;return o(t)&&("function"!=typeof(e=t.constructor)||e!==Array&&!o(e.prototype)?r(e)&&null===(e=e[i])&&(e=void 0):e=void 0),new(void 0===e?Array:e)(0===n?0:n)}},function(t,n,e){var r=e(0),o=e(198).entries;r({target:"Object",stat:!0},{entries:function(t){return o(t)}})},function(t,n,e){var r=e(1);t.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},function(t,n){t.exports={}},function(t,n,e){var r=e(98),o=e(96),i=e(7)("iterator");t.exports=function(t){if(null!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,n,e){var r=e(146),o=e(41),i=e(7)("toStringTag"),a="Arguments"==o(function(){return arguments}());t.exports=r?o:function(t){var n,e,r;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(e=function(t,n){try{return t[n]}catch(t){}}(n=Object(t),i))?e:a?o(n):"Object"==(r=o(n))&&"function"==typeof n.callee?"Arguments":r}},function(t,n,e){var r=e(5),o=e(10).f,i=Function.prototype,a=i.toString,u=/^\s*function ([^ (]*)/;!r||"name"in i||o(i,"name",{configurable:!0,get:function(){try{return a.call(this).match(u)[1]}catch(t){return""}}})},function(t,n,e){var r=e(1),o=e(7),i=e(148),a=o("species");t.exports=function(t){return i>=51||!r((function(){var n=[];return(n.constructor={})[a]=function(){return{foo:1}},1!==n[t](Boolean).foo}))}},function(t,n,e){"use strict";var r=e(0),o=e(154),i=e(27);r({target:"String",proto:!0,forced:!e(155)("includes")},{includes:function(t){return!!~String(i(this)).indexOf(o(t),arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(4);t.exports=function(){var t=r(this),n="";return t.global&&(n+="g"),t.ignoreCase&&(n+="i"),t.multiline&&(n+="m"),t.dotAll&&(n+="s"),t.unicode&&(n+="u"),t.sticky&&(n+="y"),n}},function(t,n,e){var r=e(0),o=e(3),i=e(4),a=e(17),u=e(24),s=e(50);r({target:"Reflect",stat:!0},{get:function t(n,e){var r,c,f=arguments.length<3?n:arguments[2];return i(n)===f?n[e]:(r=u.f(n,e))?a(r,"value")?r.value:void 0===r.get?void 0:r.get.call(f):o(c=s(n))?t(c,e,f):void 0}})},function(t,n,e){var r=e(178);t.exports=function(t){return(null==t?0:t.length)?r(t,1):[]}},function(t,n,e){"use strict";var r={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i=o&&!r.call({1:2},1);n.f=i?function(t){var n=o(this,t);return!!n&&n.enumerable}:r},function(t,n,e){var r=e(138),o=e(87),i=r("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},function(t,n,e){"use strict";var r=e(47),o=e(2),i=e(1);t.exports=r||!i((function(){var t=Math.random();__defineSetter__.call(null,t,(function(){})),delete o[t]}))},function(t,n,e){var r=e(7)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[r]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,n){if(!n&&!o)return!1;var e=!1;try{var i={};i[r]=function(){return{next:function(){return{done:e=!0}}}},t(i)}catch(t){}return e}},function(t,n,e){var r=e(42);t.exports=r("navigator","userAgent")||""},function(t,n,e){var r=e(32),o=e(14),i=e(86),a=e(8),u=function(t){return function(n,e,u,s){r(e);var c=o(n),f=i(c),l=a(c.length),p=t?l-1:0,h=t?-1:1;if(u<2)for(;;){if(p in f){s=f[p],p+=h;break}if(p+=h,t?p<0:l<=p)throw TypeError("Reduce of empty array with no initial value")}for(;t?p>=0:l>p;p+=h)p in f&&(s=e(s,f[p],p,c));return s}};t.exports={left:u(!1),right:u(!0)}},function(t,n,e){var r=e(43),o=e(27),i=function(t){return function(n,e){var i,a,u=String(o(n)),s=r(e),c=u.length;return s<0||s>=c?t?"":void 0:(i=u.charCodeAt(s))<55296||i>56319||s+1===c||(a=u.charCodeAt(s+1))<56320||a>57343?t?u.charAt(s):i:t?u.slice(s,s+2):a-56320+(i-55296<<10)+65536}};t.exports={codeAt:i(!1),charAt:i(!0)}},function(t,n,e){var r=e(3),o=e(41),i=e(7)("match");t.exports=function(t){var n;return r(t)&&(void 0!==(n=t[i])?!!n:"RegExp"==o(t))}},function(t,n,e){"use strict";var r=e(25),o=e(1),i=e(7),a=e(114),u=e(28),s=i("species"),c=!o((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")})),f=function(){return"$0"==="a".replace(/./,"$0")}(),l=!o((function(){var t=/(?:)/,n=t.exec;t.exec=function(){return n.apply(this,arguments)};var e="ab".split(t);return 2!==e.length||"a"!==e[0]||"b"!==e[1]}));t.exports=function(t,n,e,p){var h=i(t),d=!o((function(){var n={};return n[h]=function(){return 7},7!=""[t](n)})),v=d&&!o((function(){var n=!1,e=/a/;return"split"===t&&((e={}).constructor={},e.constructor[s]=function(){return e},e.flags="",e[h]=/./[h]),e.exec=function(){return n=!0,null},e[h](""),!n}));if(!d||!v||"replace"===t&&(!c||!f)||"split"===t&&!l){var g=/./[h],y=e(h,""[t],(function(t,n,e,r,o){return n.exec===a?d&&!o?{done:!0,value:g.call(n,e,r)}:{done:!0,value:t.call(e,n,r)}:{done:!1}}),{REPLACE_KEEPS_$0:f}),m=y[0],b=y[1];r(String.prototype,t,m),r(RegExp.prototype,h,2==n?function(t,n){return b.call(t,this,n)}:function(t){return b.call(t,this)})}p&&u(RegExp.prototype[h],"sham",!0)}},function(t,n,e){"use strict";var r=e(102),o=e(115),i=RegExp.prototype.exec,a=String.prototype.replace,u=i,s=function(){var t=/a/,n=/b*/g;return i.call(t,"a"),i.call(n,"a"),0!==t.lastIndex||0!==n.lastIndex}(),c=o.UNSUPPORTED_Y||o.BROKEN_CARET,f=void 0!==/()??/.exec("")[1];(s||f||c)&&(u=function(t){var n,e,o,u,l=this,p=c&&l.sticky,h=r.call(l),d=l.source,v=0,g=t;return p&&(-1===(h=h.replace("y","")).indexOf("g")&&(h+="g"),g=String(t).slice(l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&"\n"!==t[l.lastIndex-1])&&(d="(?: "+d+")",g=" "+g,v++),e=new RegExp("^(?:"+d+")",h)),f&&(e=new RegExp("^"+d+"$(?!\\s)",h)),s&&(n=l.lastIndex),o=i.call(p?e:l,g),p?o?(o.input=o.input.slice(v),o[0]=o[0].slice(v),o.index=l.lastIndex,l.lastIndex+=o[0].length):l.lastIndex=0:s&&o&&(l.lastIndex=l.global?o.index+o[0].length:n),f&&o&&o.length>1&&a.call(o[0],e,(function(){for(u=1;u<arguments.length-2;u++)void 0===arguments[u]&&(o[u]=void 0)})),o}),t.exports=u},function(t,n,e){"use strict";var r=e(1);function o(t,n){return RegExp(t,n)}n.UNSUPPORTED_Y=r((function(){var t=o("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),n.BROKEN_CARET=r((function(){var t=o("^r","gy");return t.lastIndex=2,null!=t.exec("str")}))},function(t,n,e){"use strict";var r=e(111).charAt;t.exports=function(t,n,e){return n+(e?r(t,n).length:1)}},function(t,n,e){var r=e(41),o=e(114);t.exports=function(t,n){var e=t.exec;if("function"==typeof e){var i=e.call(t,n);if("object"!=typeof i)throw TypeError("RegExp exec method returned something other than an Object or null");return i}if("RegExp"!==r(t))throw TypeError("RegExp#exec called on incompatible receiver");return o.call(t,n)}},function(t,n){t.exports="\t\n\v\f\r \u2028\u2029\ufeff"},function(t,n,e){var r=e(3),o=e(76);t.exports=function(t,n,e){var i,a;return o&&"function"==typeof(i=n.constructor)&&i!==e&&r(a=i.prototype)&&a!==e.prototype&&o(t,a),t}},function(t,n){var e=Math.expm1,r=Math.exp;t.exports=!e||e(10)>22025.465794806718||e(10)<22025.465794806718||-2e-17!=e(-2e-17)?function(t){return 0==(t=+t)?t:t>-1e-6&&t<1e-6?t+t*t/2:r(t)-1}:e},function(t,n,e){"use strict";var r=e(0),o=e(2),i=e(91),a=e(25),u=e(66),s=e(75),c=e(62),f=e(3),l=e(1),p=e(108),h=e(48),d=e(119);t.exports=function(t,n,e){var v=-1!==t.indexOf("Map"),g=-1!==t.indexOf("Weak"),y=v?"set":"add",m=o[t],b=m&&m.prototype,w=m,x={},O=function(t){var n=b[t];a(b,t,"add"==t?function(t){return n.call(this,0===t?0:t),this}:"delete"==t?function(t){return!(g&&!f(t))&&n.call(this,0===t?0:t)}:"get"==t?function(t){return g&&!f(t)?void 0:n.call(this,0===t?0:t)}:"has"==t?function(t){return!(g&&!f(t))&&n.call(this,0===t?0:t)}:function(t,e){return n.call(this,0===t?0:t,e),this})};if(i(t,"function"!=typeof m||!(g||b.forEach&&!l((function(){(new m).entries().next()})))))w=e.getConstructor(n,t,v,y),u.REQUIRED=!0;else if(i(t,!0)){var S=new w,j=S[y](g?{}:-0,1)!=S,E=l((function(){S.has(1)})),A=p((function(t){new m(t)})),k=!g&&l((function(){for(var t=new m,n=5;n--;)t[y](n,n);return!t.has(-0)}));A||((w=n((function(n,e){c(n,w,t);var r=d(new m,n,w);return null!=e&&s(e,r[y],r,v),r}))).prototype=b,b.constructor=w),(E||k)&&(O("delete"),O("has"),v&&O("get")),(k||j)&&O(y),g&&b.clear&&delete b.clear}return x[t]=w,r({global:!0,forced:w!=m},x),h(w,t),g||e.setStrong(w,t,v),w}},function(t,n,e){"use strict";var r=e(2),o=e(5),i=e(6).NATIVE_ARRAY_BUFFER,a=e(28),u=e(82),s=e(1),c=e(62),f=e(43),l=e(8),p=e(232),h=e(427),d=e(64).f,v=e(10).f,g=e(151),y=e(48),m=e(29),b=m.get,w=m.set,x=r.ArrayBuffer,O=x,S=r.DataView,j=r.RangeError,E=h.pack,A=h.unpack,k=function(t){return[255&t]},T=function(t){return[255&t,t>>8&255]},P=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},R=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},_=function(t){return E(t,23,4)},M=function(t){return E(t,52,8)},I=function(t,n){v(t.prototype,n,{get:function(){return b(this)[n]}})},C=function(t,n,e,r){var o=p(e),i=b(t);if(o+n>i.byteLength)throw j("Wrong index");var a=b(i.buffer).bytes,u=o+i.byteOffset,s=a.slice(u,u+n);return r?s:s.reverse()},F=function(t,n,e,r,o,i){var a=p(e),u=b(t);if(a+n>u.byteLength)throw j("Wrong index");for(var s=b(u.buffer).bytes,c=a+u.byteOffset,f=r(+o),l=0;l<n;l++)s[c+l]=f[i?l:n-l-1]};if(i){if(!s((function(){x(1)}))||!s((function(){new x(-1)}))||s((function(){return new x,new x(1.5),new x(NaN),"ArrayBuffer"!=x.name}))){for(var N,L=(O=function(t){return c(this,O),new x(p(t))}).prototype=x.prototype,D=d(x),U=0;D.length>U;)(N=D[U++])in O||a(O,N,x[N]);L.constructor=O}var q=new S(new O(2)),B=S.prototype.setInt8;q.setInt8(0,2147483648),q.setInt8(1,2147483649),!q.getInt8(0)&&q.getInt8(1)||u(S.prototype,{setInt8:function(t,n){B.call(this,t,n<<24>>24)},setUint8:function(t,n){B.call(this,t,n<<24>>24)}},{unsafe:!0})}else O=function(t){c(this,O,"ArrayBuffer");var n=p(t);w(this,{bytes:g.call(new Array(n),0),byteLength:n}),o||(this.byteLength=n)},S=function(t,n,e){c(this,S,"DataView"),c(t,O,"DataView");var r=b(t).byteLength,i=f(n);if(i<0||i>r)throw j("Wrong offset");if(i+(e=void 0===e?r-i:l(e))>r)throw j("Wrong length");w(this,{buffer:t,byteLength:e,byteOffset:i}),o||(this.buffer=t,this.byteLength=e,this.byteOffset=i)},o&&(I(O,"byteLength"),I(S,"buffer"),I(S,"byteLength"),I(S,"byteOffset")),u(S.prototype,{getInt8:function(t){return C(this,1,t)[0]<<24>>24},getUint8:function(t){return C(this,1,t)[0]},getInt16:function(t){var n=C(this,2,t,arguments.length>1?arguments[1]:void 0);return(n[1]<<8|n[0])<<16>>16},getUint16:function(t){var n=C(this,2,t,arguments.length>1?arguments[1]:void 0);return n[1]<<8|n[0]},getInt32:function(t){return R(C(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return R(C(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return A(C(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return A(C(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,n){F(this,1,t,k,n)},setUint8:function(t,n){F(this,1,t,k,n)},setInt16:function(t,n){F(this,2,t,T,n,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,n){F(this,2,t,T,n,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,n){F(this,4,t,P,n,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,n){F(this,4,t,P,n,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,n){F(this,4,t,_,n,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,n){F(this,8,t,M,n,arguments.length>2?arguments[2]:void 0)}});y(O,"ArrayBuffer"),y(S,"DataView"),t.exports={ArrayBuffer:O,DataView:S}},function(t,n,e){var r=e(124);t.exports=function(t,n){for(var e=t.length;e--;)if(r(t[e][0],n))return e;return-1}},function(t,n){t.exports=function(t,n){return t===n||t!=t&&n!=n}},function(t,n){t.exports=function(t){var n=[];if(null!=t)for(var e in Object(t))n.push(e);return n}},function(t,n,e){var r=e(467),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();t.exports=i},function(t,n){t.exports=function(t){return t}},function(t,n,e){var r=e(499),o=e(130);t.exports=function(t){return o(t)&&r(t)}},function(t,n){var e=Object.prototype.toString;t.exports=function(t){return e.call(t)}},function(t,n){t.exports=function(t){return null!=t&&"object"==typeof t}},function(t,n){t.exports=function(){return!1}},function(t,n,e){var r=e(487),o=e(276)((function(t,n){return null==t?{}:r(t,n)}));t.exports=o},function(t,n,e){var r=e(71),o=e(169),i=e(500),a=e(83),u=e(70),s=e(504),c=e(276),f=e(174),l=c((function(t,n){var e={};if(null==t)return e;var c=!1;n=r(n,(function(n){return n=a(n,t),c||(c=n.length>1),n})),u(t,f(t),e),c&&(e=o(e,7,s));for(var l=n.length;l--;)i(e,n[l]);return e}));t.exports=l},function(t,n){var e;e=function(){return this}();try{e=e||new Function("return this")()}catch(t){"object"==typeof window&&(e=window)}t.exports=e},function(t,n,e){var r=e(2),o=e(3),i=r.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},function(t,n,e){var r=e(2),o=e(28);t.exports=function(t,n){try{o(r,t,n)}catch(e){r[t]=n}return n}},function(t,n,e){var r=e(189),o=Function.toString;"function"!=typeof r.inspectSource&&(r.inspectSource=function(t){return o.call(t)}),t.exports=r.inspectSource},function(t,n,e){var r=e(47),o=e(189);(t.exports=function(t,n){return o[t]||(o[t]=void 0!==n?n:{})})("versions",[]).push({version:"3.6.1",mode:r?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(t,n,e){var r=e(42),o=e(64),i=e(141),a=e(4);t.exports=r("Reflect","ownKeys")||function(t){var n=o.f(a(t)),e=i.f;return e?n.concat(e(t)):n}},function(t,n){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(t,n){n.f=Object.getOwnPropertySymbols},function(t,n,e){var r=e(1);t.exports=!!Object.getOwnPropertySymbols&&!r((function(){return!String(Symbol())}))},function(t,n,e){var r=e(5),o=e(10),i=e(4),a=e(92);t.exports=r?Object.defineProperties:function(t,n){i(t);for(var e,r=a(n),u=r.length,s=0;u>s;)o.f(t,e=r[s++],n[e]);return t}},function(t,n,e){var r=e(0),o=e(95),i=e(1),a=e(3),u=e(66).onFreeze,s=Object.freeze;r({target:"Object",stat:!0,forced:i((function(){s(1)})),sham:!o},{freeze:function(t){return s&&a(t)?s(u(t)):t}})},function(t,n,e){var r=e(7),o=e(96),i=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},function(t,n,e){var r={};r[e(7)("toStringTag")]="z",t.exports="[object z]"===String(r)},function(t,n,e){var r=e(1);t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},function(t,n,e){var r,o,i=e(2),a=e(109),u=i.process,s=u&&u.versions,c=s&&s.v8;c?o=(r=c.split("."))[0]+r[1]:a&&(!(r=a.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=a.match(/Chrome\/(\d+)/))&&(o=r[1]),t.exports=o&&+o},function(t,n,e){"use strict";var r=e(0),o=e(21).every;r({target:"Array",proto:!0,forced:e(52)("every")},{every:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){var r=e(0),o=e(151),i=e(60);r({target:"Array",proto:!0},{fill:o}),i("fill")},function(t,n,e){"use strict";var r=e(14),o=e(57),i=e(8);t.exports=function(t){for(var n=r(this),e=i(n.length),a=arguments.length,u=o(a>1?arguments[1]:void 0,e),s=a>2?arguments[2]:void 0,c=void 0===s?e:o(s,e);c>u;)n[u++]=t;return n}},function(t,n,e){"use strict";var r=e(0),o=e(153),i=e(50),a=e(76),u=e(48),s=e(28),c=e(25),f=e(7),l=e(47),p=e(96),h=e(209),d=h.IteratorPrototype,v=h.BUGGY_SAFARI_ITERATORS,g=f("iterator"),y=function(){return this};t.exports=function(t,n,e,f,h,m,b){o(e,n,f);var w,x,O,S=function(t){if(t===h&&T)return T;if(!v&&t in A)return A[t];switch(t){case"keys":case"values":case"entries":return function(){return new e(this,t)}}return function(){return new e(this)}},j=n+" Iterator",E=!1,A=t.prototype,k=A[g]||A["@@iterator"]||h&&A[h],T=!v&&k||S(h),P="Array"==n&&A.entries||k;if(P&&(w=i(P.call(new t)),d!==Object.prototype&&w.next&&(l||i(w)===d||(a?a(w,d):"function"!=typeof w[g]&&s(w,g,y)),u(w,j,!0,!0),l&&(p[j]=y))),"values"==h&&k&&"values"!==k.name&&(E=!0,T=function(){return k.call(this)}),l&&!b||A[g]===T||s(A,g,T),p[n]=T,h)if(x={values:S("values"),keys:m?T:S("keys"),entries:S("entries")},b)for(O in x)!v&&!E&&O in A||c(A,O,x[O]);else r({target:n,proto:!0,forced:v||E},x);return x}},function(t,n,e){"use strict";var r=e(209).IteratorPrototype,o=e(51),i=e(56),a=e(48),u=e(96),s=function(){return this};t.exports=function(t,n,e){var c=n+" Iterator";return t.prototype=o(r,{next:i(1,e)}),a(t,c,!1,!0),u[c]=s,t}},function(t,n,e){var r=e(112);t.exports=function(t){if(r(t))throw TypeError("The method doesn't accept regular expressions");return t}},function(t,n,e){var r=e(7)("match");t.exports=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[r]=!1,"/./"[t](n)}catch(t){}}return!1}},function(t,n,e){var r=e(8),o=e(157),i=e(27),a=Math.ceil,u=function(t){return function(n,e,u){var s,c,f=String(i(n)),l=f.length,p=void 0===u?" ":String(u),h=r(e);return h<=l||""==p?f:(s=h-l,(c=o.call(p,a(s/p.length))).length>s&&(c=c.slice(0,s)),t?f+c:c+f)}};t.exports={start:u(!1),end:u(!0)}},function(t,n,e){"use strict";var r=e(43),o=e(27);t.exports="".repeat||function(t){var n=String(o(this)),e="",i=r(t);if(i<0||i==1/0)throw RangeError("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(n+=n))1&i&&(e+=n);return e}},function(t,n,e){"use strict";var r=e(0),o=e(24).f,i=e(8),a=e(154),u=e(27),s=e(155),c=e(47),f="".startsWith,l=Math.min,p=s("startsWith");r({target:"String",proto:!0,forced:!(!c&&!p&&!!function(){var t=o(String.prototype,"startsWith");return t&&!t.writable}())&&!p},{startsWith:function(t){var n=String(u(this));a(t);var e=i(l(arguments.length>1?arguments[1]:void 0,n.length)),r=String(t);return f?f.call(n,r,e):n.slice(e,e+r.length)===r}})},function(t,n,e){"use strict";var r=e(0),o=e(81).trim;r({target:"String",proto:!0,forced:e(160)("trim")},{trim:function(){return o(this)}})},function(t,n,e){var r=e(1),o=e(118);t.exports=function(t){return r((function(){return!!o[t]()||"
"!="
"[t]()||o[t].name!==t}))}},function(t,n,e){"use strict";var r=e(5),o=e(2),i=e(91),a=e(25),u=e(17),s=e(41),c=e(119),f=e(46),l=e(1),p=e(51),h=e(64).f,d=e(24).f,v=e(10).f,g=e(81).trim,y=o.Number,m=y.prototype,b="Number"==s(p(m)),w=function(t){var n,e,r,o,i,a,u,s,c=f(t,!1);if("string"==typeof c&&c.length>2)if(43===(n=(c=g(c)).charCodeAt(0))||45===n){if(88===(e=c.charCodeAt(2))||120===e)return NaN}else if(48===n){switch(c.charCodeAt(1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+c}for(a=(i=c.slice(2)).length,u=0;u<a;u++)if((s=i.charCodeAt(u))<48||s>o)return NaN;return parseInt(i,r)}return+c};if(i("Number",!y(" 0o1")||!y("0b1")||y("+0x1"))){for(var x,O=function(t){var n=arguments.length<1?0:t,e=this;return e instanceof O&&(b?l((function(){m.valueOf.call(e)})):"Number"!=s(e))?c(new y(w(n)),e,O):w(n)},S=r?h(y):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),j=0;S.length>j;j++)u(y,x=S[j])&&!u(O,x)&&v(O,x,d(y,x));O.prototype=m,m.constructor=O,a(o,"Number",O)}},function(t,n){t.exports=Math.sign||function(t){return 0==(t=+t)||t!=t?t:t<0?-1:1}},function(t,n,e){var r,o,i,a=e(2),u=e(1),s=e(41),c=e(58),f=e(194),l=e(135),p=e(222),h=a.location,d=a.setImmediate,v=a.clearImmediate,g=a.process,y=a.MessageChannel,m=a.Dispatch,b=0,w={},x=function(t){if(w.hasOwnProperty(t)){var n=w[t];delete w[t],n()}},O=function(t){return function(){x(t)}},S=function(t){x(t.data)},j=function(t){a.postMessage(t+"",h.protocol+"//"+h.host)};d&&v||(d=function(t){for(var n=[],e=1;arguments.length>e;)n.push(arguments[e++]);return w[++b]=function(){("function"==typeof t?t:Function(t)).apply(void 0,n)},r(b),b},v=function(t){delete w[t]},"process"==s(g)?r=function(t){g.nextTick(O(t))}:m&&m.now?r=function(t){m.now(O(t))}:y&&!p?(i=(o=new y).port2,o.port1.onmessage=S,r=c(i.postMessage,i,1)):!a.addEventListener||"function"!=typeof postMessage||a.importScripts||u(j)?r="onreadystatechange"in l("script")?function(t){f.appendChild(l("script")).onreadystatechange=function(){f.removeChild(this),x(t)}}:function(t){setTimeout(O(t),0)}:(r=j,a.addEventListener("message",S,!1))),t.exports={set:d,clear:v}},function(t,n,e){"use strict";var r=e(32),o=function(t){var n,e;this.promise=new t((function(t,r){if(void 0!==n||void 0!==e)throw TypeError("Bad Promise constructor");n=t,e=r})),this.resolve=r(n),this.reject=r(e)};t.exports.f=function(t){return new o(t)}},function(t,n,e){var r=e(2),o=e(1),i=e(108),a=e(6).NATIVE_ARRAY_BUFFER_VIEWS,u=r.ArrayBuffer,s=r.Int8Array;t.exports=!a||!o((function(){s(1)}))||!o((function(){new s(-1)}))||!i((function(t){new s,new s(null),new s(1.5),new s(t)}),!0)||o((function(){return 1!==new s(new u(2),1,void 0).length}))},function(t,n,e){var r=e(0),o=e(5),i=e(4),a=e(24);r({target:"Reflect",stat:!0,sham:!o},{getOwnPropertyDescriptor:function(t,n){return a.f(i(t),n)}})},function(t,n,e){e(0)({target:"Reflect",stat:!0},{has:function(t,n){return n in t}})},function(t,n,e){e(0)({target:"Reflect",stat:!0},{ownKeys:e(139)})},function(t,n,e){var r=e(264),o=e(462),i=e(170),a=e(465),u=e(466),s=e(265),c=e(267),f=e(468),l=e(470),p=e(472),h=e(174),d=e(473),v=e(474),g=e(475),y=e(268),m=e(45),b=e(270),w=e(478),x=e(30),O=e(479),S=e(172),j={};j["[object Arguments]"]=j["[object Array]"]=j["[object ArrayBuffer]"]=j["[object DataView]"]=j["[object Boolean]"]=j["[object Date]"]=j["[object Float32Array]"]=j["[object Float64Array]"]=j["[object Int8Array]"]=j["[object Int16Array]"]=j["[object Int32Array]"]=j["[object Map]"]=j["[object Number]"]=j["[object Object]"]=j["[object RegExp]"]=j["[object Set]"]=j["[object String]"]=j["[object Symbol]"]=j["[object Uint8Array]"]=j["[object Uint8ClampedArray]"]=j["[object Uint16Array]"]=j["[object Uint32Array]"]=!0,j["[object Error]"]=j["[object Function]"]=j["[object WeakMap]"]=!1,t.exports=function t(n,e,E,A,k,T){var P,R=1&e,_=2&e,M=4&e;if(E&&(P=k?E(n,A,k,T):E(n)),void 0!==P)return P;if(!x(n))return n;var I=m(n);if(I){if(P=v(n),!R)return c(n,P)}else{var C=d(n),F="[object Function]"==C||"[object GeneratorFunction]"==C;if(b(n))return s(n,R);if("[object Object]"==C||"[object Arguments]"==C||F&&!k){if(P=_||F?{}:y(n),!R)return _?l(n,u(P,n)):f(n,a(P,n))}else{if(!j[C])return k?n:{};P=g(n,C,R)}}T||(T=new r);var N=T.get(n);if(N)return N;T.set(n,P),O(n)?n.forEach((function(r){P.add(t(r,e,E,r,n,T))})):w(n)&&n.forEach((function(r,o){P.set(o,t(r,e,E,o,n,T))}));var L=M?_?h:p:_?keysIn:S,D=I?void 0:L(n);return o(D||n,(function(r,o){D&&(r=n[o=r]),i(P,o,t(r,e,E,o,n,T))})),P}},function(t,n,e){var r=e(171),o=e(124),i=Object.prototype.hasOwnProperty;t.exports=function(t,n,e){var a=t[n];i.call(t,n)&&o(a,e)&&(void 0!==e||n in t)||r(t,n,e)}},function(t,n,e){var r=e(463);t.exports=function(t,n,e){"__proto__"==n&&r?r(t,n,{configurable:!0,enumerable:!0,value:e,writable:!0}):t[n]=e}},function(t,n,e){var r=e(173)(Object.keys,Object);t.exports=r},function(t,n){t.exports=function(t,n){return function(e){return t(n(e))}}},function(t,n){t.exports=function(t){var n=[];if(null!=t)for(var e in Object(t))n.push(e);return n}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(){return!1}},function(t,n,e){var r=e(491),o=e(492);t.exports=function t(n,e,i,a,u){var s=-1,c=n.length;for(i||(i=o),u||(u=[]);++s<c;){var f=n[s];e>0&&i(f)?e>1?t(f,e-1,i,a,u):r(u,f):a||(u[u.length]=f)}return u}},function(t,n,e){var r=e(45);t.exports=function(){if(!arguments.length)return[];var t=arguments[0];return r(t)?t:[t]}},function(t,n,e){var r=e(280);t.exports=function(t,n){return!!(null==t?0:t.length)&&r(t,n,0)>-1}},function(t,n){t.exports=function(t,n,e){for(var r=-1,o=null==t?0:t.length;++r<o;)if(e(n,t[r]))return!0;return!1}},function(t,n,e){var r=e(280);t.exports=function(t,n){return!!(null==t?0:t.length)&&r(t,n,0)>-1}},function(t,n){t.exports=function(t){return function(n){return t(n)}}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(){throw new Error("define cannot be used indirect")}},function(t,n,e){var r;!function(o,i){"use strict";var a="model",u="name",s="type",c="vendor",f="version",l="mobile",p="tablet",h={extend:function(t,n){var e={};for(var r in t)n[r]&&n[r].length%2==0?e[r]=n[r].concat(t[r]):e[r]=t[r];return e},has:function(t,n){return"string"==typeof t&&-1!==n.toLowerCase().indexOf(t.toLowerCase())},lowerize:function(t){return t.toLowerCase()},major:function(t){return"string"==typeof t?t.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(t){return t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},d={rgx:function(t,n){for(var e,r,o,i,a,u,s=0;s<n.length&&!a;){var c=n[s],f=n[s+1];for(e=r=0;e<c.length&&!a;)if(a=c[e++].exec(t))for(o=0;o<f.length;o++)u=a[++r],"object"==typeof(i=f[o])&&i.length>0?2==i.length?"function"==typeof i[1]?this[i[0]]=i[1].call(this,u):this[i[0]]=i[1]:3==i.length?"function"!=typeof i[1]||i[1].exec&&i[1].test?this[i[0]]=u?u.replace(i[1],i[2]):void 0:this[i[0]]=u?i[1].call(this,u,i[2]):void 0:4==i.length&&(this[i[0]]=u?i[3].call(this,u.replace(i[1],i[2])):void 0):this[i]=u||void 0;s+=2}},str:function(t,n){for(var e in n)if("object"==typeof n[e]&&n[e].length>0){for(var r=0;r<n[e].length;r++)if(h.has(n[e][r],t))return"?"===e?void 0:e}else if(h.has(n[e],t))return"?"===e?void 0:e;return t}},v={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},g={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[u,f],[/(opios)[\/\s]+([\w\.]+)/i],[[u,"Opera Mini"],f],[/\s(opr)\/([\w\.]+)/i],[[u,"Opera"],f],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]*)/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon)\/([\w\.-]+)/i],[u,f],[/(konqueror)\/([\w\.]+)/i],[[u,"Konqueror"],f],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[u,"IE"],f],[/(edge|edgios|edga|edg)\/((\d+)?[\w\.]+)/i],[[u,"Edge"],f],[/(yabrowser)\/([\w\.]+)/i],[[u,"Yandex"],f],[/(puffin)\/([\w\.]+)/i],[[u,"Puffin"],f],[/(focus)\/([\w\.]+)/i],[[u,"Firefox Focus"],f],[/(opt)\/([\w\.]+)/i],[[u,"Opera Touch"],f],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[u,"UCBrowser"],f],[/(comodo_dragon)\/([\w\.]+)/i],[[u,/_/g," "],f],[/(windowswechat qbcore)\/([\w\.]+)/i],[[u,"WeChat(Win) Desktop"],f],[/(micromessenger)\/([\w\.]+)/i],[[u,"WeChat"],f],[/(brave)\/([\w\.]+)/i],[[u,"Brave"],f],[/(qqbrowserlite)\/([\w\.]+)/i],[u,f],[/(QQ)\/([\d\.]+)/i],[u,f],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[u,f],[/(BIDUBrowser)[\/\s]?([\w\.]+)/i],[u,f],[/(2345Explorer)[\/\s]?([\w\.]+)/i],[u,f],[/(MetaSr)[\/\s]?([\w\.]+)/i],[u],[/(LBBROWSER)/i],[u],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[f,[u,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[f,[u,"Facebook"]],[/safari\s(line)\/([\w\.]+)/i,/android.+(line)\/([\w\.]+)\/iab/i],[u,f],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[f,[u,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[u,/(.+)/,"$1 WebView"],f],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[u,/(.+(?:g|us))(.+)/,"$1 $2"],f],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[f,[u,"Android Browser"]],[/(sailfishbrowser)\/([\w\.]+)/i],[[u,"Sailfish Browser"],f],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[u,f],[/(dolfin)\/([\w\.]+)/i],[[u,"Dolphin"],f],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[u,"Chrome"],f],[/(coast)\/([\w\.]+)/i],[[u,"Opera Coast"],f],[/fxios\/([\w\.-]+)/i],[f,[u,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[f,[u,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[f,u],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[u,"GSA"],f],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[u,[f,d.str,v.browser.oldsafari.version]],[/(webkit|khtml)\/([\w\.]+)/i],[u,f],[/(navigator|netscape)\/([\w\.-]+)/i],[[u,"Netscape"],f],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]*)/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[u,f]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",h.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",h.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+[;l]))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",h.lowerize]]],device:[[/\((ipad|playbook);[\w\s\),;-]+(rim|apple)/i],[a,c,[s,p]],[/applecoremedia\/[\w\.]+ \((ipad)/],[a,[c,"Apple"],[s,p]],[/(apple\s{0,1}tv)/i],[[a,"Apple TV"],[c,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[c,a,[s,p]],[/(kf[A-z]+)\sbuild\/.+silk\//i],[a,[c,"Amazon"],[s,p]],[/(sd|kf)[0349hijorstuw]+\sbuild\/.+silk\//i],[[a,d.str,v.device.amazon.model],[c,"Amazon"],[s,l]],[/android.+aft([bms])\sbuild/i],[a,[c,"Amazon"],[s,"smarttv"]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[a,c,[s,l]],[/\((ip[honed|\s\w*]+);/i],[a,[c,"Apple"],[s,l]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[c,a,[s,l]],[/\(bb10;\s(\w+)/i],[a,[c,"BlackBerry"],[s,l]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone|p00c)/i],[a,[c,"Asus"],[s,p]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[c,"Sony"],[a,"Xperia Tablet"],[s,p]],[/android.+\s([c-g]\d{4}|so[-l]\w+)(?=\sbuild\/|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[a,[c,"Sony"],[s,l]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[c,a,[s,"console"]],[/android.+;\s(shield)\sbuild/i],[a,[c,"Nvidia"],[s,"console"]],[/(playstation\s[34portablevi]+)/i],[a,[c,"Sony"],[s,"console"]],[/(sprint\s(\w+))/i],[[c,d.str,v.device.sprint.vendor],[a,d.str,v.device.sprint.model],[s,l]],[/(htc)[;_\s-]+([\w\s]+(?=\)|\sbuild)|\w+)/i,/(zte)-(\w*)/i,/(alcatel|geeksphone|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i],[c,[a,/_/g," "],[s,l]],[/(nexus\s9)/i],[a,[c,"HTC"],[s,p]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[a,[c,"Huawei"],[s,l]],[/(microsoft);\s(lumia[\s\w]+)/i],[c,a,[s,l]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[a,[c,"Microsoft"],[s,"console"]],[/(kin\.[onetw]{3})/i],[[a,/\./g," "],[c,"Microsoft"],[s,l]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w*)/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[a,[c,"Motorola"],[s,l]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[a,[c,"Motorola"],[s,p]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[c,h.trim],[a,h.trim],[s,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[a,/^/,"SmartTV"],[c,"Samsung"],[s,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[a,[c,"Sharp"],[s,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[c,"Samsung"],a,[s,p]],[/smart-tv.+(samsung)/i],[c,[s,"smarttv"],a],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)/i,/sec-((sgh\w+))/i],[[c,"Samsung"],a,[s,l]],[/sie-(\w*)/i],[a,[c,"Siemens"],[s,l]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]*)/i],[[c,"Nokia"],a,[s,l]],[/android[x\d\.\s;]+\s([ab][1-7]\-?[0178a]\d\d?)/i],[a,[c,"Acer"],[s,p]],[/android.+([vl]k\-?\d{3})\s+build/i],[a,[c,"LG"],[s,p]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[c,"LG"],a,[s,p]],[/(lg) netcast\.tv/i],[c,a,[s,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w*)/i,/android.+lg(\-?[\d\w]+)\s+build/i],[a,[c,"LG"],[s,l]],[/(lenovo)\s?(s(?:5000|6000)(?:[\w-]+)|tab(?:[\s\w]+))/i],[c,a,[s,p]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[a,[c,"Lenovo"],[s,p]],[/(lenovo)[_\s-]?([\w-]+)/i],[c,a,[s,l]],[/linux;.+((jolla));/i],[c,a,[s,l]],[/((pebble))app\/[\d\.]+\s/i],[c,a,[s,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[c,a,[s,l]],[/crkey/i],[[a,"Chromecast"],[c,"Google"]],[/android.+;\s(glass)\s\d/i],[a,[c,"Google"],[s,"wearable"]],[/android.+;\s(pixel c)[\s)]/i],[a,[c,"Google"],[s,p]],[/android.+;\s(pixel( [23])?( xl)?)[\s)]/i],[a,[c,"Google"],[s,l]],[/android.+;\s(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:a\d|one|one[\s_]plus|note lte)?[\s_]*(?:\d?\w?)[\s_]*(?:plus)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+))\s+build/i],[[a,/_/g," "],[c,"Xiaomi"],[s,l]],[/android.+(mi[\s\-_]*(?:pad)(?:[\s_]*[\w\s]+))\s+build/i],[[a,/_/g," "],[c,"Xiaomi"],[s,p]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[a,[c,"Meizu"],[s,l]],[/(mz)-([\w-]{2,})/i],[[c,"Meizu"],a,[s,l]],[/android.+a000(1)\s+build/i,/android.+oneplus\s(a\d{4})\s+build/i],[a,[c,"OnePlus"],[s,l]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[a,[c,"RCA"],[s,p]],[/android.+[;\/\s]+(Venue[\d\s]{2,7})\s+build/i],[a,[c,"Dell"],[s,p]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[a,[c,"Verizon"],[s,p]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[c,"Barnes & Noble"],a,[s,p]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[a,[c,"NuVision"],[s,p]],[/android.+;\s(k88)\sbuild/i],[a,[c,"ZTE"],[s,p]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[a,[c,"Swiss"],[s,l]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[a,[c,"Swiss"],[s,p]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[a,[c,"Zeki"],[s,p]],[/(android).+[;\/]\s+([YR]\d{2})\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(\w{5})\sbuild/i],[[c,"Dragon Touch"],a,[s,p]],[/android.+[;\/]\s*(NS-?\w{0,9})\sbuild/i],[a,[c,"Insignia"],[s,p]],[/android.+[;\/]\s*((NX|Next)-?\w{0,9})\s+build/i],[a,[c,"NextBook"],[s,p]],[/android.+[;\/]\s*(Xtreme\_)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[c,"Voice"],a,[s,l]],[/android.+[;\/]\s*(LVTEL\-)?(V1[12])\s+build/i],[[c,"LvTel"],a,[s,l]],[/android.+;\s(PH-1)\s/i],[a,[c,"Essential"],[s,l]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[a,[c,"Envizen"],[s,p]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(\w{1,9})\s+build/i],[c,a,[s,p]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[a,[c,"MachSpeed"],[s,p]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[c,a,[s,p]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[a,[c,"Rotor"],[s,p]],[/android.+(KS(.+))\s+build/i],[a,[c,"Amazon"],[s,p]],[/android.+(Gigaset)[\s\-]+(Q\w{1,9})\s+build/i],[c,a,[s,p]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[s,h.lowerize],c,a],[/[\s\/\(](smart-?tv)[;\)]/i],[[s,"smarttv"]],[/(android[\w\.\s\-]{0,9});.+build/i],[a,[c,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[f,[u,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)/i],[[u,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[u,f],[/rv\:([\w\.]{1,9}).+(gecko)/i],[f,u]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[u,f],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[u,[f,d.str,v.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[u,"Windows"],[f,d.str,v.os.windows.version]],[/\((bb)(10);/i],[[u,"BlackBerry"],f],[/(blackberry)\w*\/?([\w\.]*)/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|sailfish|contiki)[\/\s-]?([\w\.]*)/i],[u,f],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]*)/i],[[u,"Symbian"],f],[/\((series40);/i],[u],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[u,"Firefox OS"],f],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w*)/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]*)/i,/(hurd|linux)\s?([\w\.]*)/i,/(gnu)\s?([\w\.]*)/i],[u,f],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[u,"Chromium OS"],f],[/(sunos)\s?([\w\.\d]*)/i],[[u,"Solaris"],f],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]*)/i],[u,f],[/(haiku)\s(\w+)/i],[u,f],[/cfnetwork\/.+darwin/i,/ip[honead]{2,4}(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[f,/_/g,"."],[u,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]*)/i,/(macintosh|mac(?=_powerpc)\s)/i],[[u,"Mac OS"],[f,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]*)/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i,/(unix)\s?([\w\.]*)/i],[u,f]]},y=function(t,n){if("object"==typeof t&&(n=t,t=void 0),!(this instanceof y))return new y(t,n).getResult();var e=t||(o&&o.navigator&&o.navigator.userAgent?o.navigator.userAgent:""),r=n?h.extend(g,n):g;return this.getBrowser=function(){var t={name:void 0,version:void 0};return d.rgx.call(t,e,r.browser),t.major=h.major(t.version),t},this.getCPU=function(){var t={architecture:void 0};return d.rgx.call(t,e,r.cpu),t},this.getDevice=function(){var t={vendor:void 0,model:void 0,type:void 0};return d.rgx.call(t,e,r.device),t},this.getEngine=function(){var t={name:void 0,version:void 0};return d.rgx.call(t,e,r.engine),t},this.getOS=function(){var t={name:void 0,version:void 0};return d.rgx.call(t,e,r.os),t},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return e},this.setUA=function(t){return e=t,this},this};y.VERSION="0.7.20",y.BROWSER={NAME:u,MAJOR:"major",VERSION:f},y.CPU={ARCHITECTURE:"architecture"},y.DEVICE={MODEL:a,VENDOR:c,TYPE:s,CONSOLE:"console",MOBILE:l,SMARTTV:"smarttv",TABLET:p,WEARABLE:"wearable",EMBEDDED:"embedded"},y.ENGINE={NAME:u,VERSION:f},y.OS={NAME:u,VERSION:f},void 0!==n?(void 0!==t&&t.exports&&(n=t.exports=y),n.UAParser=y):void 0===(r=function(){return y}.call(n,e,n,t))||(t.exports=r);var m=o&&(o.jQuery||o.Zepto);if(void 0!==m&&!m.ua){var b=new y;m.ua=b.getResult(),m.ua.get=function(){return b.getUA()},m.ua.set=function(t){b.setUA(t);var n=b.getResult();for(var e in n)m.ua[e]=n[e]}}}("object"==typeof window?window:this)},function(t,n,e){var r=e(535),o=e(184);t.exports=function(t){return r(t,o)}},function(t,n,e){var r=e(5),o=e(1),i=e(135);t.exports=!r&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},function(t,n,e){var r=e(2),o=e(136),i=r["__core-js_shared__"]||o("__core-js_shared__",{});t.exports=i},function(t,n,e){var r=e(2),o=e(137),i=r.WeakMap;t.exports="function"==typeof i&&/native code/.test(o(i))},function(t,n,e){var r=e(17),o=e(139),i=e(24),a=e(10);t.exports=function(t,n){for(var e=o(n),u=a.f,s=i.f,c=0;c<e.length;c++){var f=e[c];r(t,f)||u(t,f,s(n,f))}}},function(t,n,e){var r=e(17),o=e(34),i=e(90).indexOf,a=e(88);t.exports=function(t,n){var e,u=o(t),s=0,c=[];for(e in u)!r(a,e)&&r(u,e)&&c.push(e);for(;n.length>s;)r(u,e=n[s++])&&(~i(c,e)||c.push(e));return c}},function(t,n,e){var r=e(142);t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(t,n,e){var r=e(42);t.exports=r("document","documentElement")},function(t,n,e){var r=e(34),o=e(64).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return a&&"[object Window]"==i.call(t)?function(t){try{return o(t)}catch(t){return a.slice()}}(t):o(r(t))}},function(t,n,e){var r=e(7);n.f=r},function(t,n,e){"use strict";var r=e(5),o=e(1),i=e(92),a=e(141),u=e(105),s=e(14),c=e(86),f=Object.assign,l=Object.defineProperty;t.exports=!f||o((function(){if(r&&1!==f({b:1},f(l({},"a",{enumerable:!0,get:function(){l(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},n={},e=Symbol();return t[e]=7,"abcdefghijklmnopqrst".split("").forEach((function(t){n[t]=t})),7!=f({},t)[e]||"abcdefghijklmnopqrst"!=i(f({},n)).join("")}))?function(t,n){for(var e=s(t),o=arguments.length,f=1,l=a.f,p=u.f;o>f;)for(var h,d=c(arguments[f++]),v=l?i(d).concat(l(d)):i(d),g=v.length,y=0;g>y;)h=v[y++],r&&!p.call(d,h)||(e[h]=d[h]);return e}:f},function(t,n,e){var r=e(5),o=e(92),i=e(34),a=e(105).f,u=function(t){return function(n){for(var e,u=i(n),s=o(u),c=s.length,f=0,l=[];c>f;)e=s[f++],r&&!a.call(u,e)||l.push(t?[e,u[e]]:u[e]);return l}};t.exports={entries:u(!0),values:u(!1)}},function(t,n,e){var r=e(4);t.exports=function(t,n,e,o){try{return o?n(r(e)[0],e[1]):n(e)}catch(n){var i=t.return;throw void 0!==i&&r(i.call(t)),n}}},function(t,n){t.exports=Object.is||function(t,n){return t===n?0!==t||1/t==1/n:t!=t&&n!=n}},function(t,n,e){var r=e(3);t.exports=function(t){if(!r(t)&&null!==t)throw TypeError("Can't set "+String(t)+" as a prototype");return t}},function(t,n,e){"use strict";var r=e(32),o=e(3),i=[].slice,a={},u=function(t,n,e){if(!(n in a)){for(var r=[],o=0;o<n;o++)r[o]="a["+o+"]";a[n]=Function("C,a","return new C("+r.join(",")+")")}return a[n](t,e)};t.exports=Function.bind||function(t){var n=r(this),e=i.call(arguments,1),a=function(){var r=e.concat(i.call(arguments));return this instanceof a?u(n,r.length,r):n.apply(t,r)};return o(n.prototype)&&(a.prototype=n.prototype),a}},function(t,n,e){"use strict";var r=e(58),o=e(14),i=e(199),a=e(145),u=e(8),s=e(67),c=e(97);t.exports=function(t){var n,e,f,l,p,h=o(t),d="function"==typeof this?this:Array,v=arguments.length,g=v>1?arguments[1]:void 0,y=void 0!==g,m=0,b=c(h);if(y&&(g=r(g,v>2?arguments[2]:void 0,2)),null==b||d==Array&&a(b))for(e=new d(n=u(h.length));n>m;m++)s(e,m,y?g(h[m],m):h[m]);else for(p=(l=b.call(h)).next,e=new d;!(f=p.call(l)).done;m++)s(e,m,y?i(l,g,[f.value,m],!0):f.value);return e.length=m,e}},function(t,n,e){"use strict";var r=e(14),o=e(57),i=e(8),a=Math.min;t.exports=[].copyWithin||function(t,n){var e=r(this),u=i(e.length),s=o(t,u),c=o(n,u),f=arguments.length>2?arguments[2]:void 0,l=a((void 0===f?u:o(f,u))-c,u-s),p=1;for(c<s&&s<c+l&&(p=-1,c+=l-1,s+=l-1);l-- >0;)c in e?e[s]=e[c]:delete e[s],s+=p,c+=p;return e}},function(t,n,e){"use strict";var r=e(65),o=e(8),i=e(58),a=function(t,n,e,u,s,c,f,l){for(var p,h=s,d=0,v=!!f&&i(f,l,3);d<u;){if(d in e){if(p=v?v(e[d],d,n):e[d],c>0&&r(p))h=a(t,n,p,o(p.length),h,c-1)-1;else{if(h>=9007199254740991)throw TypeError("Exceed the acceptable array length");t[h]=p}h++}d++}return h};t.exports=a},function(t,n,e){"use strict";var r=e(21).forEach,o=e(52);t.exports=o("forEach")?function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}:[].forEach},function(t,n,e){"use strict";var r=e(0),o=e(90).indexOf,i=e(52),a=[].indexOf,u=!!a&&1/[1].indexOf(1,-0)<0,s=i("indexOf");r({target:"Array",proto:!0,forced:u||s},{indexOf:function(t){return u?a.apply(this,arguments)||0:o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(34),o=e(43),i=e(8),a=e(52),u=Math.min,s=[].lastIndexOf,c=!!s&&1/[1].lastIndexOf(1,-0)<0,f=a("lastIndexOf");t.exports=c||f?function(t){if(c)return s.apply(this,arguments)||0;var n=r(this),e=i(n.length),a=e-1;for(arguments.length>1&&(a=u(a,o(arguments[1]))),a<0&&(a=e+a);a>=0;a--)if(a in n&&n[a]===t)return a||0;return-1}:s},function(t,n,e){"use strict";var r,o,i,a=e(50),u=e(28),s=e(17),c=e(7),f=e(47),l=c("iterator"),p=!1;[].keys&&("next"in(i=[].keys())?(o=a(a(i)))!==Object.prototype&&(r=o):p=!0),null==r&&(r={}),f||s(r,l)||u(r,l,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:p}},function(t,n,e){var r=e(109);t.exports=/Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(r)},function(t,n,e){"use strict";var r=e(0),o=e(156).start;r({target:"String",proto:!0,forced:e(210)},{padStart:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){e(0)({target:"String",proto:!0},{repeat:e(157)})},function(t,n,e){"use strict";var r=e(113),o=e(4),i=e(27),a=e(200),u=e(117);r("search",1,(function(t,n,e){return[function(n){var e=i(this),r=null==n?void 0:n[t];return void 0!==r?r.call(n,e):new RegExp(n)[t](String(e))},function(t){var r=e(n,t,this);if(r.done)return r.value;var i=o(t),s=String(this),c=i.lastIndex;a(c,0)||(i.lastIndex=0);var f=u(i,s);return a(i.lastIndex,c)||(i.lastIndex=c),null===f?-1:f.index}]}))},function(t,n,e){var r=e(5),o=e(2),i=e(91),a=e(119),u=e(10).f,s=e(64).f,c=e(112),f=e(102),l=e(115),p=e(25),h=e(1),d=e(29).set,v=e(79),g=e(7)("match"),y=o.RegExp,m=y.prototype,b=/a/g,w=/a/g,x=new y(b)!==b,O=l.UNSUPPORTED_Y;if(r&&i("RegExp",!x||O||h((function(){return w[g]=!1,y(b)!=b||y(w)==w||"/a/i"!=y(b,"i")})))){for(var S=function(t,n){var e,r=this instanceof S,o=c(t),i=void 0===n;if(!r&&o&&t.constructor===S&&i)return t;x?o&&!i&&(t=t.source):t instanceof S&&(i&&(n=f.call(t)),t=t.source),O&&(e=!!n&&n.indexOf("y")>-1)&&(n=n.replace(/y/g,""));var u=a(x?new y(t,n):y(t,n),r?this:m,S);return O&&e&&d(u,{sticky:e}),u},j=function(t){t in S||u(S,t,{configurable:!0,get:function(){return y[t]},set:function(n){y[t]=n}})},E=s(y),A=0;E.length>A;)j(E[A++]);m.constructor=S,S.prototype=m,p(o,"RegExp",S)}v("RegExp")},function(t,n,e){var r=e(2),o=e(81).trim,i=e(118),a=r.parseInt,u=/^[+-]?0[Xx]/,s=8!==a(i+"08")||22!==a(i+"0x16");t.exports=s?function(t,n){var e=o(String(t));return a(e,n>>>0||(u.test(e)?16:10))}:a},function(t,n,e){var r=e(2),o=e(81).trim,i=e(118),a=r.parseFloat,u=1/a(i+"-0")!=-1/0;t.exports=u?function(t){var n=o(String(t)),e=a(n);return 0===e&&"-"==n.charAt(0)?-0:e}:a},function(t,n,e){var r=e(3),o=Math.floor;t.exports=function(t){return!r(t)&&isFinite(t)&&o(t)===t}},function(t,n,e){"use strict";var r=e(0),o=e(43),i=e(219),a=e(157),u=e(1),s=1..toFixed,c=Math.floor,f=function(t,n,e){return 0===n?e:n%2==1?f(t,n-1,e*t):f(t*t,n/2,e)};r({target:"Number",proto:!0,forced:s&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!u((function(){s.call({})}))},{toFixed:function(t){var n,e,r,u,s=i(this),l=o(t),p=[0,0,0,0,0,0],h="",d="0",v=function(t,n){for(var e=-1,r=n;++e<6;)r+=t*p[e],p[e]=r%1e7,r=c(r/1e7)},g=function(t){for(var n=6,e=0;--n>=0;)e+=p[n],p[n]=c(e/t),e=e%t*1e7},y=function(){for(var t=6,n="";--t>=0;)if(""!==n||0===t||0!==p[t]){var e=String(p[t]);n=""===n?e:n+a.call("0",7-e.length)+e}return n};if(l<0||l>20)throw RangeError("Incorrect fraction digits");if(s!=s)return"NaN";if(s<=-1e21||s>=1e21)return String(s);if(s<0&&(h="-",s=-s),s>1e-21)if(e=(n=function(t){for(var n=0,e=t;e>=4096;)n+=12,e/=4096;for(;e>=2;)n+=1,e/=2;return n}(s*f(2,69,1))-69)<0?s*f(2,-n,1):s/f(2,n,1),e*=4503599627370496,(n=52-n)>0){for(v(0,e),r=l;r>=7;)v(1e7,0),r-=7;for(v(f(10,r,1),0),r=n-1;r>=23;)g(1<<23),r-=23;g(1<<r),v(1,1),g(2),d=y()}else v(0,e),v(1<<-n,0),d=y()+a.call("0",l);return d=l>0?h+((u=d.length)<=l?"0."+a.call("0",l-u)+d:d.slice(0,u-l)+"."+d.slice(u-l)):h+d}})},function(t,n,e){var r=e(41);t.exports=function(t){if("number"!=typeof t&&"Number"!=r(t))throw TypeError("Incorrect invocation");return+t}},function(t,n){var e=Math.log;t.exports=Math.log1p||function(t){return(t=+t)>-1e-8&&t<1e-8?t-t*t/2:e(1+t)}},function(t,n,e){var r=e(2);t.exports=r.Promise},function(t,n,e){var r=e(109);t.exports=/(iphone|ipod|ipad).*applewebkit/i.test(r)},function(t,n,e){var r,o,i,a,u,s,c,f,l=e(2),p=e(24).f,h=e(41),d=e(163).set,v=e(222),g=l.MutationObserver||l.WebKitMutationObserver,y=l.process,m=l.Promise,b="process"==h(y),w=p(l,"queueMicrotask"),x=w&&w.value;x||(r=function(){var t,n;for(b&&(t=y.domain)&&t.exit();o;){n=o.fn,o=o.next;try{n()}catch(t){throw o?a():i=void 0,t}}i=void 0,t&&t.enter()},b?a=function(){y.nextTick(r)}:g&&!v?(u=!0,s=document.createTextNode(""),new g(r).observe(s,{characterData:!0}),a=function(){s.data=u=!u}):m&&m.resolve?(c=m.resolve(void 0),f=c.then,a=function(){f.call(c,r)}):a=function(){d.call(l,r)}),t.exports=x||function(t){var n={fn:t,next:void 0};i&&(i.next=n),o||(o=n,a()),i=n}},function(t,n,e){var r=e(4),o=e(3),i=e(164);t.exports=function(t,n){if(r(t),o(n)&&n.constructor===t)return n;var e=i.f(t);return(0,e.resolve)(n),e.promise}},function(t,n){t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},function(t,n,e){"use strict";var r=e(0),o=e(47),i=e(221),a=e(1),u=e(42),s=e(53),c=e(224),f=e(25);r({target:"Promise",proto:!0,real:!0,forced:!!i&&a((function(){i.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var n=s(this,u("Promise")),e="function"==typeof t;return this.then(e?function(e){return c(n,t()).then((function(){return e}))}:t,e?function(e){return c(n,t()).then((function(){throw e}))}:t)}}),o||"function"!=typeof i||i.prototype.finally||f(i.prototype,"finally",u("Promise").prototype.finally)},function(t,n,e){"use strict";var r=e(121),o=e(228);t.exports=r("Map",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),o)},function(t,n,e){"use strict";var r=e(10).f,o=e(51),i=e(82),a=e(58),u=e(62),s=e(75),c=e(152),f=e(79),l=e(5),p=e(66).fastKey,h=e(29),d=h.set,v=h.getterFor;t.exports={getConstructor:function(t,n,e,c){var f=t((function(t,r){u(t,f,n),d(t,{type:n,index:o(null),first:void 0,last:void 0,size:0}),l||(t.size=0),null!=r&&s(r,t[c],t,e)})),h=v(n),g=function(t,n,e){var r,o,i=h(t),a=y(t,n);return a?a.value=e:(i.last=a={index:o=p(n,!0),key:n,value:e,previous:r=i.last,next:void 0,removed:!1},i.first||(i.first=a),r&&(r.next=a),l?i.size++:t.size++,"F"!==o&&(i.index[o]=a)),t},y=function(t,n){var e,r=h(t),o=p(n);if("F"!==o)return r.index[o];for(e=r.first;e;e=e.next)if(e.key==n)return e};return i(f.prototype,{clear:function(){for(var t=h(this),n=t.index,e=t.first;e;)e.removed=!0,e.previous&&(e.previous=e.previous.next=void 0),delete n[e.index],e=e.next;t.first=t.last=void 0,l?t.size=0:this.size=0},delete:function(t){var n=h(this),e=y(this,t);if(e){var r=e.next,o=e.previous;delete n.index[e.index],e.removed=!0,o&&(o.next=r),r&&(r.previous=o),n.first==e&&(n.first=r),n.last==e&&(n.last=o),l?n.size--:this.size--}return!!e},forEach:function(t){for(var n,e=h(this),r=a(t,arguments.length>1?arguments[1]:void 0,3);n=n?n.next:e.first;)for(r(n.value,n.key,this);n&&n.removed;)n=n.previous},has:function(t){return!!y(this,t)}}),i(f.prototype,e?{get:function(t){var n=y(this,t);return n&&n.value},set:function(t,n){return g(this,0===t?0:t,n)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),l&&r(f.prototype,"size",{get:function(){return h(this).size}}),f},setStrong:function(t,n,e){var r=n+" Iterator",o=v(n),i=v(r);c(t,n,(function(t,n){d(this,{type:r,target:t,state:o(t),kind:n,last:void 0})}),(function(){for(var t=i(this),n=t.kind,e=t.last;e&&e.removed;)e=e.previous;return t.target&&(t.last=e=e?e.next:t.state.first)?"keys"==n?{value:e.key,done:!1}:"values"==n?{value:e.value,done:!1}:{value:[e.key,e.value],done:!1}:(t.target=void 0,{value:void 0,done:!0})}),e?"entries":"values",!e,!0),f(n)}}},function(t,n,e){"use strict";var r=e(121),o=e(228);t.exports=r("Set",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),o)},function(t,n,e){"use strict";var r,o=e(2),i=e(82),a=e(66),u=e(121),s=e(231),c=e(3),f=e(29).enforce,l=e(190),p=!o.ActiveXObject&&"ActiveXObject"in o,h=Object.isExtensible,d=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},v=t.exports=u("WeakMap",d,s);if(l&&p){r=s.getConstructor(d,"WeakMap",!0),a.REQUIRED=!0;var g=v.prototype,y=g.delete,m=g.has,b=g.get,w=g.set;i(g,{delete:function(t){if(c(t)&&!h(t)){var n=f(this);return n.frozen||(n.frozen=new r),y.call(this,t)||n.frozen.delete(t)}return y.call(this,t)},has:function(t){if(c(t)&&!h(t)){var n=f(this);return n.frozen||(n.frozen=new r),m.call(this,t)||n.frozen.has(t)}return m.call(this,t)},get:function(t){if(c(t)&&!h(t)){var n=f(this);return n.frozen||(n.frozen=new r),m.call(this,t)?b.call(this,t):n.frozen.get(t)}return b.call(this,t)},set:function(t,n){if(c(t)&&!h(t)){var e=f(this);e.frozen||(e.frozen=new r),m.call(this,t)?w.call(this,t,n):e.frozen.set(t,n)}else w.call(this,t,n);return this}})}},function(t,n,e){"use strict";var r=e(82),o=e(66).getWeakData,i=e(4),a=e(3),u=e(62),s=e(75),c=e(21),f=e(17),l=e(29),p=l.set,h=l.getterFor,d=c.find,v=c.findIndex,g=0,y=function(t){return t.frozen||(t.frozen=new m)},m=function(){this.entries=[]},b=function(t,n){return d(t.entries,(function(t){return t[0]===n}))};m.prototype={get:function(t){var n=b(this,t);if(n)return n[1]},has:function(t){return!!b(this,t)},set:function(t,n){var e=b(this,t);e?e[1]=n:this.entries.push([t,n])},delete:function(t){var n=v(this.entries,(function(n){return n[0]===t}));return~n&&this.entries.splice(n,1),!!~n}},t.exports={getConstructor:function(t,n,e,c){var l=t((function(t,r){u(t,l,n),p(t,{type:n,id:g++,frozen:void 0}),null!=r&&s(r,t[c],t,e)})),d=h(n),v=function(t,n,e){var r=d(t),a=o(i(n),!0);return!0===a?y(r).set(n,e):a[r.id]=e,t};return r(l.prototype,{delete:function(t){var n=d(this);if(!a(t))return!1;var e=o(t);return!0===e?y(n).delete(t):e&&f(e,n.id)&&delete e[n.id]},has:function(t){var n=d(this);if(!a(t))return!1;var e=o(t);return!0===e?y(n).has(t):e&&f(e,n.id)}}),r(l.prototype,e?{get:function(t){var n=d(this);if(a(t)){var e=o(t);return!0===e?y(n).get(t):e?e[n.id]:void 0}},set:function(t,n){return v(this,t,n)}}:{add:function(t){return v(this,t,!0)}}),l}}},function(t,n,e){var r=e(43),o=e(8);t.exports=function(t){if(void 0===t)return 0;var n=r(t),e=o(n);if(n!==e)throw RangeError("Wrong length or index");return e}},function(t,n,e){"use strict";var r=e(0),o=e(1),i=e(122),a=e(4),u=e(57),s=e(8),c=e(53),f=i.ArrayBuffer,l=i.DataView,p=f.prototype.slice;r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:o((function(){return!new f(2).slice(1,void 0).byteLength}))},{slice:function(t,n){if(void 0!==p&&void 0===n)return p.call(a(this),t);for(var e=a(this).byteLength,r=u(t,e),o=u(void 0===n?e:n,e),i=new(c(this,f))(s(o-r)),h=new l(this),d=new l(i),v=0;r<o;)d.setUint8(v++,h.getUint8(r++));return i}})},function(t,n,e){var r=e(431);t.exports=function(t,n){var e=r(t);if(e%n)throw RangeError("Wrong offset");return e}},function(t,n,e){var r=e(14),o=e(8),i=e(97),a=e(145),u=e(58),s=e(6).aTypedArrayConstructor;t.exports=function(t){var n,e,c,f,l,p,h=r(t),d=arguments.length,v=d>1?arguments[1]:void 0,g=void 0!==v,y=i(h);if(null!=y&&!a(y))for(p=(l=y.call(h)).next,h=[];!(f=p.call(l)).done;)h.push(f.value);for(g&&d>2&&(v=u(v,arguments[2],2)),e=o(h.length),c=new(s(this))(e),n=0;e>n;n++)c[n]=g?v(h[n],n):h[n];return c}},function(t,n,e){e(54)("Uint8",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){"use strict";var r=e(6),o=e(204),i=r.aTypedArray;(0,r.exportTypedArrayMethod)("copyWithin",(function(t,n){return o.call(i(this),t,n,arguments.length>2?arguments[2]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(21).every,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("every",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(151),i=r.aTypedArray;(0,r.exportTypedArrayMethod)("fill",(function(t){return o.apply(i(this),arguments)}))},function(t,n,e){"use strict";var r=e(6),o=e(21).filter,i=e(53),a=r.aTypedArray,u=r.aTypedArrayConstructor;(0,r.exportTypedArrayMethod)("filter",(function(t){for(var n=o(a(this),t,arguments.length>1?arguments[1]:void 0),e=i(this,this.constructor),r=0,s=n.length,c=new(u(e))(s);s>r;)c[r]=n[r++];return c}))},function(t,n,e){"use strict";var r=e(6),o=e(21).find,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("find",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(21).findIndex,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("findIndex",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(21).forEach,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("forEach",(function(t){o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(90).includes,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("includes",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(90).indexOf,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("indexOf",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(2),o=e(6),i=e(9),a=e(7)("iterator"),u=r.Uint8Array,s=i.values,c=i.keys,f=i.entries,l=o.aTypedArray,p=o.exportTypedArrayMethod,h=u&&u.prototype[a],d=!!h&&("values"==h.name||null==h.name),v=function(){return s.call(l(this))};p("entries",(function(){return f.call(l(this))})),p("keys",(function(){return c.call(l(this))})),p("values",v,!d),p(a,v,!d)},function(t,n,e){"use strict";var r=e(6),o=r.aTypedArray,i=r.exportTypedArrayMethod,a=[].join;i("join",(function(t){return a.apply(o(this),arguments)}))},function(t,n,e){"use strict";var r=e(6),o=e(208),i=r.aTypedArray;(0,r.exportTypedArrayMethod)("lastIndexOf",(function(t){return o.apply(i(this),arguments)}))},function(t,n,e){"use strict";var r=e(6),o=e(21).map,i=e(53),a=r.aTypedArray,u=r.aTypedArrayConstructor;(0,r.exportTypedArrayMethod)("map",(function(t){return o(a(this),t,arguments.length>1?arguments[1]:void 0,(function(t,n){return new(u(i(t,t.constructor)))(n)}))}))},function(t,n,e){"use strict";var r=e(6),o=e(110).left,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("reduce",(function(t){return o(i(this),t,arguments.length,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=e(110).right,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("reduceRight",(function(t){return o(i(this),t,arguments.length,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=r.aTypedArray,i=r.exportTypedArrayMethod,a=Math.floor;i("reverse",(function(){for(var t,n=o(this).length,e=a(n/2),r=0;r<e;)t=this[r],this[r++]=this[--n],this[n]=t;return this}))},function(t,n,e){"use strict";var r=e(6),o=e(8),i=e(234),a=e(14),u=e(1),s=r.aTypedArray;(0,r.exportTypedArrayMethod)("set",(function(t){s(this);var n=i(arguments.length>1?arguments[1]:void 0,1),e=this.length,r=a(t),u=o(r.length),c=0;if(u+n>e)throw RangeError("Wrong length");for(;c<u;)this[n+c]=r[c++]}),u((function(){new Int8Array(1).set({})})))},function(t,n,e){"use strict";var r=e(6),o=e(53),i=e(1),a=r.aTypedArray,u=r.aTypedArrayConstructor,s=r.exportTypedArrayMethod,c=[].slice;s("slice",(function(t,n){for(var e=c.call(a(this),t,n),r=o(this,this.constructor),i=0,s=e.length,f=new(u(r))(s);s>i;)f[i]=e[i++];return f}),i((function(){new Int8Array(1).slice()})))},function(t,n,e){"use strict";var r=e(6),o=e(21).some,i=r.aTypedArray;(0,r.exportTypedArrayMethod)("some",(function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)}))},function(t,n,e){"use strict";var r=e(6),o=r.aTypedArray,i=r.exportTypedArrayMethod,a=[].sort;i("sort",(function(t){return a.call(o(this),t)}))},function(t,n,e){"use strict";var r=e(6),o=e(8),i=e(57),a=e(53),u=r.aTypedArray;(0,r.exportTypedArrayMethod)("subarray",(function(t,n){var e=u(this),r=e.length,s=i(t,r);return new(a(e,e.constructor))(e.buffer,e.byteOffset+s*e.BYTES_PER_ELEMENT,o((void 0===n?r:i(n,r))-s))}))},function(t,n,e){"use strict";var r=e(2),o=e(6),i=e(1),a=r.Int8Array,u=o.aTypedArray,s=o.exportTypedArrayMethod,c=[].toLocaleString,f=[].slice,l=!!a&&i((function(){c.call(new a(1))}));s("toLocaleString",(function(){return c.apply(l?f.call(u(this)):u(this),arguments)}),i((function(){return[1,2].toLocaleString()!=new a([1,2]).toLocaleString()}))||!i((function(){a.prototype.toLocaleString.call([1,2])})))},function(t,n,e){"use strict";var r=e(6).exportTypedArrayMethod,o=e(1),i=e(2).Uint8Array,a=i&&i.prototype||{},u=[].toString,s=[].join;o((function(){u.call({})}))&&(u=function(){return s.call(this)});var c=a.toString!=u;r("toString",u,c)},function(t,n){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(t,n,e){"use strict";e(12);var r,o=e(0),i=e(5),a=e(262),u=e(2),s=e(143),c=e(25),f=e(62),l=e(17),p=e(197),h=e(203),d=e(111).codeAt,v=e(454),g=e(48),y=e(263),m=e(29),b=u.URL,w=y.URLSearchParams,x=y.getState,O=m.set,S=m.getterFor("URL"),j=Math.floor,E=Math.pow,A=/[A-Za-z]/,k=/[\d+\-.A-Za-z]/,T=/\d/,P=/^(0x|0X)/,R=/^[0-7]+$/,_=/^\d+$/,M=/^[\dA-Fa-f]+$/,I=/[\u0000\u0009\u000A\u000D #%/:?@[\\]]/,C=/[\u0000\u0009\u000A\u000D #/:?@[\\]]/,F=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,N=/[\u0009\u000A\u000D]/g,L=function(t,n){var e,r,o;if("["==n.charAt(0)){if("]"!=n.charAt(n.length-1))return"Invalid host";if(!(e=U(n.slice(1,-1))))return"Invalid host";t.host=e}else if(G(t)){if(n=v(n),I.test(n))return"Invalid host";if(null===(e=D(n)))return"Invalid host";t.host=e}else{if(C.test(n))return"Invalid host";for(e="",r=h(n),o=0;o<r.length;o++)e+=H(r[o],B);t.host=e}},D=function(t){var n,e,r,o,i,a,u,s=t.split(".");if(s.length&&""==s[s.length-1]&&s.pop(),(n=s.length)>4)return t;for(e=[],r=0;r<n;r++){if(""==(o=s[r]))return t;if(i=10,o.length>1&&"0"==o.charAt(0)&&(i=P.test(o)?16:8,o=o.slice(8==i?1:2)),""===o)a=0;else{if(!(10==i?_:8==i?R:M).test(o))return t;a=parseInt(o,i)}e.push(a)}for(r=0;r<n;r++)if(a=e[r],r==n-1){if(a>=E(256,5-n))return null}else if(a>255)return null;for(u=e.pop(),r=0;r<e.length;r++)u+=e[r]*E(256,3-r);return u},U=function(t){var n,e,r,o,i,a,u,s=[0,0,0,0,0,0,0,0],c=0,f=null,l=0,p=function(){return t.charAt(l)};if(":"==p()){if(":"!=t.charAt(1))return;l+=2,f=++c}for(;p();){if(8==c)return;if(":"!=p()){for(n=e=0;e<4&&M.test(p());)n=16*n+parseInt(p(),16),l++,e++;if("."==p()){if(0==e)return;if(l-=e,c>6)return;for(r=0;p();){if(o=null,r>0){if(!("."==p()&&r<4))return;l++}if(!T.test(p()))return;for(;T.test(p());){if(i=parseInt(p(),10),null===o)o=i;else{if(0==o)return;o=10*o+i}if(o>255)return;l++}s[c]=256*s[c]+o,2!=++r&&4!=r||c++}if(4!=r)return;break}if(":"==p()){if(l++,!p())return}else if(p())return;s[c++]=n}else{if(null!==f)return;l++,f=++c}}if(null!==f)for(a=c-f,c=7;0!=c&&a>0;)u=s[c],s[c--]=s[f+a-1],s[f+--a]=u;else if(8!=c)return;return s},q=function(t){var n,e,r,o;if("number"==typeof t){for(n=[],e=0;e<4;e++)n.unshift(t%256),t=j(t/256);return n.join(".")}if("object"==typeof t){for(n="",r=function(t){for(var n=null,e=1,r=null,o=0,i=0;i<8;i++)0!==t[i]?(o>e&&(n=r,e=o),r=null,o=0):(null===r&&(r=i),++o);return o>e&&(n=r,e=o),n}(t),e=0;e<8;e++)o&&0===t[e]||(o&&(o=!1),r===e?(n+=e?":":"::",o=!0):(n+=t[e].toString(16),e<7&&(n+=":")));return"["+n+"]"}return t},B={},z=p({},B,{" ":1,'"':1,"<":1,">":1,"`":1}),V=p({},z,{"#":1,"?":1,"{":1,"}":1}),W=p({},V,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),H=function(t,n){var e=d(t,0);return e>32&&e<127&&!l(n,t)?t:encodeURIComponent(t)},$={ftp:21,file:null,http:80,https:443,ws:80,wss:443},G=function(t){return l($,t.scheme)},Y=function(t){return""!=t.username||""!=t.password},J=function(t){return!t.host||t.cannotBeABaseURL||"file"==t.scheme},K=function(t,n){var e;return 2==t.length&&A.test(t.charAt(0))&&(":"==(e=t.charAt(1))||!n&&"|"==e)},X=function(t){var n;return t.length>1&&K(t.slice(0,2))&&(2==t.length||"/"===(n=t.charAt(2))||"\\"===n||"?"===n||"#"===n)},Q=function(t){var n=t.path,e=n.length;!e||"file"==t.scheme&&1==e&&K(n[0],!0)||n.pop()},Z=function(t){return"."===t||"%2e"===t.toLowerCase()},tt=function(t){return".."===(t=t.toLowerCase())||"%2e."===t||".%2e"===t||"%2e%2e"===t},nt={},et={},rt={},ot={},it={},at={},ut={},st={},ct={},ft={},lt={},pt={},ht={},dt={},vt={},gt={},yt={},mt={},bt={},wt={},xt={},Ot=function(t,n,e,o){var i,a,u,s,c=e||nt,f=0,p="",d=!1,v=!1,g=!1;for(e||(t.scheme="",t.username="",t.password="",t.host=null,t.port=null,t.path=[],t.query=null,t.fragment=null,t.cannotBeABaseURL=!1,n=n.replace(F,"")),n=n.replace(N,""),i=h(n);f<=i.length;){switch(a=i[f],c){case nt:if(!a||!A.test(a)){if(e)return"Invalid scheme";c=rt;continue}p+=a.toLowerCase(),c=et;break;case et:if(a&&(k.test(a)||"+"==a||"-"==a||"."==a))p+=a.toLowerCase();else{if(":"!=a){if(e)return"Invalid scheme";p="",c=rt,f=0;continue}if(e&&(G(t)!=l($,p)||"file"==p&&(Y(t)||null!==t.port)||"file"==t.scheme&&!t.host))return;if(t.scheme=p,e)return void(G(t)&&$[t.scheme]==t.port&&(t.port=null));p="","file"==t.scheme?c=dt:G(t)&&o&&o.scheme==t.scheme?c=ot:G(t)?c=st:"/"==i[f+1]?(c=it,f++):(t.cannotBeABaseURL=!0,t.path.push(""),c=bt)}break;case rt:if(!o||o.cannotBeABaseURL&&"#"!=a)return"Invalid scheme";if(o.cannotBeABaseURL&&"#"==a){t.scheme=o.scheme,t.path=o.path.slice(),t.query=o.query,t.fragment="",t.cannotBeABaseURL=!0,c=xt;break}c="file"==o.scheme?dt:at;continue;case ot:if("/"!=a||"/"!=i[f+1]){c=at;continue}c=ct,f++;break;case it:if("/"==a){c=ft;break}c=mt;continue;case at:if(t.scheme=o.scheme,a==r)t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query=o.query;else if("/"==a||"\\"==a&&G(t))c=ut;else if("?"==a)t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query="",c=wt;else{if("#"!=a){t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.path.pop(),c=mt;continue}t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query=o.query,t.fragment="",c=xt}break;case ut:if(!G(t)||"/"!=a&&"\\"!=a){if("/"!=a){t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,c=mt;continue}c=ft}else c=ct;break;case st:if(c=ct,"/"!=a||"/"!=p.charAt(f+1))continue;f++;break;case ct:if("/"!=a&&"\\"!=a){c=ft;continue}break;case ft:if("@"==a){d&&(p="%40"+p),d=!0,u=h(p);for(var y=0;y<u.length;y++){var m=u[y];if(":"!=m||g){var b=H(m,W);g?t.password+=b:t.username+=b}else g=!0}p=""}else if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&G(t)){if(d&&""==p)return"Invalid authority";f-=h(p).length+1,p="",c=lt}else p+=a;break;case lt:case pt:if(e&&"file"==t.scheme){c=gt;continue}if(":"!=a||v){if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&G(t)){if(G(t)&&""==p)return"Invalid host";if(e&&""==p&&(Y(t)||null!==t.port))return;if(s=L(t,p))return s;if(p="",c=yt,e)return;continue}"["==a?v=!0:"]"==a&&(v=!1),p+=a}else{if(""==p)return"Invalid host";if(s=L(t,p))return s;if(p="",c=ht,e==pt)return}break;case ht:if(!T.test(a)){if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&G(t)||e){if(""!=p){var w=parseInt(p,10);if(w>65535)return"Invalid port";t.port=G(t)&&w===$[t.scheme]?null:w,p=""}if(e)return;c=yt;continue}return"Invalid port"}p+=a;break;case dt:if(t.scheme="file","/"==a||"\\"==a)c=vt;else{if(!o||"file"!=o.scheme){c=mt;continue}if(a==r)t.host=o.host,t.path=o.path.slice(),t.query=o.query;else if("?"==a)t.host=o.host,t.path=o.path.slice(),t.query="",c=wt;else{if("#"!=a){X(i.slice(f).join(""))||(t.host=o.host,t.path=o.path.slice(),Q(t)),c=mt;continue}t.host=o.host,t.path=o.path.slice(),t.query=o.query,t.fragment="",c=xt}}break;case vt:if("/"==a||"\\"==a){c=gt;break}o&&"file"==o.scheme&&!X(i.slice(f).join(""))&&(K(o.path[0],!0)?t.path.push(o.path[0]):t.host=o.host),c=mt;continue;case gt:if(a==r||"/"==a||"\\"==a||"?"==a||"#"==a){if(!e&&K(p))c=mt;else if(""==p){if(t.host="",e)return;c=yt}else{if(s=L(t,p))return s;if("localhost"==t.host&&(t.host=""),e)return;p="",c=yt}continue}p+=a;break;case yt:if(G(t)){if(c=mt,"/"!=a&&"\\"!=a)continue}else if(e||"?"!=a)if(e||"#"!=a){if(a!=r&&(c=mt,"/"!=a))continue}else t.fragment="",c=xt;else t.query="",c=wt;break;case mt:if(a==r||"/"==a||"\\"==a&&G(t)||!e&&("?"==a||"#"==a)){if(tt(p)?(Q(t),"/"==a||"\\"==a&&G(t)||t.path.push("")):Z(p)?"/"==a||"\\"==a&&G(t)||t.path.push(""):("file"==t.scheme&&!t.path.length&&K(p)&&(t.host&&(t.host=""),p=p.charAt(0)+":"),t.path.push(p)),p="","file"==t.scheme&&(a==r||"?"==a||"#"==a))for(;t.path.length>1&&""===t.path[0];)t.path.shift();"?"==a?(t.query="",c=wt):"#"==a&&(t.fragment="",c=xt)}else p+=H(a,V);break;case bt:"?"==a?(t.query="",c=wt):"#"==a?(t.fragment="",c=xt):a!=r&&(t.path[0]+=H(a,B));break;case wt:e||"#"!=a?a!=r&&("'"==a&&G(t)?t.query+="%27":t.query+="#"==a?"%23":H(a,B)):(t.fragment="",c=xt);break;case xt:a!=r&&(t.fragment+=H(a,z))}f++}},St=function(t){var n,e,r=f(this,St,"URL"),o=arguments.length>1?arguments[1]:void 0,a=String(t),u=O(r,{type:"URL"});if(void 0!==o)if(o instanceof St)n=S(o);else if(e=Ot(n={},String(o)))throw TypeError(e);if(e=Ot(u,a,null,n))throw TypeError(e);var s=u.searchParams=new w,c=x(s);c.updateSearchParams(u.query),c.updateURL=function(){u.query=String(s)||null},i||(r.href=Et.call(r),r.origin=At.call(r),r.protocol=kt.call(r),r.username=Tt.call(r),r.password=Pt.call(r),r.host=Rt.call(r),r.hostname=_t.call(r),r.port=Mt.call(r),r.pathname=It.call(r),r.search=Ct.call(r),r.searchParams=Ft.call(r),r.hash=Nt.call(r))},jt=St.prototype,Et=function(){var t=S(this),n=t.scheme,e=t.username,r=t.password,o=t.host,i=t.port,a=t.path,u=t.query,s=t.fragment,c=n+":";return null!==o?(c+="//",Y(t)&&(c+=e+(r?":"+r:"")+"@"),c+=q(o),null!==i&&(c+=":"+i)):"file"==n&&(c+="//"),c+=t.cannotBeABaseURL?a[0]:a.length?"/"+a.join("/"):"",null!==u&&(c+="?"+u),null!==s&&(c+="#"+s),c},At=function(){var t=S(this),n=t.scheme,e=t.port;if("blob"==n)try{return new URL(n.path[0]).origin}catch(t){return"null"}return"file"!=n&&G(t)?n+"://"+q(t.host)+(null!==e?":"+e:""):"null"},kt=function(){return S(this).scheme+":"},Tt=function(){return S(this).username},Pt=function(){return S(this).password},Rt=function(){var t=S(this),n=t.host,e=t.port;return null===n?"":null===e?q(n):q(n)+":"+e},_t=function(){var t=S(this).host;return null===t?"":q(t)},Mt=function(){var t=S(this).port;return null===t?"":String(t)},It=function(){var t=S(this),n=t.path;return t.cannotBeABaseURL?n[0]:n.length?"/"+n.join("/"):""},Ct=function(){var t=S(this).query;return t?"?"+t:""},Ft=function(){return S(this).searchParams},Nt=function(){var t=S(this).fragment;return t?"#"+t:""},Lt=function(t,n){return{get:t,set:n,configurable:!0,enumerable:!0}};if(i&&s(jt,{href:Lt(Et,(function(t){var n=S(this),e=String(t),r=Ot(n,e);if(r)throw TypeError(r);x(n.searchParams).updateSearchParams(n.query)})),origin:Lt(At),protocol:Lt(kt,(function(t){var n=S(this);Ot(n,String(t)+":",nt)})),username:Lt(Tt,(function(t){var n=S(this),e=h(String(t));if(!J(n)){n.username="";for(var r=0;r<e.length;r++)n.username+=H(e[r],W)}})),password:Lt(Pt,(function(t){var n=S(this),e=h(String(t));if(!J(n)){n.password="";for(var r=0;r<e.length;r++)n.password+=H(e[r],W)}})),host:Lt(Rt,(function(t){var n=S(this);n.cannotBeABaseURL||Ot(n,String(t),lt)})),hostname:Lt(_t,(function(t){var n=S(this);n.cannotBeABaseURL||Ot(n,String(t),pt)})),port:Lt(Mt,(function(t){var n=S(this);J(n)||(""==(t=String(t))?n.port=null:Ot(n,t,ht))})),pathname:Lt(It,(function(t){var n=S(this);n.cannotBeABaseURL||(n.path=[],Ot(n,t+"",yt))})),search:Lt(Ct,(function(t){var n=S(this);""==(t=String(t))?n.query=null:("?"==t.charAt(0)&&(t=t.slice(1)),n.query="",Ot(n,t,wt)),x(n.searchParams).updateSearchParams(n.query)})),searchParams:Lt(Ft),hash:Lt(Nt,(function(t){var n=S(this);""!=(t=String(t))?("#"==t.charAt(0)&&(t=t.slice(1)),n.fragment="",Ot(n,t,xt)):n.fragment=null}))}),c(jt,"toJSON",(function(){return Et.call(this)}),{enumerable:!0}),c(jt,"toString",(function(){return Et.call(this)}),{enumerable:!0}),b){var Dt=b.createObjectURL,Ut=b.revokeObjectURL;Dt&&c(St,"createObjectURL",(function(t){return Dt.apply(b,arguments)})),Ut&&c(St,"revokeObjectURL",(function(t){return Ut.apply(b,arguments)}))}g(St,"URL"),o({global:!0,forced:!a,sham:!i},{URL:St})},function(t,n,e){var r=e(1),o=e(7),i=e(47),a=o("iterator");t.exports=!r((function(){var t=new URL("b?a=1&b=2&c=3","http://a"),n=t.searchParams,e="";return t.pathname="c%20d",n.forEach((function(t,r){n.delete("b"),e+=r+t})),i&&!t.toJSON||!n.sort||"http://a/c%20d?a=1&c=3"!==t.href||"3"!==n.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!n[a]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==e||"x"!==new URL("http://x",void 0).host}))},function(t,n,e){"use strict";e(9);var r=e(0),o=e(42),i=e(262),a=e(25),u=e(82),s=e(48),c=e(153),f=e(29),l=e(62),p=e(17),h=e(58),d=e(98),v=e(4),g=e(3),y=e(51),m=e(56),b=e(455),w=e(97),x=e(7),O=o("fetch"),S=o("Headers"),j=x("iterator"),E=f.set,A=f.getterFor("URLSearchParams"),k=f.getterFor("URLSearchParamsIterator"),T=/\+/g,P=Array(4),R=function(t){return P[t-1]||(P[t-1]=RegExp("((?:%[\\da-f]{2}){"+t+"})","gi"))},_=function(t){try{return decodeURIComponent(t)}catch(n){return t}},M=function(t){var n=t.replace(T," "),e=4;try{return decodeURIComponent(n)}catch(t){for(;e;)n=n.replace(R(e--),_);return n}},I=/[!'()~]|%20/g,C={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},F=function(t){return C[t]},N=function(t){return encodeURIComponent(t).replace(I,F)},L=function(t,n){if(n)for(var e,r,o=n.split("&"),i=0;i<o.length;)(e=o[i++]).length&&(r=e.split("="),t.push({key:M(r.shift()),value:M(r.join("="))}))},D=function(t){this.entries.length=0,L(this.entries,t)},U=function(t,n){if(t<n)throw TypeError("Not enough arguments")},q=c((function(t,n){E(this,{type:"URLSearchParamsIterator",iterator:b(A(t).entries),kind:n})}),"Iterator",(function(){var t=k(this),n=t.kind,e=t.iterator.next(),r=e.value;return e.done||(e.value="keys"===n?r.key:"values"===n?r.value:[r.key,r.value]),e})),B=function(){l(this,B,"URLSearchParams");var t,n,e,r,o,i,a,u,s,c=arguments.length>0?arguments[0]:void 0,f=this,h=[];if(E(f,{type:"URLSearchParams",entries:h,updateURL:function(){},updateSearchParams:D}),void 0!==c)if(g(c))if("function"==typeof(t=w(c)))for(e=(n=t.call(c)).next;!(r=e.call(n)).done;){if((a=(i=(o=b(v(r.value))).next).call(o)).done||(u=i.call(o)).done||!i.call(o).done)throw TypeError("Expected sequence with length 2");h.push({key:a.value+"",value:u.value+""})}else for(s in c)p(c,s)&&h.push({key:s,value:c[s]+""});else L(h,"string"==typeof c?"?"===c.charAt(0)?c.slice(1):c:c+"")},z=B.prototype;u(z,{append:function(t,n){U(arguments.length,2);var e=A(this);e.entries.push({key:t+"",value:n+""}),e.updateURL()},delete:function(t){U(arguments.length,1);for(var n=A(this),e=n.entries,r=t+"",o=0;o<e.length;)e[o].key===r?e.splice(o,1):o++;n.updateURL()},get:function(t){U(arguments.length,1);for(var n=A(this).entries,e=t+"",r=0;r<n.length;r++)if(n[r].key===e)return n[r].value;return null},getAll:function(t){U(arguments.length,1);for(var n=A(this).entries,e=t+"",r=[],o=0;o<n.length;o++)n[o].key===e&&r.push(n[o].value);return r},has:function(t){U(arguments.length,1);for(var n=A(this).entries,e=t+"",r=0;r<n.length;)if(n[r++].key===e)return!0;return!1},set:function(t,n){U(arguments.length,1);for(var e,r=A(this),o=r.entries,i=!1,a=t+"",u=n+"",s=0;s<o.length;s++)(e=o[s]).key===a&&(i?o.splice(s--,1):(i=!0,e.value=u));i||o.push({key:a,value:u}),r.updateURL()},sort:function(){var t,n,e,r=A(this),o=r.entries,i=o.slice();for(o.length=0,e=0;e<i.length;e++){for(t=i[e],n=0;n<e;n++)if(o[n].key>t.key){o.splice(n,0,t);break}n===e&&o.push(t)}r.updateURL()},forEach:function(t){for(var n,e=A(this).entries,r=h(t,arguments.length>1?arguments[1]:void 0,3),o=0;o<e.length;)r((n=e[o++]).value,n.key,this)},keys:function(){return new q(this,"keys")},values:function(){return new q(this,"values")},entries:function(){return new q(this,"entries")}},{enumerable:!0}),a(z,j,z.entries),a(z,"toString",(function(){for(var t,n=A(this).entries,e=[],r=0;r<n.length;)t=n[r++],e.push(N(t.key)+"="+N(t.value));return e.join("&")}),{enumerable:!0}),s(B,"URLSearchParams"),r({global:!0,forced:!i},{URLSearchParams:B}),i||"function"!=typeof O||"function"!=typeof S||r({global:!0,enumerable:!0,forced:!0},{fetch:function(t){var n,e,r,o=[t];return arguments.length>1&&(n=arguments[1],g(n)&&(e=n.body,"URLSearchParams"===d(e)&&((r=n.headers?new S(n.headers):new S).has("content-type")||r.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),n=y(n,{body:m(0,String(e)),headers:m(0,r)}))),o.push(n)),O.apply(this,o)}}),t.exports={URLSearchParams:B,getState:A}},function(t,n,e){var r=e(457),o=e(458),i=e(459),a=e(460),u=e(461);function s(t){var n=-1,e=null==t?0:t.length;for(this.clear();++n<e;){var r=t[n];this.set(r[0],r[1])}}s.prototype.clear=r,s.prototype.delete=o,s.prototype.get=i,s.prototype.has=a,s.prototype.set=u,t.exports=s},function(t,n,e){(function(t){var r=e(126),o=n&&!n.nodeType&&n,i=o&&"object"==typeof t&&t&&!t.nodeType&&t,a=i&&i.exports===o?r.Buffer:void 0,u=a?a.allocUnsafe:void 0;t.exports=function(t,n){if(n)return t.slice();var e=t.length,r=u?u(e):new t.constructor(e);return t.copy(r),r}}).call(this,e(266)(t))},function(t,n){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,n){t.exports=function(t,n){var e=-1,r=t.length;for(n||(n=Array(r));++e<r;)n[e]=t[e];return n}},function(t,n,e){var r=e(476),o=e(269),i=e(477);t.exports=function(t){return"function"!=typeof t.constructor||i(t)?{}:r(o(t))}},function(t,n,e){var r=e(173)(Object.getPrototypeOf,Object);t.exports=r},function(t,n){t.exports=function(){return!1}},function(t,n,e){var r=e(272),o=e(486),i=e(83);t.exports=function(t,n,e){for(var a=-1,u=n.length,s={};++a<u;){var c=n[a],f=r(t,c);e(f,c)&&o(s,i(c,t),f)}return s}},function(t,n,e){var r=e(83),o=e(127);t.exports=function(t,n){for(var e=0,i=(n=r(n,t)).length;null!=t&&e<i;)t=t[o(n[e++])];return e&&e==i?t:void 0}},function(t,n){t.exports=function(){return!1}},function(t,n){var e=/^(?:0|[1-9]\d*)$/;t.exports=function(t,n){var r=typeof t;return!!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&e.test(t))&&t>-1&&t%1==0&&t<n}},function(t,n){t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}},function(t,n,e){var r=e(104),o=e(277),i=e(279);t.exports=function(t){return i(o(t,void 0,r),t+"")}},function(t,n,e){var r=e(278),o=Math.max;t.exports=function(t,n,e){return n=o(void 0===n?t.length-1:n,0),function(){for(var i=arguments,a=-1,u=o(i.length-n,0),s=Array(u);++a<u;)s[a]=i[n+a];a=-1;for(var c=Array(n+1);++a<n;)c[a]=i[a];return c[n]=e(s),r(t,this,c)}}},function(t,n){t.exports=function(t,n,e){switch(e.length){case 0:return t.call(n);case 1:return t.call(n,e[0]);case 2:return t.call(n,e[0],e[1]);case 3:return t.call(n,e[0],e[1],e[2])}return t.apply(n,e)}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(t,n,e){for(var r=e-1,o=t.length;++r<o;)if(t[r]===n)return r;return-1}},function(t,n,e){var r=e(179),o=e(180),i=e(181),a=e(71),u=e(183),s=e(182);t.exports=function(t,n,e,c){var f=-1,l=o,p=!0,h=t.length,d=[],v=n.length;if(!h)return d;e&&(n=a(n,u(e))),c?(l=i,p=!1):n.length>=200&&(l=s,p=!1,n=new r(n));t:for(;++f<h;){var g=t[f],y=null==e?g:e(g);if(g=c||0!==g?g:0,p&&y==y){for(var m=v;m--;)if(n[m]===y)continue t;d.push(g)}else l(n,y,c)||d.push(g)}return d}},function(t,n){(function(n){t.exports=n}).call(this,{})},function(t,n,e){var r=e(171),o=e(124);t.exports=function(t,n,e){(void 0===e||o(t[n],e))&&(void 0!==e||n in t)||r(t,n,e)}},function(t,n){t.exports=function(t,n){if(("constructor"!==n||"function"!=typeof t[n])&&"__proto__"!=n)return t[n]}},function(t,n,e){var r=e(84),o=e(131);t.exports=function(t){return r((function(n,e){var r=-1,i=e.length,a=i>1?e[i-1]:void 0,u=i>2?e[2]:void 0;for(a=t.length>3&&"function"==typeof a?(i--,a):void 0,u&&o(e[0],e[1],u)&&(a=i<3?void 0:a,i=1),n=Object(n);++r<i;){var s=e[r];s&&t(n,s,r,a)}return n}))}},function(t,n){t.exports=function(t){return t}},function(t,n,e){var r=e(129),o=e(130),i=e(72);t.exports=function(t){if(!o(t))return!1;var n=r(t);return"[object Error]"==n||"[object DOMException]"==n||"string"==typeof t.message&&"string"==typeof t.name&&!i(t)}},function(t,n){t.exports=/<%=([\s\S]+?)%>/g},function(t,n,e){var r=e(169);t.exports=function(t,n){return r(t,5,n="function"==typeof n?n:void 0)}},function(t,n,e){t.exports=e(480)},function(t,n,e){var r=e(175),o=e(481),i=e(482);t.exports=function(t,n){return i(t,o(r(n)))}},function(t,n,e){var r=e(494);t.exports=function(t){return t&&t.length?r(t):[]}},function(t,n,e){var r=e(71),o=e(497),i=e(84),a=e(498),u=i((function(t){var n=r(t,a);return n.length&&n[0]===t[0]?o(n):[]}));t.exports=u},function(t,n,e){var r=e(281),o=e(178),i=e(84),a=e(128),u=i((function(t,n){return a(t)?r(t,o(n,1,a,!0)):[]}));t.exports=u},function(t,n,e){var r,o=o||function(t){"use strict";if(!(void 0===t||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var n=t.document,e=function(){return t.URL||t.webkitURL||t},r=n.createElementNS("http://www.w3.org/1999/xhtml","a"),o="download"in r,i=/constructor/i.test(t.HTMLElement)||t.safari,a=/CriOS\/[\d]+/.test(navigator.userAgent),u=function(n){(t.setImmediate||t.setTimeout)((function(){throw n}),0)},s=function(t){setTimeout((function(){"string"==typeof t?e().revokeObjectURL(t):t.remove()}),4e4)},c=function(t){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob([String.fromCharCode(65279),t],{type:t.type}):t},f=function(n,f,l){l||(n=c(n));var p,h=this,d="application/octet-stream"===n.type,v=function(){!function(t,n,e){for(var r=(n=[].concat(n)).length;r--;){var o=t["on"+n[r]];if("function"==typeof o)try{o.call(t,e||t)}catch(t){u(t)}}}(h,"writestart progress write writeend".split(" "))};if(h.readyState=h.INIT,o)return p=e().createObjectURL(n),void setTimeout((function(){r.href=p,r.download=f,function(t){var n=new MouseEvent("click");t.dispatchEvent(n)}(r),v(),s(p),h.readyState=h.DONE}));!function(){if((a||d&&i)&&t.FileReader){var r=new FileReader;return r.onloadend=function(){var n=a?r.result:r.result.replace(/^data:[^;]*;/,"data:attachment/file;");t.open(n,"_blank")||(t.location.href=n),n=void 0,h.readyState=h.DONE,v()},r.readAsDataURL(n),void(h.readyState=h.INIT)}(p||(p=e().createObjectURL(n)),d)?t.location.href=p:t.open(p,"_blank")||(t.location.href=p);h.readyState=h.DONE,v(),s(p)}()},l=f.prototype;return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(t,n,e){return n=n||t.name||"download",e||(t=c(t)),navigator.msSaveOrOpenBlob(t,n)}:(l.abort=function(){},l.readyState=l.INIT=0,l.WRITING=1,l.DONE=2,l.error=l.onwritestart=l.onprogress=l.onwrite=l.onabort=l.onerror=l.onwriteend=null,function(t,n,e){return new f(t,n||t.name||"download",e)})}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);t.exports?t.exports.saveAs=o:null!==e(185)&&null!==e(282)&&(void 0===(r=function(){return o}.call(n,e,n,t))||(t.exports=r))},function(t,n,e){var r=e(281),o=e(84),i=e(128),a=o((function(t,n){return i(t)?r(t,n):[]}));t.exports=a},function(t,n,e){var r=e(178),o=e(505),i=e(84),a=e(131),u=i((function(t,n){if(null==t)return[];var e=n.length;return e>1&&a(t,n[0],n[1])?n=[]:e>2&&a(n[0],n[1],n[2])&&(n=[n[0]]),o(t,r(n,1),[])}));t.exports=u},function(t,n,e){var r=e(511),o=e(285)((function(t,n,e){r(t,n,e)}));t.exports=o},function(t,n,e){var r=e(523),o=e(286);t.exports=function(t,n,e){return void 0===e&&(e=n,n=void 0),void 0!==e&&(e=(e=o(e))==e?e:0),void 0!==n&&(n=(n=o(n))==n?n:0),r(o(t),n,e)}},function(t,n,e){(function(t){var r;!function(t,o,i){function a(t){var n=this,e=function(){var t=4022871197;return function(n){n=String(n);for(var e=0;e<n.length;e++){var r=.02519603282416938*(t+=n.charCodeAt(e));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)}}();n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=e(" "),n.s1=e(" "),n.s2=e(" "),n.s0-=e(t),n.s0<0&&(n.s0+=1),n.s1-=e(t),n.s1<0&&(n.s1+=1),n.s2-=e(t),n.s2<0&&(n.s2+=1),e=null}function u(t,n){return n.c=t.c,n.s0=t.s0,n.s1=t.s1,n.s2=t.s2,n}function s(t,n){var e=new a(t),r=n&&n.state,o=e.next;return o.int32=function(){return 4294967296*e.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,r&&("object"==typeof r&&u(r,e),o.state=function(){return u(e,{})}),o}o&&o.exports?o.exports=s:e(185)&&e(282)?void 0===(r=function(){return s}.call(n,e,n,o))||(o.exports=r):this.alea=s}(0,t,e(185))}).call(this,e(266)(t))},function(t,n,e){var r=e(524),o=e(525),i=e(526),a=e(527),u=e(528),s=e(287),c=e(131),f=e(172),l=e(288),p=e(529),h=e(176),d=/\b__p \+= '';/g,v=/\b(__p \+=) '' \+/g,g=/(__e\(.*?\)|\b__t\)) \+\n'';/g,y=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,m=/($^)/,b=/['\n\r\u2028\u2029\\]/g,w=Object.prototype.hasOwnProperty;t.exports=function(t,n,e){var x=p.imports._.templateSettings||p;e&&c(t,n,e)&&(n=void 0),t=h(t),n=r({},n,x,a);var O,S,j=r({},n.imports,x.imports,a),E=f(j),A=i(j,E),k=0,T=n.interpolate||m,P="__p += '",R=RegExp((n.escape||m).source+"|"+T.source+"|"+(T===l?y:m).source+"|"+(n.evaluate||m).source+"|$","g"),_=w.call(n,"sourceURL")?"//# sourceURL="+(n.sourceURL+"").replace(/[\r\n]/g," ")+"\n":"";t.replace(R,(function(n,e,r,o,i,a){return r||(r=o),P+=t.slice(k,a).replace(b,u),e&&(O=!0,P+="' +\n__e("+e+") +\n'"),i&&(S=!0,P+="';\n"+i+";\n__p += '"),r&&(P+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),k=a+n.length,n})),P+="';\n";var M=w.call(n,"variable")&&n.variable;M||(P="with (obj) {\n"+P+"\n}\n"),P=(S?P.replace(d,""):P).replace(v,"$1").replace(g,"$1;"),P="function("+(M||"obj")+") {\n"+(M?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(O?", __e = _.escape":"")+(S?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+P+"return __p\n}";var I=o((function(){return Function(E,_+"return "+P).apply(void 0,A)}));if(I.source=P,s(I))throw I;return I}},function(t,n,e){var r=e(129),o=e(45),i=e(130);t.exports=function(t){return"string"==typeof t||!o(t)&&i(t)&&"[object String]"==r(t)}},function(t,n,e){"use strict";(function(t){e(16),e(19),e(20),e(22),e(33),e(9),e(18),e(61),e(68),e(11),e(44),e(26),e(12),e(69),e(23),e(13);var r=e(85),o=e.n(r),i=e(30),a=e.n(i);function u(t){return function(t){if(Array.isArray(t))return t}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var s=function(t,n){return t.reduce((function(t,n){return t[n]}),n)},fromObject=function(t,n){return c(o()(t),n)},c=function(n,e){var r=e||window.lab;if(void 0===r)throw new Error("Couldn't find library in global scope, and no root object available");var o=u(n.type.split(".")).slice(1),i=s(o,r);return i.metadata.nestedComponents.forEach((function(t){n[t]&&(Array.isArray(n[t])?n[t]=n[t].map((function(t){return fromObject(t,r)})):a()(n[t])&&(n[t]=fromObject(n[t],r)))})),n.plugins&&(n.plugins=n.plugins.map((function(n){try{var e=u((n.path||n.type).split(".")),o=e[0],i=e.slice(1);return new(s(i,"global"===o?t||window:r))(n)}catch(t){throw new Error("Couldn't instantiate plugin ".concat(n.type,". ")+"Error: ".concat(t.message))}}))),new i(n)};n.a=fromObject}).call(this,e(134))},function(t,n,e){var r=e(537),o=e(30);t.exports=function(t,n,e){var i=!0,a=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return o(e)&&(i="leading"in e?!!e.leading:i,a="trailing"in e?!!e.trailing:a),r(t,n,{leading:i,maxWait:n,trailing:a})}},function(t,n,e){t.exports=e(539)},function(t,n,e){e(307),e(450);var r=e(89);t.exports=r},function(t,n,e){e(16),e(308),e(19),e(309),e(310),e(20),e(311),e(312),e(313),e(314),e(315),e(316),e(317),e(318),e(319),e(74),e(320),e(321),e(322),e(94),e(144),e(323),e(35),e(324),e(325),e(49),e(326),e(327),e(328),e(329),e(36),e(330),e(331),e(59),e(332),e(11),e(334),e(335),e(336),e(337),e(338),e(99),e(339),e(340),e(33),e(341),e(342),e(15),e(343),e(149),e(150),e(37),e(344),e(345),e(346),e(347),e(22),e(77),e(207),e(78),e(348),e(18),e(61),e(349),e(350),e(68),e(351),e(352),e(353),e(354),e(355),e(356),e(9),e(357),e(358),e(359),e(360),e(101),e(361),e(362),e(363),e(211),e(212),e(80),e(213),e(69),e(158),e(159),e(364),e(365),e(12),e(366),e(367),e(368),e(369),e(370),e(371),e(372),e(373),e(374),e(375),e(376),e(377),e(378),e(214),e(44),e(379),e(380),e(381),e(26),e(382),e(383),e(161),e(384),e(385),e(387),e(388),e(389),e(390),e(391),e(392),e(393),e(218),e(394),e(395),e(396),e(397),e(398),e(399),e(400),e(401),e(402),e(404),e(405),e(406),e(407),e(408),e(409),e(410),e(411),e(412),e(413),e(414),e(415),e(416),e(418),e(419),e(421),e(422),e(40),e(424),e(226),e(227),e(229),e(230),e(425),e(426),e(428),e(233),e(429),e(430),e(236),e(432),e(433),e(434),e(435),e(436),e(437),e(438),e(439),e(440),e(237),e(238),e(239),e(240),e(241),e(242),e(243),e(244),e(245),e(246),e(247),e(248),e(249),e(250),e(251),e(252),e(253),e(254),e(255),e(256),e(257),e(258),e(259),e(441),e(442),e(443),e(444),e(103),e(166),e(445),e(167),e(446),e(168),e(447),e(448),e(449);var r=e(89);t.exports=r},function(t,n,e){e(31)("asyncIterator")},function(t,n,e){e(31)("hasInstance")},function(t,n,e){e(31)("isConcatSpreadable")},function(t,n,e){e(31)("match")},function(t,n,e){e(31)("matchAll")},function(t,n,e){e(31)("replace")},function(t,n,e){e(31)("search")},function(t,n,e){e(31)("species")},function(t,n,e){e(31)("split")},function(t,n,e){e(31)("toPrimitive")},function(t,n,e){e(31)("toStringTag")},function(t,n,e){e(31)("unscopables")},function(t,n,e){e(0)({target:"Object",stat:!0,sham:!e(5)},{create:e(51)})},function(t,n,e){var r=e(0),o=e(5);r({target:"Object",stat:!0,forced:!o,sham:!o},{defineProperty:e(10).f})},function(t,n,e){var r=e(0),o=e(5);r({target:"Object",stat:!0,forced:!o,sham:!o},{defineProperties:e(143)})},function(t,n,e){var r=e(0),o=e(75),i=e(67);r({target:"Object",stat:!0},{fromEntries:function(t){var n={};return o(t,(function(t,e){i(n,t,e)}),void 0,!0),n}})},function(t,n,e){var r=e(0),o=e(5),i=e(139),a=e(34),u=e(24),s=e(67);r({target:"Object",stat:!0,sham:!o},{getOwnPropertyDescriptors:function(t){for(var n,e,r=a(t),o=u.f,c=i(r),f={},l=0;c.length>l;)void 0!==(e=o(r,n=c[l++]))&&s(f,n,e);return f}})},function(t,n,e){var r=e(0),o=e(1),i=e(195).f;r({target:"Object",stat:!0,forced:o((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:i})},function(t,n,e){e(0)({target:"Object",stat:!0},{is:e(200)})},function(t,n,e){var r=e(0),o=e(1),i=e(3),a=Object.isExtensible;r({target:"Object",stat:!0,forced:o((function(){a(1)}))},{isExtensible:function(t){return!!i(t)&&(!a||a(t))}})},function(t,n,e){var r=e(0),o=e(1),i=e(3),a=Object.isFrozen;r({target:"Object",stat:!0,forced:o((function(){a(1)}))},{isFrozen:function(t){return!i(t)||!!a&&a(t)}})},function(t,n,e){var r=e(0),o=e(1),i=e(3),a=Object.isSealed;r({target:"Object",stat:!0,forced:o((function(){a(1)}))},{isSealed:function(t){return!i(t)||!!a&&a(t)}})},function(t,n,e){var r=e(0),o=e(3),i=e(66).onFreeze,a=e(95),u=e(1),s=Object.preventExtensions;r({target:"Object",stat:!0,forced:u((function(){s(1)})),sham:!a},{preventExtensions:function(t){return s&&o(t)?s(i(t)):t}})},function(t,n,e){var r=e(0),o=e(3),i=e(66).onFreeze,a=e(95),u=e(1),s=Object.seal;r({target:"Object",stat:!0,forced:u((function(){s(1)})),sham:!a},{seal:function(t){return s&&o(t)?s(i(t)):t}})},function(t,n,e){var r=e(0),o=e(198).values;r({target:"Object",stat:!0},{values:function(t){return o(t)}})},function(t,n,e){"use strict";var r=e(146),o=e(98);t.exports=r?{}.toString:function(){return"[object "+o(this)+"]"}},function(t,n,e){"use strict";var r=e(0),o=e(5),i=e(107),a=e(14),u=e(32),s=e(10);o&&r({target:"Object",proto:!0,forced:i},{__defineGetter__:function(t,n){s.f(a(this),t,{get:u(n),enumerable:!0,configurable:!0})}})},function(t,n,e){"use strict";var r=e(0),o=e(5),i=e(107),a=e(14),u=e(32),s=e(10);o&&r({target:"Object",proto:!0,forced:i},{__defineSetter__:function(t,n){s.f(a(this),t,{set:u(n),enumerable:!0,configurable:!0})}})},function(t,n,e){"use strict";var r=e(0),o=e(5),i=e(107),a=e(14),u=e(46),s=e(50),c=e(24).f;o&&r({target:"Object",proto:!0,forced:i},{__lookupGetter__:function(t){var n,e=a(this),r=u(t,!0);do{if(n=c(e,r))return n.get}while(e=s(e))}})},function(t,n,e){"use strict";var r=e(0),o=e(5),i=e(107),a=e(14),u=e(46),s=e(50),c=e(24).f;o&&r({target:"Object",proto:!0,forced:i},{__lookupSetter__:function(t){var n,e=a(this),r=u(t,!0);do{if(n=c(e,r))return n.set}while(e=s(e))}})},function(t,n,e){e(0)({target:"Function",proto:!0},{bind:e(202)})},function(t,n,e){"use strict";var r=e(3),o=e(10),i=e(50),a=e(7)("hasInstance"),u=Function.prototype;a in u||o.f(u,a,{value:function(t){if("function"!=typeof this||!r(t))return!1;if(!r(this.prototype))return t instanceof this;for(;t=i(t);)if(this.prototype===t)return!0;return!1}})},function(t,n,e){e(0)({global:!0},{globalThis:e(2)})},function(t,n,e){e(0)({target:"Array",stat:!0},{isArray:e(65)})},function(t,n,e){"use strict";var r=e(0),o=e(1),i=e(67);r({target:"Array",stat:!0,forced:o((function(){function t(){}return!(Array.of.call(t)instanceof t)}))},{of:function(){for(var t=0,n=arguments.length,e=new("function"==typeof this?this:Array)(n);n>t;)i(e,t,arguments[t++]);return e.length=n,e}})},function(t,n,e){var r=e(0),o=e(204),i=e(60);r({target:"Array",proto:!0},{copyWithin:o}),i("copyWithin")},function(t,n,e){"use strict";var r=e(0),o=e(21).find,i=e(60),a=!0;"find"in[]&&Array(1).find((function(){a=!1})),r({target:"Array",proto:!0,forced:a},{find:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("find")},function(t,n,e){"use strict";var r=e(0),o=e(21).findIndex,i=e(60),a=!0;"findIndex"in[]&&Array(1).findIndex((function(){a=!1})),r({target:"Array",proto:!0,forced:a},{findIndex:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("findIndex")},function(t,n,e){"use strict";var r=e(0),o=e(205),i=e(14),a=e(8),u=e(43),s=e(93);r({target:"Array",proto:!0},{flat:function(){var t=arguments.length?arguments[0]:void 0,n=i(this),e=a(n.length),r=s(n,0);return r.length=o(r,n,n,e,0,void 0===t?1:u(t)),r}})},function(t,n,e){"use strict";var r=e(0),o=e(205),i=e(14),a=e(8),u=e(32),s=e(93);r({target:"Array",proto:!0},{flatMap:function(t){var n,e=i(this),r=a(e.length);return u(t),(n=s(e,0)).length=o(n,e,e,r,0,1,t,arguments.length>1?arguments[1]:void 0),n}})},function(t,n,e){var r=e(0),o=e(208);r({target:"Array",proto:!0,forced:o!==[].lastIndexOf},{lastIndexOf:o})},function(t,n,e){"use strict";var r=e(0),o=e(110).right;r({target:"Array",proto:!0,forced:e(52)("reduceRight")},{reduceRight:function(t){return o(this,t,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(0),o=e(65),i=[].reverse,a=[1,2];r({target:"Array",proto:!0,forced:String(a)===String(a.reverse())},{reverse:function(){return o(this)&&(this.length=this.length),i.call(this)}})},function(t,n,e){"use strict";var r=e(0),o=e(21).some;r({target:"Array",proto:!0,forced:e(52)("some")},{some:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(0),o=e(32),i=e(14),a=e(1),u=e(52),s=[],c=s.sort,f=a((function(){s.sort(void 0)})),l=a((function(){s.sort(null)})),p=u("sort");r({target:"Array",proto:!0,forced:f||!l||p},{sort:function(t){return void 0===t?c.call(i(this)):c.call(i(this),o(t))}})},function(t,n,e){"use strict";var r=e(0),o=e(57),i=e(43),a=e(8),u=e(14),s=e(93),c=e(67),f=e(100),l=Math.max,p=Math.min;r({target:"Array",proto:!0,forced:!f("splice")},{splice:function(t,n){var e,r,f,h,d,v,g=u(this),y=a(g.length),m=o(t,y),b=arguments.length;if(0===b?e=r=0:1===b?(e=0,r=y-m):(e=b-2,r=p(l(i(n),0),y-m)),y+e-r>9007199254740991)throw TypeError("Maximum allowed length exceeded");for(f=s(g,r),h=0;h<r;h++)(d=m+h)in g&&c(f,h,g[d]);if(f.length=r,e<r){for(h=m;h<y-r;h++)v=h+e,(d=h+r)in g?g[v]=g[d]:delete g[v];for(h=y;h>y-r+e;h--)delete g[h-1]}else if(e>r)for(h=y-r;h>m;h--)v=h+e-1,(d=h+r-1)in g?g[v]=g[d]:delete g[v];for(h=0;h<e;h++)g[h+m]=arguments[h+2];return g.length=y-r+e,f}})},function(t,n,e){e(79)("Array")},function(t,n,e){e(60)("flat")},function(t,n,e){e(60)("flatMap")},function(t,n,e){var r=e(0),o=e(57),i=String.fromCharCode,a=String.fromCodePoint;r({target:"String",stat:!0,forced:!!a&&1!=a.length},{fromCodePoint:function(t){for(var n,e=[],r=arguments.length,a=0;r>a;){if(n=+arguments[a++],o(n,1114111)!==n)throw RangeError(n+" is not a valid code point");e.push(n<65536?i(n):i(55296+((n-=65536)>>10),n%1024+56320))}return e.join("")}})},function(t,n,e){var r=e(0),o=e(34),i=e(8);r({target:"String",stat:!0},{raw:function(t){for(var n=o(t.raw),e=i(n.length),r=arguments.length,a=[],u=0;e>u;)a.push(String(n[u++])),u<r&&a.push(String(arguments[u]));return a.join("")}})},function(t,n,e){"use strict";var r=e(0),o=e(111).codeAt;r({target:"String",proto:!0},{codePointAt:function(t){return o(this,t)}})},function(t,n,e){"use strict";var r=e(0),o=e(24).f,i=e(8),a=e(154),u=e(27),s=e(155),c=e(47),f="".endsWith,l=Math.min,p=s("endsWith");r({target:"String",proto:!0,forced:!(!c&&!p&&!!function(){var t=o(String.prototype,"endsWith");return t&&!t.writable}())&&!p},{endsWith:function(t){var n=String(u(this));a(t);var e=arguments.length>1?arguments[1]:void 0,r=i(n.length),o=void 0===e?r:l(i(e),r),s=String(t);return f?f.call(n,s,o):n.slice(o-s.length,o)===s}})},function(t,n,e){"use strict";var r=e(113),o=e(4),i=e(8),a=e(27),u=e(116),s=e(117);r("match",1,(function(t,n,e){return[function(n){var e=a(this),r=null==n?void 0:n[t];return void 0!==r?r.call(n,e):new RegExp(n)[t](String(e))},function(t){var r=e(n,t,this);if(r.done)return r.value;var a=o(t),c=String(this);if(!a.global)return s(a,c);var f=a.unicode;a.lastIndex=0;for(var l,p=[],h=0;null!==(l=s(a,c));){var d=String(l[0]);p[h]=d,""===d&&(a.lastIndex=u(c,i(a.lastIndex),f)),h++}return 0===h?null:p}]}))},function(t,n,e){"use strict";var r=e(0),o=e(153),i=e(27),a=e(8),u=e(32),s=e(4),c=e(41),f=e(112),l=e(102),p=e(28),h=e(1),d=e(7),v=e(53),g=e(116),y=e(29),m=e(47),b=d("matchAll"),w=y.set,x=y.getterFor("RegExp String Iterator"),O=RegExp.prototype,S=O.exec,j="".matchAll,E=!!j&&!h((function(){"a".matchAll(/./)})),A=o((function(t,n,e,r){w(this,{type:"RegExp String Iterator",regexp:t,string:n,global:e,unicode:r,done:!1})}),"RegExp String",(function(){var t=x(this);if(t.done)return{value:void 0,done:!0};var n=t.regexp,e=t.string,r=function(t,n){var e,r=t.exec;if("function"==typeof r){if("object"!=typeof(e=r.call(t,n)))throw TypeError("Incorrect exec result");return e}return S.call(t,n)}(n,e);return null===r?{value:void 0,done:t.done=!0}:t.global?(""==String(r[0])&&(n.lastIndex=g(e,a(n.lastIndex),t.unicode)),{value:r,done:!1}):(t.done=!0,{value:r,done:!1})})),k=function(t){var n,e,r,o,i,u,c=s(this),f=String(t);return n=v(c,RegExp),void 0===(e=c.flags)&&c instanceof RegExp&&!("flags"in O)&&(e=l.call(c)),r=void 0===e?"":String(e),o=new n(n===RegExp?c.source:c,r),i=!!~r.indexOf("g"),u=!!~r.indexOf("u"),o.lastIndex=a(c.lastIndex),new A(o,f,i,u)};r({target:"String",proto:!0,forced:E},{matchAll:function(t){var n,e,r,o=i(this);if(null!=t){if(f(t)&&!~String(i("flags"in O?t.flags:l.call(t))).indexOf("g"))throw TypeError("`.matchAll` does not allow non-global regexes");if(E)return j.apply(o,arguments);if(void 0===(e=t[b])&&m&&"RegExp"==c(t)&&(e=k),null!=e)return u(e).call(t,o)}else if(E)return j.apply(o,arguments);return n=String(o),r=new RegExp(t,"g"),m?k.call(r,n):r[b](n)}}),m||b in O||p(O,b,k)},function(t,n,e){"use strict";var r=e(0),o=e(156).end;r({target:"String",proto:!0,forced:e(210)},{padEnd:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,n,e){"use strict";var r=e(0),o=e(81).start,i=e(160)("trimStart"),a=i?function(){return o(this)}:"".trimStart;r({target:"String",proto:!0,forced:i},{trimStart:a,trimLeft:a})},function(t,n,e){"use strict";var r=e(0),o=e(81).end,i=e(160)("trimEnd"),a=i?function(){return o(this)}:"".trimEnd;r({target:"String",proto:!0,forced:i},{trimEnd:a,trimRight:a})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("anchor")},{anchor:function(t){return o(this,"a","name",t)}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("big")},{big:function(){return o(this,"big","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("blink")},{blink:function(){return o(this,"blink","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("bold")},{bold:function(){return o(this,"b","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("fixed")},{fixed:function(){return o(this,"tt","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("fontcolor")},{fontcolor:function(t){return o(this,"font","color",t)}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("fontsize")},{fontsize:function(t){return o(this,"font","size",t)}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("italics")},{italics:function(){return o(this,"i","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("link")},{link:function(t){return o(this,"a","href",t)}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("small")},{small:function(){return o(this,"small","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("strike")},{strike:function(){return o(this,"strike","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("sub")},{sub:function(){return o(this,"sub","","")}})},function(t,n,e){"use strict";var r=e(0),o=e(38);r({target:"String",proto:!0,forced:e(39)("sup")},{sup:function(){return o(this,"sup","","")}})},function(t,n,e){var r=e(5),o=e(10),i=e(102),a=e(115).UNSUPPORTED_Y;r&&("g"!=/./g.flags||a)&&o.f(RegExp.prototype,"flags",{configurable:!0,get:i})},function(t,n,e){var r=e(5),o=e(115).UNSUPPORTED_Y,i=e(10).f,a=e(29).get,u=RegExp.prototype;r&&o&&i(RegExp.prototype,"sticky",{configurable:!0,get:function(){if(this!==u){if(this instanceof RegExp)return!!a(this).sticky;throw TypeError("Incompatible receiver, RegExp required")}}})},function(t,n,e){"use strict";var r=e(0),o=e(3),i=function(){var t=!1,n=/[ac]/;return n.exec=function(){return t=!0,/./.exec.apply(this,arguments)},!0===n.test("abc")&&t}(),a=/./.test;r({target:"RegExp",proto:!0,forced:!i},{test:function(t){if("function"!=typeof this.exec)return a.call(this,t);var n=this.exec(t);if(null!==n&&!o(n))throw new Error("RegExp exec method returned something other than an Object or null");return!!n}})},function(t,n,e){var r=e(0),o=e(215);r({global:!0,forced:parseInt!=o},{parseInt:o})},function(t,n,e){var r=e(0),o=e(216);r({global:!0,forced:parseFloat!=o},{parseFloat:o})},function(t,n,e){e(0)({target:"Number",stat:!0},{EPSILON:Math.pow(2,-52)})},function(t,n,e){e(0)({target:"Number",stat:!0},{isFinite:e(386)})},function(t,n,e){var r=e(2).isFinite;t.exports=Number.isFinite||function(t){return"number"==typeof t&&r(t)}},function(t,n,e){e(0)({target:"Number",stat:!0},{isInteger:e(217)})},function(t,n,e){e(0)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},function(t,n,e){var r=e(0),o=e(217),i=Math.abs;r({target:"Number",stat:!0},{isSafeInteger:function(t){return o(t)&&i(t)<=9007199254740991}})},function(t,n,e){e(0)({target:"Number",stat:!0},{MAX_SAFE_INTEGER:9007199254740991})},function(t,n,e){e(0)({target:"Number",stat:!0},{MIN_SAFE_INTEGER:-9007199254740991})},function(t,n,e){var r=e(0),o=e(216);r({target:"Number",stat:!0,forced:Number.parseFloat!=o},{parseFloat:o})},function(t,n,e){var r=e(0),o=e(215);r({target:"Number",stat:!0,forced:Number.parseInt!=o},{parseInt:o})},function(t,n,e){"use strict";var r=e(0),o=e(1),i=e(219),a=1..toPrecision;r({target:"Number",proto:!0,forced:o((function(){return"1"!==a.call(1,void 0)}))||!o((function(){a.call({})}))},{toPrecision:function(t){return void 0===t?a.call(i(this)):a.call(i(this),t)}})},function(t,n,e){var r=e(0),o=e(220),i=Math.acosh,a=Math.log,u=Math.sqrt,s=Math.LN2;r({target:"Math",stat:!0,forced:!i||710!=Math.floor(i(Number.MAX_VALUE))||i(1/0)!=1/0},{acosh:function(t){return(t=+t)<1?NaN:t>94906265.62425156?a(t)+s:o(t-1+u(t-1)*u(t+1))}})},function(t,n,e){var r=e(0),o=Math.asinh,i=Math.log,a=Math.sqrt;r({target:"Math",stat:!0,forced:!(o&&1/o(0)>0)},{asinh:function t(n){return isFinite(n=+n)&&0!=n?n<0?-t(-n):i(n+a(n*n+1)):n}})},function(t,n,e){var r=e(0),o=Math.atanh,i=Math.log;r({target:"Math",stat:!0,forced:!(o&&1/o(-0)<0)},{atanh:function(t){return 0==(t=+t)?t:i((1+t)/(1-t))/2}})},function(t,n,e){var r=e(0),o=e(162),i=Math.abs,a=Math.pow;r({target:"Math",stat:!0},{cbrt:function(t){return o(t=+t)*a(i(t),1/3)}})},function(t,n,e){var r=e(0),o=Math.floor,i=Math.log,a=Math.LOG2E;r({target:"Math",stat:!0},{clz32:function(t){return(t>>>=0)?31-o(i(t+.5)*a):32}})},function(t,n,e){var r=e(0),o=e(120),i=Math.cosh,a=Math.abs,u=Math.E;r({target:"Math",stat:!0,forced:!i||i(710)===1/0},{cosh:function(t){var n=o(a(t)-1)+1;return(n+1/(n*u*u))*(u/2)}})},function(t,n,e){var r=e(0),o=e(120);r({target:"Math",stat:!0,forced:o!=Math.expm1},{expm1:o})},function(t,n,e){e(0)({target:"Math",stat:!0},{fround:e(403)})},function(t,n,e){var r=e(162),o=Math.abs,i=Math.pow,a=i(2,-52),u=i(2,-23),s=i(2,127)*(2-u),c=i(2,-126);t.exports=Math.fround||function(t){var n,e,i=o(t),f=r(t);return i<c?f*function(t){return t+1/a-1/a}(i/c/u)*c*u:(e=(n=(1+u/a)*i)-(n-i))>s||e!=e?f*(1/0):f*e}},function(t,n,e){var r=e(0),o=Math.hypot,i=Math.abs,a=Math.sqrt;r({target:"Math",stat:!0,forced:!!o&&o(1/0,NaN)!==1/0},{hypot:function(t,n){for(var e,r,o=0,u=0,s=arguments.length,c=0;u<s;)c<(e=i(arguments[u++]))?(o=o*(r=c/e)*r+1,c=e):o+=e>0?(r=e/c)*r:e;return c===1/0?1/0:c*a(o)}})},function(t,n,e){var r=e(0),o=e(1),i=Math.imul;r({target:"Math",stat:!0,forced:o((function(){return-5!=i(4294967295,5)||2!=i.length}))},{imul:function(t,n){var e=+t,r=+n,o=65535&e,i=65535&r;return 0|o*i+((65535&e>>>16)*i+o*(65535&r>>>16)<<16>>>0)}})},function(t,n,e){var r=e(0),o=Math.log,i=Math.LOG10E;r({target:"Math",stat:!0},{log10:function(t){return o(t)*i}})},function(t,n,e){e(0)({target:"Math",stat:!0},{log1p:e(220)})},function(t,n,e){var r=e(0),o=Math.log,i=Math.LN2;r({target:"Math",stat:!0},{log2:function(t){return o(t)/i}})},function(t,n,e){e(0)({target:"Math",stat:!0},{sign:e(162)})},function(t,n,e){var r=e(0),o=e(1),i=e(120),a=Math.abs,u=Math.exp,s=Math.E;r({target:"Math",stat:!0,forced:o((function(){return-2e-17!=Math.sinh(-2e-17)}))},{sinh:function(t){return a(t=+t)<1?(i(t)-i(-t))/2:(u(t-1)-u(-t-1))*(s/2)}})},function(t,n,e){var r=e(0),o=e(120),i=Math.exp;r({target:"Math",stat:!0},{tanh:function(t){var n=o(t=+t),e=o(-t);return n==1/0?1:e==1/0?-1:(n-e)/(i(t)+i(-t))}})},function(t,n,e){e(48)(Math,"Math",!0)},function(t,n,e){var r=e(0),o=Math.ceil,i=Math.floor;r({target:"Math",stat:!0},{trunc:function(t){return(t>0?i:o)(t)}})},function(t,n,e){e(0)({target:"Date",stat:!0},{now:function(){return(new Date).getTime()}})},function(t,n,e){"use strict";var r=e(0),o=e(1),i=e(14),a=e(46);r({target:"Date",proto:!0,forced:o((function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}))},{toJSON:function(t){var n=i(this),e=a(n);return"number"!=typeof e||isFinite(e)?n.toISOString():null}})},function(t,n,e){var r=e(0),o=e(417);r({target:"Date",proto:!0,forced:Date.prototype.toISOString!==o},{toISOString:o})},function(t,n,e){"use strict";var r=e(1),o=e(156).start,i=Math.abs,a=Date.prototype,u=a.getTime,s=a.toISOString;t.exports=r((function(){return"0385-07-25T07:06:39.999Z"!=s.call(new Date(-5e13-1))}))||!r((function(){s.call(new Date(NaN))}))?function(){if(!isFinite(u.call(this)))throw RangeError("Invalid time value");var t=this.getUTCFullYear(),n=this.getUTCMilliseconds(),e=t<0?"-":t>9999?"+":"";return e+o(i(t),e?6:4,0)+"-"+o(this.getUTCMonth()+1,2,0)+"-"+o(this.getUTCDate(),2,0)+"T"+o(this.getUTCHours(),2,0)+":"+o(this.getUTCMinutes(),2,0)+":"+o(this.getUTCSeconds(),2,0)+"."+o(n,3,0)+"Z"}:s},function(t,n,e){var r=e(25),o=Date.prototype,i=o.toString,a=o.getTime;new Date(NaN)+""!="Invalid Date"&&r(o,"toString",(function(){var t=a.call(this);return t==t?i.call(this):"Invalid Date"}))},function(t,n,e){var r=e(28),o=e(420),i=e(7)("toPrimitive"),a=Date.prototype;i in a||r(a,i,o)},function(t,n,e){"use strict";var r=e(4),o=e(46);t.exports=function(t){if("string"!==t&&"number"!==t&&"default"!==t)throw TypeError("Incorrect hint");return o(r(this),"number"!==t)}},function(t,n,e){var r=e(0),o=e(42),i=e(1),a=o("JSON","stringify"),u=/[\uD800-\uDFFF]/g,s=/^[\uD800-\uDBFF]$/,c=/^[\uDC00-\uDFFF]$/,f=function(t,n,e){var r=e.charAt(n-1),o=e.charAt(n+1);return s.test(t)&&!c.test(o)||c.test(t)&&!s.test(r)?"\\u"+t.charCodeAt(0).toString(16):t},l=i((function(){return'"\\udf06\\ud834"'!==a("\udf06\ud834")||'"\\udead"'!==a("\udead")}));a&&r({target:"JSON",stat:!0,forced:l},{stringify:function(t,n,e){var r=a.apply(null,arguments);return"string"==typeof r?r.replace(u,f):r}})},function(t,n,e){var r=e(2);e(48)(r.JSON,"JSON",!0)},function(t,n,e){var r=e(2);t.exports=function(t,n){var e=r.console;e&&e.error&&(1===arguments.length?e.error(t):e.error(t,n))}},function(t,n,e){"use strict";var r=e(0),o=e(32),i=e(164),a=e(225),u=e(75);r({target:"Promise",stat:!0},{allSettled:function(t){var n=this,e=i.f(n),r=e.resolve,s=e.reject,c=a((function(){var e=o(n.resolve),i=[],a=0,s=1;u(t,(function(t){var o=a++,u=!1;i.push(void 0),s++,e.call(n,t).then((function(t){u||(u=!0,i[o]={status:"fulfilled",value:t},--s||r(i))}),(function(t){u||(u=!0,i[o]={status:"rejected",reason:t},--s||r(i))}))})),--s||r(i)}));return c.error&&s(c.value),e.promise}})},function(t,n,e){"use strict";e(121)("WeakSet",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),e(231))},function(t,n,e){"use strict";var r=e(0),o=e(2),i=e(122),a=e(79),u=i.ArrayBuffer;r({global:!0,forced:o.ArrayBuffer!==u},{ArrayBuffer:u}),a("ArrayBuffer")},function(t,n){var e=Math.abs,r=Math.pow,o=Math.floor,i=Math.log,a=Math.LN2;t.exports={pack:function(t,n,u){var s,c,f,l=new Array(u),p=8*u-n-1,h=(1<<p)-1,d=h>>1,v=23===n?r(2,-24)-r(2,-77):0,g=t<0||0===t&&1/t<0?1:0,y=0;for((t=e(t))!=t||t===1/0?(c=t!=t?1:0,s=h):(s=o(i(t)/a),t*(f=r(2,-s))<1&&(s--,f*=2),(t+=s+d>=1?v/f:v*r(2,1-d))*f>=2&&(s++,f/=2),s+d>=h?(c=0,s=h):s+d>=1?(c=(t*f-1)*r(2,n),s+=d):(c=t*r(2,d-1)*r(2,n),s=0));n>=8;l[y++]=255&c,c/=256,n-=8);for(s=s<<n|c,p+=n;p>0;l[y++]=255&s,s/=256,p-=8);return l[--y]|=128*g,l},unpack:function(t,n){var e,o=t.length,i=8*o-n-1,a=(1<<i)-1,u=a>>1,s=i-7,c=o-1,f=t[c--],l=127&f;for(f>>=7;s>0;l=256*l+t[c],c--,s-=8);for(e=l&(1<<-s)-1,l>>=-s,s+=n;s>0;e=256*e+t[c],c--,s-=8);if(0===l)l=1-u;else{if(l===a)return e?NaN:f?-1/0:1/0;e+=r(2,n),l-=u}return(f?-1:1)*e*r(2,l-n)}}},function(t,n,e){var r=e(0),o=e(6);r({target:"ArrayBuffer",stat:!0,forced:!o.NATIVE_ARRAY_BUFFER_VIEWS},{isView:o.isView})},function(t,n,e){var r=e(0),o=e(122);r({global:!0,forced:!e(6).NATIVE_ARRAY_BUFFER},{DataView:o.DataView})},function(t,n,e){e(54)("Int8",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){var r=e(43);t.exports=function(t){var n=r(t);if(n<0)throw RangeError("The argument can't be less than 0");return n}},function(t,n,e){e(54)("Uint8",(function(t){return function(n,e,r){return t(this,n,e,r)}}),!0)},function(t,n,e){e(54)("Int16",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){e(54)("Uint16",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){e(54)("Int32",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){e(54)("Uint32",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){e(54)("Float32",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){e(54)("Float64",(function(t){return function(n,e,r){return t(this,n,e,r)}}))},function(t,n,e){"use strict";var r=e(165);(0,e(6).exportTypedArrayStaticMethod)("from",e(235),r)},function(t,n,e){"use strict";var r=e(6),o=e(165),i=r.aTypedArrayConstructor;(0,r.exportTypedArrayStaticMethod)("of",(function(){for(var t=0,n=arguments.length,e=new(i(this))(n);n>t;)e[t]=arguments[t++];return e}),o)},function(t,n,e){var r=e(0),o=e(42),i=e(32),a=e(4),u=e(1),s=o("Reflect","apply"),c=Function.apply;r({target:"Reflect",stat:!0,forced:!u((function(){s((function(){}))}))},{apply:function(t,n,e){return i(t),a(e),s?s(t,n,e):c.call(t,n,e)}})},function(t,n,e){var r=e(0),o=e(42),i=e(32),a=e(4),u=e(3),s=e(51),c=e(202),f=e(1),l=o("Reflect","construct"),p=f((function(){function t(){}return!(l((function(){}),[],t)instanceof t)})),h=!f((function(){l((function(){}))})),d=p||h;r({target:"Reflect",stat:!0,forced:d,sham:d},{construct:function(t,n){i(t),a(n);var e=arguments.length<3?t:i(arguments[2]);if(h&&!p)return l(t,n,e);if(t==e){switch(n.length){case 0:return new t;case 1:return new t(n[0]);case 2:return new t(n[0],n[1]);case 3:return new t(n[0],n[1],n[2]);case 4:return new t(n[0],n[1],n[2],n[3])}var r=[null];return r.push.apply(r,n),new(c.apply(t,r))}var o=e.prototype,f=s(u(o)?o:Object.prototype),d=Function.apply.call(t,f,n);return u(d)?d:f}})},function(t,n,e){var r=e(0),o=e(5),i=e(4),a=e(46),u=e(10);r({target:"Reflect",stat:!0,forced:e(1)((function(){Reflect.defineProperty(u.f({},1,{value:1}),1,{value:2})})),sham:!o},{defineProperty:function(t,n,e){i(t);var r=a(n,!0);i(e);try{return u.f(t,r,e),!0}catch(t){return!1}}})},function(t,n,e){var r=e(0),o=e(4),i=e(24).f;r({target:"Reflect",stat:!0},{deleteProperty:function(t,n){var e=i(o(t),n);return!(e&&!e.configurable)&&delete t[n]}})},function(t,n,e){var r=e(0),o=e(4),i=e(50);r({target:"Reflect",stat:!0,sham:!e(147)},{getPrototypeOf:function(t){return i(o(t))}})},function(t,n,e){var r=e(0),o=e(4),i=Object.isExtensible;r({target:"Reflect",stat:!0},{isExtensible:function(t){return o(t),!i||i(t)}})},function(t,n,e){var r=e(0),o=e(42),i=e(4);r({target:"Reflect",stat:!0,sham:!e(95)},{preventExtensions:function(t){i(t);try{var n=o("Object","preventExtensions");return n&&n(t),!0}catch(t){return!1}}})},function(t,n,e){var r=e(0),o=e(4),i=e(3),a=e(17),u=e(1),s=e(10),c=e(24),f=e(50),l=e(56);r({target:"Reflect",stat:!0,forced:u((function(){var t=s.f({},"a",{configurable:!0});return!1!==Reflect.set(f(t),"a",1,t)}))},{set:function t(n,e,r){var u,p,h=arguments.length<4?n:arguments[3],d=c.f(o(n),e);if(!d){if(i(p=f(n)))return t(p,e,r,h);d=l(0)}if(a(d,"value")){if(!1===d.writable||!i(h))return!1;if(u=c.f(h,e)){if(u.get||u.set||!1===u.writable)return!1;u.value=r,s.f(h,e,u)}else s.f(h,e,l(0,r));return!0}return void 0!==d.set&&(d.set.call(h,r),!0)}})},function(t,n,e){var r=e(0),o=e(4),i=e(201),a=e(76);a&&r({target:"Reflect",stat:!0},{setPrototypeOf:function(t,n){o(t),i(n);try{return a(t,n),!0}catch(t){return!1}}})},function(t,n,e){e(23),e(13),e(451),e(452),e(453),e(261),e(456),e(263);var r=e(89);t.exports=r},function(t,n,e){var r=e(0),o=e(2),i=e(163);r({global:!0,bind:!0,enumerable:!0,forced:!o.setImmediate||!o.clearImmediate},{setImmediate:i.set,clearImmediate:i.clear})},function(t,n,e){var r=e(0),o=e(2),i=e(223),a=e(41),u=o.process,s="process"==a(u);r({global:!0,enumerable:!0,noTargetGet:!0},{queueMicrotask:function(t){var n=s&&u.domain;i(n?n.bind(t):t)}})},function(t,n,e){var r=e(0),o=e(2),i=e(109),a=[].slice,u=function(t){return function(n,e){var r=arguments.length>2,o=r?a.call(arguments,2):void 0;return t(r?function(){("function"==typeof n?n:Function(n)).apply(this,o)}:n,e)}};r({global:!0,bind:!0,forced:/MSIE .\./.test(i)},{setTimeout:u(o.setTimeout),setInterval:u(o.setInterval)})},function(t,n,e){"use strict";var r=/[^\0-\u007E]/,o=/[.\u3002\uFF0E\uFF61]/g,i="Overflow: input needs wider integers to process",a=Math.floor,u=String.fromCharCode,s=function(t){return t+22+75*(t<26)},c=function(t,n,e){var r=0;for(t=e?a(t/700):t>>1,t+=a(t/n);t>455;r+=36)t=a(t/35);return a(r+36*t/(t+38))},f=function(t){var n,e,r=[],o=(t=function(t){for(var n=[],e=0,r=t.length;e<r;){var o=t.charCodeAt(e++);if(o>=55296&&o<=56319&&e<r){var i=t.charCodeAt(e++);56320==(64512&i)?n.push(((1023&o)<<10)+(1023&i)+65536):(n.push(o),e--)}else n.push(o)}return n}(t)).length,f=128,l=0,p=72;for(n=0;n<t.length;n++)(e=t[n])<128&&r.push(u(e));var h=r.length,d=h;for(h&&r.push("-");d<o;){var v=2147483647;for(n=0;n<t.length;n++)(e=t[n])>=f&&e<v&&(v=e);var g=d+1;if(v-f>a((2147483647-l)/g))throw RangeError(i);for(l+=(v-f)*g,f=v,n=0;n<t.length;n++){if((e=t[n])<f&&++l>2147483647)throw RangeError(i);if(e==f){for(var y=l,m=36;;m+=36){var b=m<=p?1:m>=p+26?26:m-p;if(y<b)break;var w=y-b,x=36-b;r.push(u(s(b+w%x))),y=a(w/x)}r.push(u(s(y))),p=c(l,g,d==h),l=0,++d}}++l,++f}return r.join("")};t.exports=function(t){var n,e,i=[],a=t.toLowerCase().replace(o,".").split(".");for(n=0;n<a.length;n++)e=a[n],i.push(r.test(e)?"xn--"+f(e):e);return i.join(".")}},function(t,n,e){var r=e(4),o=e(97);t.exports=function(t){var n=o(t);if("function"!=typeof n)throw TypeError(String(t)+" is not iterable");return r(n.call(t))}},function(t,n,e){"use strict";e(0)({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return URL.prototype.toString.call(this)}})},function(t,n){t.exports=function(){this.__data__=[],this.size=0}},function(t,n,e){var r=e(123),o=Array.prototype.splice;t.exports=function(t){var n=this.__data__,e=r(n,t);return!(e<0)&&(e==n.length-1?n.pop():o.call(n,e,1),--this.size,!0)}},function(t,n,e){var r=e(123);t.exports=function(t){var n=this.__data__,e=r(n,t);return e<0?void 0:n[e][1]}},function(t,n,e){var r=e(123);t.exports=function(t){return r(this.__data__,t)>-1}},function(t,n,e){var r=e(123);t.exports=function(t,n){var e=this.__data__,o=r(e,t);return o<0?(++this.size,e.push([t,n])):e[o][1]=n,this}},function(t,n){t.exports=function(t,n){for(var e=-1,r=null==t?0:t.length;++e<r&&!1!==n(t[e],e,t););return t}},function(t,n,e){var r=e(464),o=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=o},function(t,n){t.exports=function(t,n){return null==t?void 0:t[n]}},function(t,n,e){var r=e(70),o=e(172);t.exports=function(t,n){return t&&r(n,o(n),t)}},function(t,n,e){var r=e(70),o=e(125);t.exports=function(t,n){return t&&r(n,o(n),t)}},function(t,n,e){(function(n){var e="object"==typeof n&&n&&n.Object===Object&&n;t.exports=e}).call(this,e(134))},function(t,n,e){var r=e(70),o=e(469);t.exports=function(t,n){return r(t,o(t),n)}},function(t,n){t.exports=function(){return[]}},function(t,n,e){var r=e(70),o=e(471);t.exports=function(t,n){return r(t,o(t),n)}},function(t,n){t.exports=function(){return[]}},function(t,n,e){var r=e(173)(Object.keys,Object);t.exports=r},function(t,n){var e=Object.prototype.toString;t.exports=function(t){return e.call(t)}},function(t,n){var e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=t.length,r=new t.constructor(n);return n&&"string"==typeof t[0]&&e.call(t,"index")&&(r.index=t.index,r.input=t.input),r}},function(t,n){t.exports=function(t){return t}},function(t,n,e){var r=e(30),o=Object.create,i=function(){function t(){}return function(n){if(!r(n))return{};if(o)return o(n);t.prototype=n;var e=new t;return t.prototype=void 0,e}}();t.exports=i},function(t,n){t.exports=function(){return!1}},function(t,n){t.exports=function(){return!1}},function(t,n){t.exports=function(){return!1}},function(t,n,e){"use strict";var r;function o(t){return!!t&&("object"==(void 0===t?"undefined":i(t))||"function"==typeof t)}var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol?"symbol":typeof t},a=function(){var t=null,n=function(n,e){if(!o(n)||!o(e))throw new TypeError("Cannot create proxy with a non-object as target or handler");var r=function(){};t=function(){r=function(t){throw new TypeError("Cannot perform '"+t+"' on a proxy that has been revoked")}};var i=e;for(var a in e={get:null,set:null,apply:null,construct:null},i){if(!(a in e))throw new TypeError("Proxy polyfill does not support trap '"+a+"'");e[a]=i[a]}"function"==typeof i&&(e.apply=i.apply.bind(i));var u=this,s=!1,c="function"==typeof n;(e.apply||e.construct||c)&&(u=function(){var t=this&&this.constructor===u;if(r(t?"construct":"apply"),t&&e.construct)return e.construct.call(this,n,arguments);if(!t&&e.apply)return e.apply(n,this,arguments);if(c){if(t){var o=Array.prototype.slice.call(arguments);o.unshift(n);var i=n.bind.apply(n,o);return new i}return n.apply(this,arguments)}throw new TypeError(t?"not a constructor":"not a function")},s=!0);var f=e.get?function(t){return r("get"),e.get(this,t,u)}:function(t){return r("get"),this[t]},l=e.set?function(t,n){r("set"),e.set(this,t,n,u)}:function(t,n){r("set"),this[t]=n},p=Object.getOwnPropertyNames(n),h={};p.forEach((function(t){if(!(s&&t in u)){var e={enumerable:!!Object.getOwnPropertyDescriptor(n,t).enumerable,get:f.bind(n,t),set:l.bind(n,t)};Object.defineProperty(u,t,e),h[t]=!0}}));var d=!0;if(Object.setPrototypeOf?Object.setPrototypeOf(u,Object.getPrototypeOf(n)):u.__proto__?u.__proto__=n.__proto__:d=!1,e.get||!d)for(var v in n)h[v]||Object.defineProperty(u,v,{get:f.bind(n,v)});return Object.seal(n),Object.seal(u),u};return n.revocable=function(e,r){return{proxy:new n(e,r),revoke:t}},n}();"object"===i(n)?t.exports="function"!=typeof Proxy?a:Proxy:void 0===(r=function(){return"function"!=typeof Proxy?a:Proxy}.call(n,e,n,t))||(t.exports=r)},function(t,n){t.exports=function(t){if("function"!=typeof t)throw new TypeError("Expected a function");return function(){var n=arguments;switch(n.length){case 0:return!t.call(this);case 1:return!t.call(this,n[0]);case 2:return!t.call(this,n[0],n[1]);case 3:return!t.call(this,n[0],n[1],n[2])}return!t.apply(this,n)}}},function(t,n,e){var r=e(71),o=e(175),i=e(271),a=e(174);t.exports=function(t,n){if(null==t)return{};var e=r(a(t),(function(t){return[t]}));return n=o(n),i(t,e,(function(t,e){return n(t,e[0])}))}},function(t,n,e){var r=e(45),o=e(273),i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,a=/^\w*$/;t.exports=function(t,n){if(r(t))return!1;var e=typeof t;return!("number"!=e&&"symbol"!=e&&"boolean"!=e&&null!=t&&!o(t))||(a.test(t)||!i.test(t)||null!=n&&t in Object(n))}},function(t,n,e){var r=e(485),o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,a=r((function(t){var n=[];return 46===t.charCodeAt(0)&&n.push(""),t.replace(o,(function(t,e,r,o){n.push(r?o.replace(i,"$1"):e||t)})),n}));t.exports=a},function(t,n){t.exports=function(t){return t}},function(t,n,e){var r=e(170),o=e(83),i=e(274),a=e(30),u=e(127);t.exports=function(t,n,e,s){if(!a(t))return t;for(var c=-1,f=(n=o(n,t)).length,l=f-1,p=t;null!=p&&++c<f;){var h=u(n[c]),d=e;if(c!=l){var v=p[h];void 0===(d=s?s(v,h,p):void 0)&&(d=a(v)?v:i(n[c+1])?[]:{})}r(p,h,d),p=p[h]}return t}},function(t,n,e){var r=e(271),o=e(488);t.exports=function(t,n){return r(t,n,(function(n,e){return o(t,e)}))}},function(t,n,e){var r=e(489),o=e(490);t.exports=function(t,n){return null!=t&&o(t,n,r)}},function(t,n){t.exports=function(t,n){return null!=t&&n in Object(t)}},function(t,n,e){var r=e(83),o=e(177),i=e(45),a=e(274),u=e(275),s=e(127);t.exports=function(t,n,e){for(var c=-1,f=(n=r(n,t)).length,l=!1;++c<f;){var p=s(n[c]);if(!(l=null!=t&&e(t,p)))break;t=t[p]}return l||++c!=f?l:!!(f=null==t?0:t.length)&&u(f)&&a(p,f)&&(i(t)||o(t))}},function(t,n){t.exports=function(t,n){for(var e=-1,r=n.length,o=t.length;++e<r;)t[o+e]=n[e];return t}},function(t,n,e){var r=e(493),o=e(177),i=e(45),a=r?r.isConcatSpreadable:void 0;t.exports=function(t){return i(t)||o(t)||!!(a&&t&&t[a])}},function(t,n,e){var r=e(126).Symbol;t.exports=r},function(t,n,e){var r=e(179),o=e(180),i=e(181),a=e(182),u=e(495),s=e(496);t.exports=function(t,n,e){var c=-1,f=o,l=t.length,p=!0,h=[],d=h;if(e)p=!1,f=i;else if(l>=200){var v=n?null:u(t);if(v)return s(v);p=!1,f=a,d=new r}else d=n?[]:h;t:for(;++c<l;){var g=t[c],y=n?n(g):g;if(g=e||0!==g?g:0,p&&y==y){for(var m=d.length;m--;)if(d[m]===y)continue t;n&&d.push(y),h.push(g)}else f(d,y,e)||(d!==h&&d.push(y),h.push(g))}return h}},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(){return[]}},function(t,n,e){var r=e(179),o=e(180),i=e(181),a=e(71),u=e(183),s=e(182),c=Math.min;t.exports=function(t,n,e){for(var f=e?i:o,l=t[0].length,p=t.length,h=p,d=Array(p),v=1/0,g=[];h--;){var y=t[h];h&&n&&(y=a(y,u(n))),v=c(y.length,v),d[h]=!e&&(n||l>=120&&y.length>=120)?new r(h&&y):void 0}y=t[0];var m=-1,b=d[0];t:for(;++m<l&&g.length<v;){var w=y[m],x=n?n(w):w;if(w=e||0!==w?w:0,!(b?s(b,x):f(g,x,e))){for(h=p;--h;){var O=d[h];if(!(O?s(O,x):f(t[h],x,e)))continue t}b&&b.push(x),g.push(w)}}return g}},function(t,n,e){var r=e(128);t.exports=function(t){return r(t)?t:[]}},function(t,n,e){var r=e(63),o=e(275);t.exports=function(t){return null!=t&&o(t.length)&&!r(t)}},function(t,n,e){var r=e(83),o=e(501),i=e(502),a=e(127);t.exports=function(t,n){return n=r(n,t),null==(t=i(t,n))||delete t[a(o(n))]}},function(t,n){t.exports=function(t){var n=null==t?0:t.length;return n?t[n-1]:void 0}},function(t,n,e){var r=e(272),o=e(503);t.exports=function(t,n){return n.length<2?t:r(t,o(n,0,-1))}},function(t,n){t.exports=function(t,n,e){var r=-1,o=t.length;n<0&&(n=-n>o?0:o+n),(e=e>o?o:e)<0&&(e+=o),o=n>e?0:e-n>>>0,n>>>=0;for(var i=Array(o);++r<o;)i[r]=t[r+n];return i}},function(t,n,e){var r=e(72);t.exports=function(t){return r(t)?void 0:t}},function(t,n,e){var r=e(71),o=e(175),i=e(506),a=e(507),u=e(183),s=e(508),c=e(184);t.exports=function(t,n,e){var f=-1;n=r(n.length?n:[c],u(o));var l=i(t,(function(t,e,o){return{criteria:r(n,(function(n){return n(t)})),index:++f,value:t}}));return a(l,(function(t,n){return s(t,n,e)}))}},function(t,n){t.exports=function(t,n){for(var e=-1,r=null==t?0:t.length,o=Array(r);++e<r;)o[e]=n(t[e],e,t);return o}},function(t,n){t.exports=function(t,n){var e=t.length;for(t.sort(n);e--;)t[e]=t[e].value;return t}},function(t,n,e){var r=e(509);t.exports=function(t,n,e){for(var o=-1,i=t.criteria,a=n.criteria,u=i.length,s=e.length;++o<u;){var c=r(i[o],a[o]);if(c)return o>=s?c:c*("desc"==e[o]?-1:1)}return t.index-n.index}},function(t,n,e){var r=e(273);t.exports=function(t,n){if(t!==n){var e=void 0!==t,o=null===t,i=t==t,a=r(t),u=void 0!==n,s=null===n,c=n==n,f=r(n);if(!s&&!f&&!a&&t>n||a&&u&&c&&!s&&!f||o&&u&&c||!e&&c||!i)return 1;if(!o&&!a&&!f&&t<n||f&&e&&i&&!o&&!a||s&&e&&i||!u&&i||!c)return-1}return 0}},function(t,n){!function(){"use strict";if(self.document){var t=KeyboardEvent.prototype,n=Object.getOwnPropertyDescriptor(t,"key");if(n){var e={Win:"Meta",Scroll:"ScrollLock",Spacebar:" ",Down:"ArrowDown",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Del:"Delete",Apps:"ContextMenu",Esc:"Escape",Multiply:"*",Add:"+",Subtract:"-",Decimal:".",Divide:"/"};Object.defineProperty(t,"key",{get:function(){var t=n.get.call(this);return e.hasOwnProperty(t)?e[t]:t}})}}}()},function(t,n,e){var r=e(264),o=e(283),i=e(512),a=e(514),u=e(30),s=e(125),c=e(284);t.exports=function t(n,e,f,l,p){n!==e&&i(e,(function(i,s){if(p||(p=new r),u(i))a(n,e,s,f,t,l,p);else{var h=l?l(c(n,s),i,s+"",n,e,p):void 0;void 0===h&&(h=i),o(n,s,h)}}),s)}},function(t,n,e){var r=e(513)();t.exports=r},function(t,n){t.exports=function(t){return function(n,e,r){for(var o=-1,i=Object(n),a=r(n),u=a.length;u--;){var s=a[t?u:++o];if(!1===e(i[s],s,i))break}return n}}},function(t,n,e){var r=e(283),o=e(265),i=e(515),a=e(267),u=e(268),s=e(177),c=e(45),f=e(128),l=e(270),p=e(63),h=e(30),d=e(72),v=e(518),g=e(284),y=e(519);t.exports=function(t,n,e,m,b,w,x){var O=g(t,e),S=g(n,e),j=x.get(S);if(j)r(t,e,j);else{var E=w?w(O,S,e+"",t,n,x):void 0,A=void 0===E;if(A){var k=c(S),T=!k&&l(S),P=!k&&!T&&v(S);E=S,k||T||P?c(O)?E=O:f(O)?E=a(O):T?(A=!1,E=o(S,!0)):P?(A=!1,E=i(S,!0)):E=[]:d(S)||s(S)?(E=O,s(O)?E=y(O):h(O)&&!p(O)||(E=u(S))):A=!1}A&&(x.set(S,E),b(E,S,m,w,x),x.delete(S)),r(t,e,E)}}},function(t,n,e){var r=e(516);t.exports=function(t,n){var e=n?r(t.buffer):t.buffer;return new t.constructor(e,t.byteOffset,t.length)}},function(t,n,e){var r=e(517);t.exports=function(t){var n=new t.constructor(t.byteLength);return new r(n).set(new r(t)),n}},function(t,n,e){var r=e(126).Uint8Array;t.exports=r},function(t,n){t.exports=function(){return!1}},function(t,n,e){var r=e(70),o=e(125);t.exports=function(t){return r(t,o(t))}},function(t,n,e){var r=e(521),o=e(131),i=e(522);t.exports=function(t){return function(n,e,a){return a&&"number"!=typeof a&&o(n,e,a)&&(e=a=void 0),n=i(n),void 0===e?(e=n,n=0):e=i(e),a=void 0===a?n<e?1:-1:i(a),r(n,e,a,t)}}},function(t,n){var e=Math.ceil,r=Math.max;t.exports=function(t,n,o,i){for(var a=-1,u=r(e((n-t)/(o||1)),0),s=Array(u);u--;)s[i?u:++a]=t,t+=o;return s}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(t,n,e){return t==t&&(void 0!==e&&(t=t<=e?t:e),void 0!==n&&(t=t>=n?t:n)),t}},function(t,n,e){var r=e(70),o=e(285),i=e(125),a=o((function(t,n,e,o){r(n,i(n),t,o)}));t.exports=a},function(t,n,e){var r=e(278),o=e(84),i=e(287),a=o((function(t,n){try{return r(t,void 0,n)}catch(t){return i(t)?t:new Error(t)}}));t.exports=a},function(t,n,e){var r=e(71);t.exports=function(t,n){return r(n,(function(n){return t[n]}))}},function(t,n,e){var r=e(124),o=Object.prototype,i=o.hasOwnProperty;t.exports=function(t,n,e,a){return void 0===t||r(t,o[e])&&!i.call(a,e)?n:t}},function(t,n){var e={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};t.exports=function(t){return"\\"+e[t]}},function(t,n,e){var r=e(530),o={escape:e(533),evaluate:e(534),interpolate:e(288),variable:"",imports:{_:{escape:r}}};t.exports=o},function(t,n,e){var r=e(531),o=e(176),i=/[&<>"']/g,a=RegExp(i.source);t.exports=function(t){return(t=o(t))&&a.test(t)?t.replace(i,r):t}},function(t,n,e){var r=e(532)({"&":"&","<":"<",">":">",'"':""","'":"'"});t.exports=r},function(t,n){t.exports=function(t){return function(n){return null==t?void 0:t[n]}}},function(t,n){t.exports=/<%-([\s\S]+?)%>/g},function(t,n){t.exports=/<%([\s\S]+?)%>/g},function(t,n,e){var r=e(536);t.exports=function(t,n){var e=null==t?0:t.length;return e?r(t,n)/e:NaN}},function(t,n){t.exports=function(t,n){for(var e,r=-1,o=t.length;++r<o;){var i=n(t[r]);void 0!==i&&(e=void 0===e?i:e+i)}return e}},function(t,n,e){var r=e(30),o=e(538),i=e(286),a=Math.max,u=Math.min;t.exports=function(t,n,e){var s,c,f,l,p,h,d=0,v=!1,g=!1,y=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function m(n){var e=s,r=c;return s=c=void 0,d=n,l=t.apply(r,e)}function b(t){return d=t,p=setTimeout(x,n),v?m(t):l}function w(t){var e=t-h;return void 0===h||e>=n||e<0||g&&t-d>=f}function x(){var t=o();if(w(t))return O(t);p=setTimeout(x,function(t){var e=n-(t-h);return g?u(e,f-(t-d)):e}(t))}function O(t){return p=void 0,y&&s?m(t):(s=c=void 0,l)}function S(){var t=o(),e=w(t);if(s=arguments,c=this,h=t,e){if(void 0===p)return b(h);if(g)return clearTimeout(p),p=setTimeout(x,n),m(h)}return void 0===p&&(p=setTimeout(x,n)),l}return n=i(n)||0,r(e)&&(v=!!e.leading,f=(g="maxWait"in e)?a(i(e.maxWait)||0,n):f,y="trailing"in e?!!e.trailing:y),S.cancel=function(){void 0!==p&&clearTimeout(p),d=0,s=h=c=p=void 0},S.flush=function(){return void 0===p?l:O(o())},S}},function(t,n,e){var r=e(126);t.exports=function(){return r.Date.now()}},function(t,n,e){"use strict";e.r(n);e(306),e(16),e(19),e(20),e(15),e(37),e(22),e(33),e(77),e(9),e(78),e(18),e(61),e(99),e(74),e(144),e(35),e(49),e(36),e(59),e(11),e(40),e(166),e(167),e(168),e(44),e(26),e(229),e(101),e(12),e(69),e(23),e(13);var r=e(289),o=e.n(r),i=e(290),a=e.n(i),u=(e(68),e(214),e(211),e(80),e(158),e(291)),s=e.n(u),c=e(132),f=e.n(c),l=e(292),p=e.n(l),h=e(293),d=e.n(h),v=e(294),g=e.n(v),y=e(104),m=e.n(y),b=e(85),w=e.n(b),x=e(30),O=e.n(x),S=e(295),j=e(63),E=e.n(j),A=e(296),k=e.n(A);function T(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var P=function(){function t(n){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.plugins=[],this.context=n}return function(t,n,e){n&&T(t.prototype,n),e&&T(t,e)}(t,[{key:"add",value:function(t){this.plugins.push(t),t.handle(this.context,"plugin:init")}},{key:"remove",value:function(t){t.handle(this.context,"plugin:removal"),this.plugins=k()(this.plugins,t)}},{key:"trigger",value:function(t){for(var n=this,e=arguments.length,r=new Array(e>1?e-1:0),o=1;o<e;o++)r[o-1]=arguments[o];return Promise.all(this.plugins.map((function(e){return e.handle.apply(e,[n.context,t].concat(r))})))}}]),t}();function R(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){_(t,n,e[n])}))}return t}function _(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function M(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function I(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var C=function(){function t(){var n=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};M(this,t),this.internals={callbacks:{},rawOptions:R({debug:!1,plugins:[]},e),parsedOptions:{}},this.plugins=new P(this),this.internals.rawOptions.plugins.map((function(t){return n.plugins.add(t)}))}return function(t,n,e){n&&I(t.prototype,n),e&&I(t,e)}(t,[{key:"on",value:function(t,n){return n.displayName=n.displayName||"".concat(t," handler on ").concat(this.internals.rawOptions.title),this.internals.callbacks["$".concat(t)]=this.internals.callbacks["$".concat(t)]||[],this.internals.callbacks["$".concat(t)].push(n),this}},{key:"off",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return null===n?delete this.internals.callbacks["$".concat(t)]:this.internals.callbacks["$".concat(t)]=this.internals.callbacks["$".concat(t)].filter((function(t){return t!==n})),this}},{key:"once",value:function(t,n){function e(){this.off(t,e);for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];return n.apply(this,o)}return e.fn=n,this.on(t,e),this}},{key:"waitFor",value:function(t){var n=this;return new Promise((function(e){return n.on(t,e)}))}},{key:"trigger",value:async function(t){for(var n,e=this,r=arguments.length,o=new Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];var a=this.internals.callbacks["$".concat(t)];if(a)try{await Promise.all(a.map((function(t){return t.apply(e,o)})))}catch(n){throw console.error("%cError in ".concat(this.internals.rawOptions.title,"%c ")+"during event ".concat(t,"%c: ").concat(n),"font-weight: bold","font-weight: normal","font-weight: normal; opacity: 0.5"),n}return await(n=this.plugins).trigger.apply(n,[t].concat(o)),this}},{key:"triggerMethod",value:async function(t){for(var n=arguments.length,e=new Array(n>1?n-1:0),r=1;r<n;r++)e[r-1]=arguments[r];this.internals.rawOptions.debug&&(console.info("%c".concat(this.internals.rawOptions.title,"%c (").concat(this.type,") → ")+"Event %c".concat(t,"%c · arguments [").concat(e,"]"),"font-weight: bold","font-weight: normal","font-weight: bold","font-weight: normal; opacity: 0.5"),console.time("".concat(t," on ").concat(this.internals.rawOptions.title)+"(".concat(this.internals.rawOptions.id,")")));var o=/(^|:)(\w)/gi;function i(t,n,e){return e.toUpperCase()}var a,u="on".concat(t.replace(o,i)),s=this[u];return E()(s)&&(a=await s.apply(this,e)),await this.trigger.apply(this,[t].concat(e)),this.internals.rawOptions.debug&&console.timeEnd("".concat(t," on ").concat(this.internals.rawOptions.title)+"(".concat(this.internals.rawOptions.id,")")),a}}]),t}();e(207),e(226);function F(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function N(t,n){if(null==t)return{};var e,r,o=function(t,n){if(null==t)return{};var e,r,o={},i=Object.keys(t);for(r=0;r<i.length;r++)e=i[r],n.indexOf(e)>=0||(o[e]=t[e]);return o}(t,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)e=i[r],n.indexOf(e)>=0||Object.prototype.propertyIsEnumerable.call(t,e)&&(o[e]=t[e])}return o}var L=function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=n.retry,r=(e=void 0===e?{}:e).times,o=void 0===r?3:r,i=e.delay,a=void 0===i?10:i,u=e.factor,s=void 0===u?5:u,c=N(n,["retry"]);return new Promise((function(n,e){var r=function(r){return window.fetch(t,c).then((function(t){return n(t)})).catch((function(t){r<=o?i(r):e(t)}))},i=function(t){var n=a*Math.pow(s,t);setTimeout((function(){return r(++t)}),n)};r(0)}))},D=function(t,n){var e,r,o,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=i.throttle,u=void 0===a||a,s=[],c=!1,f=!1,l=function(){if(c&&u)f=!0;else{var n=s;s=[],e=null,c=!0,Promise.resolve(t.apply(o,r)).then((function(t){var e=!0,r=!1,o=void 0;try{for(var i,a=n[Symbol.iterator]();!(e=(i=a.next()).done);e=!0){var u=F(i.value,2),s=u[0];u[1];s(t)}}catch(t){r=!0,o=t}finally{try{e||null==a.return||a.return()}finally{if(r)throw o}}})).catch((function(t){var e=!0,r=!1,o=void 0;try{for(var i,a=n[Symbol.iterator]();!(e=(i=a.next()).done);e=!0){var u=F(i.value,2);u[0];(0,u[1])(t)}}catch(t){r=!0,o=t}finally{try{e||null==a.return||a.return()}finally{if(r)throw o}}})).finally((function(){f&&null===e&&p(),c=f=!1}))}},p=function(){clearTimeout(e),s.length>0&&l()},h=function(){clearTimeout(e),e=null,f=!1,r=o=void 0,s=[]},d=function(){var t=arguments,i=this;return new Promise((function(a,u){r=t,o=i,clearTimeout(e),e=setTimeout(l,n),s.push([a,u])}))};return d.flush=p,d.cancel=h,d};function U(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){Y(t,n,e[n])}))}return t}function q(t){return(q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function B(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function z(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function V(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function W(t,n){return!n||"object"!==q(n)&&"function"!=typeof n?$(t):n}function H(t){return(H=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function $(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function G(t,n){return(G=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}function Y(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}var J=["id","participant","participant_id"],K=[].concat(J,["sender","sender_type","sender_id","timestamp","meta"]),X=function(t){return O()(t)&&(t=JSON.stringify(t)),"string"==typeof t&&(t=t.replace(/"/g,'""'),/[,"\n]+/.test(t)&&(t='"'.concat(t,'"'))),t},Q=function(t){return t.toString().padStart(2,"0")},Z=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;return"".concat(t.getFullYear(),"-")+"".concat(Q((t.getMonth()+1).toString()),"-")+"".concat(Q(t.getDate().toString()),"--")+"".concat(t.toTimeString().split(" ")[0])},tt=function(t){return t.map((function(t){return s()(t,(function(t,n){return n.startsWith("_")}))}))},nt=function(t){function n(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};z(this,n),Y($(t=W(this,H(n).call(this,e))),"stateProxy",new window.Proxy({},{get:function(n,e){return t.get(e)},set:function(n,e,r){return t.set(e,r)||!0},has:function(n,e){return Reflect.has(t.state,e)},ownKeys:function(){return Reflect.ownKeys(t.state)},getOwnPropertyDescriptor:function(n,e){return Reflect.getOwnPropertyDescriptor(t.state,e)}})),Y($(t),"_debouncedTransmit",D(t.transmit,2500)),Y($(t),"_lastIncrementalTransmission",0),"session"===e.persistence?t.storage=sessionStorage:"local"===e.persistence?t.storage=localStorage:t.storage=null,e.clearPersistence&&t.clear();var r=!0;if(t.storage){var o=t.storage.getItem("lab.js-data");if(o)try{t.data=JSON.parse(o),t.state=Object.assign.apply(Object,[{}].concat(B(t.data))),K.forEach((function(n){Object.hasOwnProperty.call(t.state,n)&&delete t.state[n]})),r=!1}catch(t){r=!0}}return r&&(t.data=[],t.state={}),t.staging={},t}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&G(t,n)}(n,t),function(t,n,e){n&&V(t.prototype,n),e&&V(t,e)}(n,[{key:"set",value:function(t,n){var e=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r={};"object"===q(t)?r=t:r[t]=n,this.state=Object.assign(this.state,r),this.staging=Object.assign(this.staging,r),e||this.triggerMethod("set")}},{key:"get",value:function(t){return this.state[t]}},{key:"commit",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;this.set(t,n,!0);var e=this.data.push(w()(this.staging))-1;return this.storage&&this.storage.setItem("lab.js-data",JSON.stringify(this.data)),this.triggerMethod("commit"),this.staging={},e}},{key:"update",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(t){return t};this.data[t]=n(this.data[t]||{}),this.triggerMethod("update")}},{key:"clear",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.triggerMethod("clear"),t&&this.storage&&this.storage.clear(),n&&(this.data=[],this.staging={},this.state={})}},{key:"keys",value:function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:K,e=this.data.map((function(t){return Object.keys(t)}));t&&e.push(Object.keys(this.state)),e=m()(e),e.sort(),e=p()(e,!0).sort();var r=d()(n,e),o=g()(e,r);return r.concat(o)}},{key:"extract",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:RegExp(".*"),e="string"==typeof n?RegExp("^".concat(n,"$")):n;return this.data.filter((function(t){return e.test(t.sender)})).map((function(n){return n[t]}))}},{key:"select",value:function(t){var n,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:RegExp(".*");if(n="function"==typeof t?this.keys().filter(t):"string"==typeof t?[t]:t,!Array.isArray(n))throw new Error("The input parameter should be either an array of strings, a string, or a filter function.");var r="string"==typeof e?RegExp("^".concat(e,"$")):e;return this.data.filter((function(t){return r.test(t.sender)})).map((function(t){return f()(t,n)}))}},{key:"exportJson",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=t?this.cleanData:this.data;return JSON.stringify(n)}},{key:"exportJsonL",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=t?this.cleanData:this.data;return n.map((function(t){return JSON.stringify(t)})).join("\n")}},{key:"exportCsv",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:",",n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],e=n?this.cleanData:this.data,r=this.keys().filter((function(t){return!n||!t.startsWith("_")})),o=e.map((function(n){return r.map((function(t){return Object.hasOwnProperty.call(n,t)?n[t]:null})).map(X).join(t)}));return o.unshift(r.map(X).join(t)),o.join("\r\n")}},{key:"exportBlob",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"csv",n="";return n="json"===t?this.exportJson():this.exportCsv(),new Blob([n],{type:"octet/stream"})}},{key:"makeFilename",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"study",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"csv",e=this.id;return t+"--"+(e?"".concat(e,"--"):"")+Z()+(n?".".concat(n):"")}},{key:"download",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"csv",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"data.csv";return Object(S.saveAs)(this.exportBlob(t),n)}},{key:"show",value:function(){return console.table(this.data,this.keys())}},{key:"transmit",value:function(t){var n=this,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=r.incremental,i=void 0!==o&&o,a=r.encoding,u=void 0===a?"json":a,s=r.headers,c=void 0===s?{}:s,f=r.retry,l=void 0===f?{}:f;this.triggerMethod("transmit");var p,h=i?this._lastIncrementalTransmission:0,d=this.data.length,v=tt(this.data.slice(h)),g={};return"form"===u?((p=new FormData).append("metadata",JSON.stringify(U({slice:h},e))),p.append("url",window.location.href),p.append("data",JSON.stringify(v))):(p=JSON.stringify({metadata:U({slice:h},e),url:window.location.href,data:v}),g={Accept:"application/json","Content-Type":"application/json"}),L(t,{method:"post",headers:U({},g,c),body:p,credentials:"include",retry:U({times:i?2:3},l)}).then((function(t){return i&&(n._lastIncrementalTransmission=d),t}))}},{key:"queueIncrementalTransmission",value:function(t,n,e){return this._debouncedTransmit(t,n,U({incremental:!0},e))}},{key:"flushIncrementalTransmissionQueue",value:function(){this._debouncedTransmit.flush()}},{key:"cancelIncrementalTransmissionQueue",value:function(){this._debouncedTransmit.cancel()}},{key:"cleanData",get:function(){return tt(this.data)}},{key:"id",get:function(){var t=!0,n=!1,e=void 0;try{for(var r,o=J[Symbol.iterator]();!(t=(r=o.next()).done);t=!0){var i=r.value;if(Object.keys(this.state).includes(i))return this.state[i]}}catch(t){n=!0,e=t}finally{try{t||null==o.return||o.return()}finally{if(n)throw e}}}}]),n}(C),et=e(133),rt=e.n(et),ot=e(297),it=e.n(ot);e(94),e(103);function at(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){ut(t,n,e[n])}))}return t}function ut(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}var st=e(186),ct=e.n(st),ft=(new ct.a).getBrowser().name,lt=parseInt((new ct.a).getBrowser().version.split(".")[0],10);function pt(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function ht(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function dt(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function vt(t,n,e){return n&&dt(t.prototype,n),e&&dt(t,e),t}var gt={frameInterval:16.68},yt="Firefox"===ft&<<54,mt=function(t){return t&&!yt&&t<performance.timing.navigationStart?t:performance.now()},bt=window.requestIdleCallback?window.requestIdleCallback:function(t){return window.setTimeout(t)},wt=function(){function t(n,e){ht(this,t),this.f=n,this.delay=e;for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];this.params=o,this._running=!1,this._timeoutHandle=null}return vt(t,[{key:"run",value:function(){var t;this._running?console.log("Cannot restart previously run timer"):(this._timeoutHandle=(t=window).setTimeout.apply(t,[this.f,this.delay].concat(pt(this.params))),this._running=!0)}},{key:"cancel",value:function(){window.clearTimeout(this._timeoutHandle)}}]),t}(),xt={overshoot:1,closest:1.5,undershoot:2},Ot=function(){function t(n,e){ht(this,t),this.delay=e,this.f=n;for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];this.params=o,this._running=!1,this._timeoutHandle=void 0,this._animationFrameHandle=void 0,this._lastAnimationFrame=void 0,this.targetTime=void 0,this.mode="closest",this.tick=this.tick.bind(this)}return vt(t,[{key:"tick",value:function(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=n-this._lastAnimationFrame||gt.frameInterval;r<gt.frameInterval&&(gt.frameInterval=r);var o=(this.targetTime-n)/r;o<=xt[this.mode]?this.f.apply(this,[n].concat(pt(this.params))):this.targetTime-n<200?(this._animationFrameHandle=window.requestAnimationFrame((function(n){return t.tick(n,!0)})),e&&(this._lastAnimationFrame=n)):this._timeoutHandle=window.setTimeout(this.tick,(this.targetTime-n-100)/2)}},{key:"run",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now();this._running?console.log("Cannot restart previously run timer"):(this.targetTime=this.targetTime||t+this.delay,this.tick(),this._running=!0)}},{key:"cancel",value:function(){window.clearTimeout(this._timeoutHandle),window.cancelAnimationFrame(this._animationFrameHandle)}}]),t}();function St(t){return(St="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function jt(t,n){return!n||"object"!==St(n)&&"function"!=typeof n?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):n}function Et(t,n,e){return(Et="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,n,e){var r=function(t,n){for(;!Object.prototype.hasOwnProperty.call(t,n)&&null!==(t=At(t)););return t}(t,n);if(r){var o=Object.getOwnPropertyDescriptor(r,n);return o.get?o.get.call(e):o.value}})(t,n,e||t)}function At(t){return(At=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function kt(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&Tt(t,n)}function Tt(t,n){return(Tt=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}function Pt(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){It(t,n,e[n])}))}return t}function Rt(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function _t(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function Mt(t,n,e){return n&&_t(t.prototype,n),e&&_t(t,e),t}function It(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function Ct(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function Ft(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var Nt=async function(t,n,e){var r=await fetch(t,e);if(!r.ok)throw new Error("Couldn't load audio from ".concat(r.url));var o=await r.arrayBuffer();try{var i=await function(t,n){return new Promise((function(e,r){t.decodeAudioData(n,e,r)}))}(n,o);if(!i)throw new Error("No data available after decoding ".concat(t));return i}catch(n){throw new Error("Error decoding audio data from ".concat(t))}},Lt=function(t,n){var e,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};switch(t){case"oscillator":e=n.createOscillator();break;case"bufferSource":e=n.createBufferSource();break;default:throw new Error("Can't create node of unknown type")}return Object.entries(r).forEach((function(t){var n=Ft(t,2),r=n[0],o=n[1];o&&(e[r]=o)})),Object.entries(o).forEach((function(t){var n=Ft(t,2),r=n[0],o=n[1];o&&(e[r].value=o)})),e},Dt=function(){function t(n){var e,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Rt(this,t),It(this,"defaultPayload",{panningModel:"equalpower"}),this.timeline=n,this.options=r,this.payload=Pt({},this.defaultPayload,o,{gain:null!==(e=o.gain)&&void 0!==e?e:1}),this.processingChain=[],this.nodeOrder={}}return Mt(t,[{key:"setAudioOrigin",value:function(){this.audioSyncOrigin=function(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return n&&"getOutputTimestamp"in t?at({},t.getOutputTimestamp(),{baseLatency:t.baseLatency||0}):{contextTime:t.currentTime,performanceTime:performance.now(),baseLatency:t.baseLatency||0}}(this.timeline.controller.audioContext)}},{key:"schedule",value:function(t){return function(t,n){var e=n.contextTime;return(t-n.performanceTime)/1e3+e-n.baseLatency}(t,this.audioSyncOrigin)}},{key:"prepare",value:function(){var t=this.timeline.controller.audioContext;if("number"==typeof this.payload.gain&&1!==this.payload.gain||this.payload.rampUp&&0!==this.payload.rampUp||this.payload.rampDown&&0!==this.payload.rampDown){var n=t.createGain();n.gain.value=this.payload.rampUp?Math.pow(10,-10):this.payload.gain,this.nodeOrder.gain=this.processingChain.push(n)-1}if(this.payload.pan&&0!==this.payload.pan){var e=t.createPanner();e.panningModel=this.payload.panningModel,e.setPosition(this.payload.pan,0,1-Math.abs(this.payload.pan)),this.processingChain.push(e)}!function(t,n,e){[t].concat(Ct(n),[e]).reduce((function(t,n){return t.connect(n),n}))}(this.source,this.processingChain,t.destination)}},{key:"start",value:function(t){var n=this.options.start,e=this.payload.rampUp,r=this.timeline.controller.audioContext;"running"!==r.state&&console.warn("Sending audio to a context in ".concat(r.state," state."),"This may result in missing sounds —","Please make sure that users interact with the page","before using audio."),this.setAudioOrigin();var o=Math.max(0,this.schedule(t+n));if(e){var i=this.processingChain[this.nodeOrder.gain].gain,a=this.schedule(t+n+parseFloat(e));i.setValueAtTime(Math.pow(10,-10),o),i.exponentialRampToValueAtTime(this.payload.gain,a)}this.source.start(o)}},{key:"afterStart",value:function(t){var n=this.options.stop,e=this.payload.rampDown;if(n&&e){var r=this.processingChain[this.nodeOrder.gain].gain,o=this.schedule(t+n-parseFloat(e)),i=this.schedule(t+n);r.setValueAtTime(this.payload.gain,o),r.exponentialRampToValueAtTime(1e-4,i)}if(n){var a=this.schedule(t+n);this.source.stop(a)}}},{key:"end",value:function(t,n){var e=this,r=n||!this.options.stop,o=r?t:this.timeline.offset+this.options.stop;if(r){var i=this.schedule(t);this.source.stop(i)}window.setTimeout((function(){return bt((function(){return e.teardown()}))}),o-performance.now()+20)}},{key:"teardown",value:function(){this.source.disconnect(),this.source=void 0,this.processingChain.forEach((function(t){return t.disconnect()})),this.processingChain=[],this.nodeOrder={}}}]),t}(),Ut=function(t){function n(){return Rt(this,n),jt(this,At(n).apply(this,arguments))}return kt(n,t),Mt(n,[{key:"prepare",value:async function(){var t=this.timeline.controller,e=t.cache,r=t.audioContext,o=this.payload,i=o.src,a=o.loop,u=await e.audio.get(i);this.source=Lt("bufferSource",r,{buffer:u,loop:a}),Et(At(n.prototype),"prepare",this).call(this)}}]),n}(Dt),qt=function(t){function n(){return Rt(this,n),jt(this,At(n).apply(this,arguments))}return kt(n,t),Mt(n,[{key:"prepare",value:function(){var t=this.payload,e=t.type,r=t.frequency,o=t.detune;this.source=Lt("oscillator",this.timeline.controller.audioContext,{type:e},{frequency:r,detune:o}),Et(At(n.prototype),"prepare",this).call(this)}}]),n}(Dt);function Bt(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function zt(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var Vt=function(){function t(n){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];Bt(this,t),this.controller=n,this.events=e,this.offset=void 0}return function(t,n,e){n&&zt(t.prototype,n),e&&zt(t,e)}(t,[{key:"prepare",value:async function(){var t=this,n=it()(this.events,[function(t){return t.start},function(t){return t.priority}]);return this.items=n.map((function(n){var e=rt()(n,"payload");switch(n.type){case"sound":return new Ut(t,e,n.payload);case"oscillator":return new qt(t,e,n.payload);default:console.warn("Unknown event type ".concat(n.type,", skipping"))}})),await Promise.all(this.items.map((function(t){return t.prepare()})))}},{key:"start",value:function(t){var n=this;this.items.forEach((function(n){return n.start(t)})),this.offset=t,bt((function(){return n.afterStart()}))}},{key:"afterStart",value:function(){var t=this;this.items.forEach((function(n){return n.afterStart(t.offset)}))}},{key:"end",value:async function(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Promise.all(this.items.map((function(e){return e.end(t,n)})))}},{key:"teardown",value:async function(){}}]),t}();e(212),e(159),e(510);function Wt(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function Ht(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function $t(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var Gt={Space:" "},Yt=function(t){var n=$t(t,3);return{eventName:n[0],filters:n[1],selector:n[2]}},Jt=function(){function t(n){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t),this.el=n.el||document,this.events=n.events||{},this.parsedEvents=[],this.context=n.context||this,this.processEvent=n.processEvent||Yt,this.startTime=-1/0}return function(t,n,e){n&&Ht(t.prototype,n),e&&Ht(t,e)}(t,[{key:"wrapHandler",value:function(t,n){return null!==this.context&&(t=t.bind(this.context)),function(e){return n.reduce((function(t,n){return t&&n(e)}),!0)?t(e):null}}},{key:"prepare",value:function(){var t=this;this.parsedEvents=Object.entries(this.events).map((function(n){var e=$t(n,2),r=e[0],o=e[1],i=t.processEvent(function(t){var n=/^(\w+)\s*([^()]*)$/,e=/^(\w+)\(([\w\s,]+)\)\s*(.*)$/,r=null,o=null,i=null;if(n.test(t)){var a=$t(n.exec(t),3);r=a[1],i=a[2]}else if(e.test(t)){var u=$t(e.exec(t),4);r=u[1],o=u[2],i=u[3],o=o.split(",").map((function(t){return t.trim()}))}else console.log("Can't interpret event string ",t);return[r,o,i]}(r)),a=i.eventName,u=i.filters,s=i.selector,c=i.moreChecks,f=void 0===c?[]:c;return[r,a,s,t.wrapHandler(o,[].concat(Wt(function(t,n){var e=n.filters,r=void 0===e?[]:e,o=n.filterRepeat,i=void 0===o||o,a=n.startTime,u=void 0===a?-1/0:a,s=[];if(s.push((function(t){return mt(t.timeStamp)>=u})),["keypress","keydown","keyup"].includes(t)){var c=(r||[]).map((function(t){return Gt[t]||t}));(c.length>0||i)&&s.push((function(t){return!(i&&t.repeat||c.length>0&&!c.includes(t.key))}))}else if(["click","mousedown","mouseup"].includes(t)){var f=(r||[]).map((function(t){return parseInt(t)}));f.length>0&&s.push((function(t){return f.includes(t.button)}))}return s}(a,{filters:u,startTime:t.startTime})),Wt(f)))]}))}},{key:"attach",value:function(){var t=this;this.parsedEvents.forEach((function(n){var e=$t(n,4),r=e[1],o=e[2],i=e[3];""!==o?Array.from(t.el.querySelectorAll(o)).forEach((function(t){return t.addEventListener(r,i)})):document.addEventListener(r,i)}))}},{key:"detach",value:function(){var t=this;this.parsedEvents.forEach((function(n){var e=$t(n,4),r=e[1],o=e[2],i=e[3];""!==o?Array.from(t.el.querySelectorAll(o)).forEach((function(t){return t.removeEventListener(r,i)})):document.removeEventListener(r,i)}))}},{key:"teardown",value:function(){this.parsedEvents=null}}]),t}(),Kt=(e(150),e(233),e(236),e(237),e(238),e(239),e(240),e(241),e(242),e(243),e(244),e(245),e(246),e(247),e(248),e(249),e(250),e(251),e(252),e(253),e(254),e(255),e(256),e(257),e(258),e(259),e(298)),Xt=e.n(Kt),Qt=e(55),Zt=e.n(Qt),tn=e(299),nn=e.n(tn),en=e(300),rn=e.n(en),on=function(t,n){return function(e){return function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(t,n){return t===n};if(0===t.length)return 0;for(var e=1,r=1,o=0;o<t.length;o++)r>e&&(e=r),n(t[o],t[o+1])?r++:r=1;return e}(e,n)<=t}},an=function(t,n){return function(e){return function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(t){return t};if(0!==t.length){for(var e={},r=1/0,o=0;o<t.length;o++){var i=t[o],a=n(i);if(void 0!==e[a]){var u=o-e[a];r>u&&(r=u)}e[a]=o}return r}}(e,n)>=t}};function un(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function sn(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function cn(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var fn=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Math.random;return("00000000-0000-4000-8000-000000000000".replace(/[08]/g,(function(n){return(n^16*t()>>n/4).toString(16)})))},ln=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256,n=new Uint8Array(t);return(window.crypto||window.msCrypto).getRandomValues(n),String.fromCharCode.apply(null,n)},pn=function(){function Random(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};sn(this,Random),"alea"===t.algorithm?this.random=rn()(t.seed||ln()):this.random=Math.random}return function(t,n,e){n&&cn(t.prototype,n),e&&cn(t,e)}(Random,[{key:"range",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,e=void 0===n?0:t,r=void 0===n?t:n-t;return e+Math.floor(this.random()*r)}},{key:"choice",value:function(t){return t[this.range(t.length)]}},{key:"sample",value:function(t){var n=this,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return r?Array(e).fill(0).map((function(){return n.choice(t)})):this.shuffle(t).slice(0,nn()(e,t.length))}},{key:"sampleMode",value:function(t,n){var e=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"draw-shuffle";if(!(Array.isArray(t)&&t.length>0))throw new Error("Can't sample: Empty input, or not an array");var o=n||t.length,i=Math.floor(o/t.length),a=o%t.length;switch(r){case"sequential":return[].concat(un(Zt()(i).reduce((function(n){return n.concat(t)}),[])),un(t.slice(0,a)));case"draw":case"draw-shuffle":var u=[].concat(un(Zt()(i).reduce((function(n){return n.concat(e.shuffle(t))}),[])),un(this.sample(t,a,!1)));return"draw-shuffle"===r&&o>t.length?this.shuffle(u):u;case"draw-replace":return this.sample(t,o,!0);default:throw new Error("Unknown sample mode, please specify")}}},{key:"shuffle",value:function(t){for(var n=t.slice(),e=n.length;0!==e;){var r=this.range(e--),o=[n[r],n[e]];n[e]=o[0],n[r]=o[1]}return n}},{key:"constrainedShuffle",value:function(t){var n,e,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Math.pow(10,4);if(E()(r))n=r;else{var a=[];r.maxRepSeries&&a.push(on(r.maxRepSeries,o.equality)),r.minRepDistance&&a.push(an(r.minRepDistance,o.hash)),n=function(t){return a.reduce((function(n,e){return n&&e(t)}),!0)}}for(var u=0;u<i&&!n(e=this.shuffle(t));u++);return e}},{key:"shuffleTable",value:function(t){var n=this,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=e.map((function(n){return t.map((function(t){return f()(t,n)}))})),i=m()(e),a=t.map((function(t){return rt()(t,i)}));return Xt.a.apply(void 0,un(o.map((function(t){return{data:n.shuffle(t)}}))).concat([{data:r?this.shuffle(a):a}])).data}},{key:"uuid4",value:function(){return fn(this.random)}}]),Random}(),hn=(e(161),e(73)),dn=e.n(hn),vn=e(301),gn=e.n(vn),yn=e(72),mn=e.n(yn),bn=e(45),wn=e.n(bn),xn=e(302),On=e.n(xn);function Sn(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function jn(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var En=function(t){return Object.assign.apply(Object,[{}].concat(jn(function(t){for(var n=[Object.getPrototypeOf(t)];Object.getPrototypeOf(n[0]);)n.unshift(Object.getPrototypeOf(n[0]));return n}(t).map((function(t){var n;return null===(n=t.constructor.metadata)||void 0===n?void 0:n.parsableOptions})))))},An=function t(n,e,r){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!r)return n;if(!On()(n))return wn()(n)?n.map((function(n){return t(n,e,r.content,o)})):mn()(n)?dn()(Object.entries(n).map((function(n){var i,a,u=Sn(n,2),s=u[0],c=u[1];return[r.keys?t(s,e,{},o):s,t(c,e,(null===(i=r.content)||void 0===i?void 0:i[s])||(null===(a=r.content)||void 0===a?void 0:a["*"]),o)]}))):n;var i=gn()(n,{escape:"",evaluate:""}).call(o,e);switch(r.type){case void 0:return i;case"number":return Number(i);case"boolean":return Boolean("false"!==i.trim());default:throw new Error("Output type ".concat(r.type," unknown, can't convert option"))}},kn=function(t,n,e,r){return dn()(Object.entries(e).map((function(e){var o=Sn(e,2),i=o[0],a=o[1];if(t[i]){var u=An(t[i],n,a,r);if(u!==t[i])return[i,u]}})).filter((function(t){return void 0!==t})))},Tn=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"complete";return(new Promise((function(n){if(document.readyState===t)n();else{document.addEventListener("readystatechange",(function e(r){r.target.readyState===t&&(r.target.removeEventListener("readystatechange",e),n())}))}})))};e(227),e(230);function Pn(t){return(Pn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function Rn(t,n){return!n||"object"!==Pn(n)&&"function"!=typeof n?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):n}function _n(t,n,e){return(_n="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,n,e){var r=function(t,n){for(;!Object.prototype.hasOwnProperty.call(t,n)&&null!==(t=Mn(t)););return t}(t,n);if(r){var o=Object.getOwnPropertyDescriptor(r,n);return o.get?o.get.call(e):o.value}})(t,n,e||t)}function Mn(t){return(Mn=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function In(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&Cn(t,n)}function Cn(t,n){return(Cn=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}function Fn(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function Nn(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function Ln(t,n,e){return n&&Nn(t.prototype,n),e&&Nn(t,e),t}function Dn(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}var Un=function(){function t(n){Fn(this,t),Dn(this,"cache",new Map),Dn(this,"pending",new Map),this.cachedFunc=n}return Ln(t,[{key:"get",value:async function(t){if(this.cache.has(t))return this.cache.get(t);if(this.pending.has(t))return await this.pending.get(t);var n=this.cachedFunc(t);this.pending.set(t,n);var e=await n;return this.cache.set(t,e),this.pending.delete(t),e}},{key:"getAll",value:async function(t){var n=this;return Promise.all(t.map((function(t){return n.get(t)})))}},{key:"readSync",value:function(t){if(this.cache.has(t))return this.cache.get(t);throw Error('Key "'.concat(t,'" not present in cache'))}}]),t}(),qn=async function(t){var n=new Image;return n.src=t,await n.decode(),n},Bn=function(t){function n(){var t;return Fn(this,n),(t=Rn(this,Mn(n).call(this,qn))).bitmapCache=new WeakMap,t}return In(n,t),Ln(n,[{key:"get",value:async function(t){var e=await _n(Mn(n.prototype),"get",this).call(this,t);if(window.createImageBitmap)try{var r=await createImageBitmap(e);this.bitmapCache.set(e,r)}catch(n){console.log("Couldn't cache bitmap for ".concat(t,", error ").concat(n))}return e}},{key:"readSync",value:function(t){var e=_n(Mn(n.prototype),"readSync",this).call(this,t);return[e,this.bitmapCache.get(e)]}}]),n}(Un),zn=function(t){function n(t){return Fn(this,n),Rn(this,Mn(n).call(this,(function(n){return Nt(n,t)})))}return In(n,t),n}(Un);function Vn(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var Wn=function t(n,e){e(n);var r=Object.getPrototypeOf(n).constructor.metadata;r.nestedComponents&&r.nestedComponents.forEach((function(r){var o=n.options[r];wn()(o)?o.map((function(n){return t(n,e)})):o instanceof se&&t(o,e)}))},Hn=function(t,n,e){var r=w()(e);return Wn(t,(function(t){return r=n(r,t)})),r},$n=function(t,n){return Object.assign.apply(Object,[{}].concat(Vn(t.parents.map((function(t){return t.options[n]||{}}))),[t.options[n]]))};function Gn(t){return(Gn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function Yn(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function Jn(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){ne(t,n,e[n])}))}return t}function Kn(t,n){return!n||"object"!==Gn(n)&&"function"!=typeof n?Qn(t):n}function Xn(t){return(Xn=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Qn(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Zn(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&te(t,n)}function te(t,n){return(te=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}function ne(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function ee(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function re(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function oe(t,n,e){return n&&re(t.prototype,n),e&&re(t,e),t}var ie=Object.freeze({initialized:0,prepared:1,running:2,done:3}),ae=["debug","el"],ue=function(){function t(){ee(this,t),this.datastore=new nt,this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.cache={images:new Bn,audio:new zn(this.audioContext)},this.domConnection=new Jt({el:document,context:this}),this.domConnection.events={keydown:this.indicateInteraction,mousedown:this.indicateInteraction,touchstart:this.indicateInteraction},this.domConnection.prepare(),this.domConnection.attach()}return oe(t,[{key:"indicateInteraction",value:async function(){"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.domConnection.detach()}}]),t}(),se=function(t){function Component(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ee(this,Component),ne(Qn(t=Kn(this,Xn(Component).call(this,Jn({events:{},messageHandlers:{},timeline:[],el:null,controller:null,title:null,id:null,tardy:!1,skip:!1,scrollTop:!1,parent:null,parameters:{},responses:{},correctResponse:null,data:{},datacommit:null,random:{},timeout:null,handMeDowns:[].concat(ae)},n,{media:Jn({images:[],audio:[]},n.media),files:Jn({},n.files),timing:Jn({method:"frames"},n.timing)})))),"status",ie.initialized),ne(Qn(t),"data",{}),ne(Qn(t),"internals",Jn({timestamps:{}},t.internals)),ne(Qn(t),"parameters",new window.Proxy({},{get:function(n,e){return t.aggregateParameters[e]},set:function(n,e,r){return(t.options.parameters[e]=r)||!0},has:function(n,e){return Reflect.has(t.aggregateParameters,e)},ownKeys:function(n,e){return Reflect.ownKeys(t.aggregateParameters)},getOwnPropertyDescriptor:function(n,e){return Reflect.getOwnPropertyDescriptor(t.aggregateParameters,e)}})),ne(Qn(t),"state",new window.Proxy({},{get:function(n,e){if(t.options.datastore)return t.options.datastore.state[e];throw new Error("No datastore to read state from")},set:function(n,e,r){if(t.options.datastore)return t.options.datastore.set(e,r),!0;throw new Error("No datastore to save state to")},has:function(n,e){if(t.options.datastore)return Reflect.has(t.options.datastore.state,e);throw new Error("No datastore to read state from")},ownKeys:function(n){if(t.options.datastore)return Reflect.ownKeys(t.options.datastore.state);throw new Error("No datastore to read state from")},getOwnPropertyDescriptor:function(n,e){if(t.options.datastore)return Reflect.getOwnPropertyDescriptor(t.options.datastore.state,e);throw new Error("No datastore to read state from")}})),ne(Qn(t),"files",new window.Proxy({},{get:function(n,e){return t._aggregateFiles[e]},set:function(n,e,r){return(t.options.files[e]=r)||!0},has:function(n,e){return Reflect.has(t._aggregateFiles,e)},ownKeys:function(n,e){return Reflect.ownKeys(t._aggregateFiles)},getOwnPropertyDescriptor:function(n,e){return Reflect.getOwnPropertyDescriptor(t._aggregateFiles,e)}})),t.internals.parsedOptions=Object.create(t.internals.rawOptions),t.options=new a.a(t.internals.rawOptions,{get:function(n,e){return t.internals.parsedOptions[e]},set:function(n,e,r){if(t.internals.rawOptions[e]=r,t.status>=ie.prepared){var o=An(r,{parameters:t.aggregateParameters,state:t.options.datastore.state,files:t._aggregateFiles,random:t.random},En(Qn(t))[e],Qn(t));o!==r&&(t.internals.parsedOptions[e]=o)}return!0}}),Object.keys(t.options.messageHandlers).forEach((function(n){return t.on(n,t.options.messageHandlers[n])})),t.internals.domConnection=new Jt({el:t.options.el,context:Qn(t)}),t.on("run",(function(){t.internals.domConnection.attach()})),t.on("end",(function(){t.internals.domConnection.detach()})),t}return Zn(Component,t),oe(Component,[{key:"prepare",value:async function(){var t=this,n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!this.options.tardy||n){this.parent&&this.parents.reduce((function(t,n){return n.options.handMeDowns.forEach((function(n){return t.add(n)})),t}),new Set).forEach((function(n){t.options[n]=t.options[n]||t.parent.options[n]})),this.parent&&this.parent.internals.controller?this.internals.controller=this.parent.internals.controller:(this.internals.controller=new ue,this.once("after:prepare",Tn)),this.options.datastore=this.internals.controller.datastore,this.internals.timeline=new Vt(this.internals.controller),this.options.debug&&(this.on("before:run",(function(){return console.group("".concat(t.options.title," %c(").concat(t.type,")"),"font-weight: normal")})),this.on("after:end",(function(){return console.groupEnd()}))),this.options.debug&&null==this.options.el&&console.log("No output element specified, using main section"),this.options.el=this.options.el||document.querySelector('[data-labjs-section="main"]'),this.internals.root=this.parents[0],this.random=new pn(this.options.random),await this.triggerMethod("before:prepare");var e=Object.freeze({parameters:this.aggregateParameters,state:this.options.datastore.state,files:this._aggregateFiles,random:this.random}),r=kn(this.internals.rawOptions,e,En(this),e);if(this.internals.parsedOptions=Object.assign(Object.create(this.internals.rawOptions),r),Object.keys(this.options.responses).forEach((function(n){t.options.events[n]=function(e){e.preventDefault(),t.respond(t.options.responses[n],{timestamp:mt(e.timeStamp),action:n})}})),this.internals.domConnection.events=this.options.events,this.internals.domConnection.el=this.options.el,null!==this.options.timeout){var o="frames"===this.options.timing.method?Ot:wt;this.internals.timeout=new o((function(n){return t.end("timeout",n,!0)}),this.options.timeout),this.on("show",(function(n){t.internals.timeout.run(n),t.options.debug&&(t.internals.timestamps.timeoutTarget=t.internals.timeout.targetTime)}))}this.data=Jn({},this.data,this.options.data),await this.triggerMethod("prepare",n),this.status=ie.prepared,await this.preload(),this.internals.timeline.events=this.options.timeline,await this.internals.timeline.prepare(),this.internals.domConnection.prepare(),await this.triggerMethod("after:prepare")}else this.options.debug&&console.log("Skipping automated preparation")}},{key:"preload",value:async function(){await Promise.all([this.internals.controller.cache.images.getAll(this.options.media.images),this.internals.controller.cache.audio.getAll(this.options.media.audio)])}},{key:"run",value:async function(t,n){return this.status<ie.prepared&&(this.options.debug&&console.log("Preparing at the last minute"),await this.prepare()),await this.triggerMethod("before:run"),this.status=ie.running,this.internals.timestamps.run=performance.now(),this.options.skip?this.end("skipped",t,n):(this.options.scrollTop&&window.scrollTo(0,0),await this.triggerMethod("run",t,n),this.render(t,n))}},{key:"render",value:async function(t,n){var e=this,r=async function(t){e.internals.timestamps.render=t,await e.triggerMethod("render",t),e.internals.timeline.start(t+gt.frameInterval),e.internals.showFrameRequest=window.requestAnimationFrame((function(t){e.internals.timestamps.show=t,e.triggerMethod("show",t)}))};n?r(t):this.internals.frameRequest=window.requestAnimationFrame(r)}},{key:"respond",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=n.timestamp,r=n.action;return this.data.response=t,r&&(this.data.response_action=r),null!==this.options.correctResponse&&(this.data.correctResponse=this.options.correctResponse,this.data.correct=t===this.options.correctResponse),this.end("response",e)}},{key:"end",value:async function(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:performance.now(),r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.internals.timestamps.end=e,this.data.ended_on=n,this.status=ie.done,null!==this.options.timeout&&this.internals.timeout.cancel(),this.internals.frameRequest&&window.cancelAnimationFrame(this.internals.frameRequest),this.internals.showFrameRequest&&window.cancelAnimationFrame(this.internals.showFrameRequest),"timeout"===this.data.ended_on||"response"===this.data.ended_on&&"Safari"===ft?this.data.duration=this.internals.timestamps.end-this.internals.timestamps.render:this.data.duration=this.internals.timestamps.end-(this.internals.timestamps.show||this.internals.timestamps.render),await this.triggerMethod("end",e,r),this.internals.timeline.end(e+gt.frameInterval),!1!==this.options.datacommit&&this.commit(Jn({},this.aggregateParameters,this.data,{time_run:this.internals.timestamps.run,time_render:this.internals.timestamps.render,time_show:this.internals.timestamps.show,time_end:this.internals.timestamps.end})),await this.triggerMethod("after:end",e,r);var o=function(n){t.internals.timestamps.switch=n,t.options.datastore.update(t.internals.logIndex,(function(t){return Jn({},t,{time_switch:n,duration:"timeout"===t.ended_on?n-(t.time_show||t.time_render):t.duration})})),bt((function(){return t.options.datastore.triggerMethod("idle")})),bt((function(){return t.epilogue()}))};return r?window.requestAnimationFrame(o):window.requestAnimationFrame((function(){return window.requestAnimationFrame(o)})),e}},{key:"epilogue",value:function(){this.internals.timeline.teardown(),this.internals.domConnection.teardown(),this.triggerMethod("epilogue")}},{key:"commit",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.internals.logIndex=this.options.datastore.commit(Jn({},this.metadata,t,{time_commit:performance.now(),timestamp:(new Date).toISOString()})),this.triggerMethod("commit")}},{key:"clone",value:function(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.constructor.metadata.nestedComponents||[],r=Jn({},o()(this.internals.rawOptions,(function(n,r,o){if(o===t.internals.rawOptions&&e.includes(r)){if(Array.isArray(n))return n.map((function(t){return t instanceof Component?t.clone():t}));if(n instanceof Component)return n.clone()}})),n);return new this.constructor(r)}},{key:"timer",get:function(){var t=this.internals.timestamps;switch(this.status){case ie.running:return performance.now()-(t.show||t.render);case ie.done:return this.internals.timestamps.end-(t.show||t.run);default:return}}},{key:"progress",get:function(){return 1*(this.status===ie.done)}},{key:"aggregateParameters",get:function(){return $n(this,"parameters")}},{key:"_aggregateFiles",get:function(){return $n(this,"files")}},{key:"id",get:function(){return this.options.id.split("_").map((function(t){return parseInt(t)||t}))}},{key:"metadata",get:function(){return{sender:this.options.title,sender_type:this.type,sender_id:this.options.id}}},{key:"parents",get:function(){for(var t=[],n=this;n.parent;)n=n.parent,t=t.concat(n);return t.reverse()}},{key:"type",get:function(){return[].concat(Yn(this.constructor.metadata.module),[this.constructor.name]).join(".")}}]),Component}(C);se.metadata={module:["core"],nestedComponents:[],parsableOptions:{parameters:{type:"object",content:{"*":{}}},responses:{keys:{},content:{"*":"string"}},correctResponse:{},timeline:{type:"array",content:{type:"object",content:{start:{type:"number"},stop:{type:"number"},"*":"string",payload:{type:"object",content:{gain:{type:"number"},loop:{type:"boolean"},"*":"string"}}}}},timeout:{type:"number"},skip:{type:"boolean"}}};var Dummy=function(t){function Dummy(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ee(this,Dummy),Kn(this,Xn(Dummy).call(this,Jn({skip:!0},t)))}return Zn(Dummy,t),Dummy}(se),ce=e(187),fe=e.n(ce);function le(t){return(le="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function pe(t,n,e){return(pe="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,n,e){var r=function(t,n){for(;!Object.prototype.hasOwnProperty.call(t,n)&&null!==(t=we(t)););return t}(t,n);if(r){var o=Object.getOwnPropertyDescriptor(r,n);return o.get?o.get.call(e):o.value}})(t,n,e||t)}function he(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function de(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){ve(t,n,e[n])}))}return t}function ve(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function ge(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function ye(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function me(t,n,e){return n&&ye(t.prototype,n),e&&ye(t,e),t}function be(t,n){return!n||"object"!==le(n)&&"function"!=typeof n?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):n}function we(t){return(we=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function xe(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&Oe(t,n)}function Oe(t,n){return(Oe=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}var Se=function(t,n){return t.forEach((function(t){return t.parent=n})),t.forEach((function(t,e){null==n.options.id?t.options.id=String(e):t.options.id=[n.options.id,e].join("_")})),Promise.all(t.map((function(t){return t.prepare(!1)})))},je=function(t){function Sequence(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ge(this,Sequence),(t=be(this,we(Sequence).call(this,de({content:[],shuffle:!1,indexParameter:void 0},n)))).internals.currentComponent=null,t.internals.currentPosition=null,t}return xe(Sequence,t),me(Sequence,[{key:"onPrepare",value:async function(){var t=this;this.options.shuffle&&(this.options.content=this.random.shuffle(this.options.content)),this.options.indexParameter&&this.options.content.forEach((function(n,e){return n.options.parameters[t.options.indexParameter]=e})),this.internals.iterator=this.options.content.entries(),this.internals.stepper=this.step.bind(this),await Se(this.options.content,this)}},{key:"onRun",value:async function(t,n){return this.step(t,n)}},{key:"onEnd",value:function(){this.internals.currentComponent&&this.internals.currentComponent.status!==ie.done&&(this.internals.currentComponent.off("after:end",this.internals.stepper),this.internals.currentComponent.end("abort by sequence"))}},{key:"step",value:async function(t,n){if(this.status===ie.done)throw new Error("Sequence ended, can't take any more steps");var e=this.internals.iterator.next();if(e.done)return this.end("completion",t,n);var r=he(e.value,2);return this.internals.currentPosition=r[0],this.internals.currentComponent=r[1],this.internals.currentComponent.on("after:end",this.internals.stepper),this.internals.currentComponent.run(t,n)}},{key:"progress",get:function(){return this.status===ie.done?1:fe()(this.options.content.map((function(t){return t.progress})))}}]),Sequence}(se);je.metadata={module:["flow"],nestedComponents:["content"],parsableOptions:{shuffle:{type:"boolean"}}};var Ee=function(t){function Loop(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ge(this,Loop),be(this,we(Loop).call(this,de({template:null,templateParameters:[],sample:{n:void 0,mode:"sequential"},shuffleGroups:void 0,shuffleUngrouped:!1},t)))}return xe(Loop,t),me(Loop,[{key:"onPrepare",value:function(){var t=this,n=[];if(Array.isArray(this.options.templateParameters)&&this.options.templateParameters.length>0){var e=Array.isArray(this.options.shuffleGroups)&&this.options.shuffleGroups.length?this.random.shuffleTable(this.options.templateParameters,this.options.shuffleGroups,this.options.shuffleUngrouped):this.options.templateParameters;n=this.random.sampleMode(e,this.options.sample.n,!0===this.options.sample.replace?"draw-replace":this.options.sample.mode)}else console.warn("Empty or invalid parameter set for loop, no content generated");return this.options.template instanceof se?this.options.content=n.map((function(n){var e=t.options.template.clone();return e.options.parameters=de({},e.options.parameters,n),e})):E()(this.options.template)?this.options.content=n.map((function(n,e){return t.options.template(n,e,t)})):console.warn("Missing or invalid template in loop, no content generated"),pe(we(Loop.prototype),"onPrepare",this).call(this)}}]),Loop}(je);Ee.metadata={module:["flow"],nestedComponents:["template"],parsableOptions:{templateParameters:{type:"array",content:{content:{"*":{}}}},sample:{type:"object",content:{n:{type:"number"},replace:{type:"boolean"},mode:{}}}}};var Ae=function(t){function Parallel(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ge(this,Parallel),be(this,we(Parallel).call(this,de({content:[],mode:"race"},t)))}return xe(Parallel,t),me(Parallel,[{key:"onPrepare",value:async function(){await Se(this.options.content,this)}},{key:"onRun",value:function(t){var n=this;return Promise[this.options.mode](this.options.content.map((function(t){return t.waitFor("end")}))).then((function(){return n.end()})),Promise.all(this.options.content.map((function(n){return n.run(t)})))}},{key:"onEnd",value:function(){this.options.content.forEach((function(t){t.status<ie.done&&t.end("abort by parallel")}))}},{key:"progress",get:function(){return this.status===ie.done?1:fe()(this.options.content.map((function(t){return t.progress})))}}]),Parallel}(se);Ae.metadata={module:["flow"],nestedComponents:["content"],parsableOptions:{mode:{}}};e(149);var ke=function(){function t(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(n,e,r){return e&&t(n.prototype,e),r&&t(n,r),n}}(),Te=function(t,n){return Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(n)}}))}(["",""],["",""]);function Pe(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}var Re=function(){function t(){for(var n=this,e=arguments.length,r=Array(e),o=0;o<e;o++)r[o]=arguments[o];return Pe(this,t),this.tag=function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),o=1;o<e;o++)r[o-1]=arguments[o];return"function"==typeof t?n.interimTag.bind(n,t):"string"==typeof t?n.transformEndResult(t):(t=t.map(n.transformString.bind(n)),n.transformEndResult(t.reduce(n.processSubstitutions.bind(n,r))))},r.length>0&&Array.isArray(r[0])&&(r=r[0]),this.transformers=r.map((function(t){return"function"==typeof t?t():t})),this.tag}return ke(t,[{key:"interimTag",value:function(t,n){for(var e=arguments.length,r=Array(e>2?e-2:0),o=2;o<e;o++)r[o-2]=arguments[o];return this.tag(Te,t.apply(void 0,[n].concat(r)))}},{key:"processSubstitutions",value:function(t,n,e){var r=this.transformSubstitution(t.shift(),n);return"".concat(n,r,e)}},{key:"transformString",value:function(t){return this.transformers.reduce((function(t,n){return n.onString?n.onString(t):t}),t)}},{key:"transformSubstitution",value:function(t,n){return this.transformers.reduce((function(t,e){return e.onSubstitution?e.onSubstitution(t,n):t}),t)}},{key:"transformEndResult",value:function(t){return this.transformers.reduce((function(t,n){return n.onEndResult?n.onEndResult(t):t}),t)}}]),t}(),_e=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return{onEndResult:function(n){if(""===t)return n.trim();if("start"===(t=t.toLowerCase())||"left"===t)return n.replace(/^\s*/,"");if("end"===t||"right"===t)return n.replace(/\s*$/,"");throw new Error("Side not supported: "+t)}}};function Me(t){if(Array.isArray(t)){for(var n=0,e=Array(t.length);n<t.length;n++)e[n]=t[n];return e}return Array.from(t)}var Ie=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"initial";return{onEndResult:function(n){if("initial"===t){var e=n.match(/^[^\S\n]*(?=\S)/gm),r=e&&Math.min.apply(Math,Me(e.map((function(t){return t.length}))));if(r){var o=new RegExp("^.{"+r+"}","gm");return n.replace(o,"")}return n}if("all"===t)return n.replace(/^[^\S\n]+/gm,"");throw new Error("Unknown type: "+t)}}},Ce=function(t,n){return{onEndResult:function(e){if(null==t||null==n)throw new Error("replaceResultTransformer requires at least 2 arguments.");return e.replace(t,n)}}},Fe=function(t,n){return{onSubstitution:function(e,r){if(null==t||null==n)throw new Error("replaceSubstitutionTransformer requires at least 2 arguments.");return null==e?e:e.toString().replace(t,n)}}},Ne={separator:"",conjunction:"",serial:!1},Le=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ne;return{onSubstitution:function(n,e){if(Array.isArray(n)){var r=n.length,o=t.separator,i=t.conjunction,a=t.serial,u=e.match(/(\n?[^\S\n]+)$/);if(n=u?n.join(o+u[1]):n.join(o+" "),i&&r>1){var s=n.lastIndexOf(o);n=n.slice(0,s)+(a?o:"")+" "+i+n.slice(s+1)}}return n}}},De=function(t){return{onSubstitution:function(n,e){if(null==t||"string"!=typeof t)throw new Error("You need to specify a string character to split by.");return"string"==typeof n&&n.includes(t)&&(n=n.split(t)),n}}},Ue=function(t){return null!=t&&!Number.isNaN(t)&&"boolean"!=typeof t},qe=function(){return{onSubstitution:function(t){return Array.isArray(t)?t.filter(Ue):Ue(t)?t:""}}},Be=(new Re(Le({separator:","}),Ie,_e),new Re(Le({separator:",",conjunction:"and"}),Ie,_e),new Re(Le({separator:",",conjunction:"or"}),Ie,_e),new Re(De("\n"),qe,Le,Ie,_e),new Re(De("\n"),Le,Ie,_e,Fe(/&/g,"&"),Fe(/</g,"<"),Fe(/>/g,">"),Fe(/"/g,"""),Fe(/'/g,"'"),Fe(/`/g,"`")),new Re(Ce(/(?:\n(?:\s*))+/g," "),_e),new Re(Ce(/(?:\n\s*)/g,""),_e),new Re(Le({separator:","}),Ce(/(?:\s+)/g," "),_e),new Re(Le({separator:",",conjunction:"or"}),Ce(/(?:\s+)/g," "),_e),new Re(Le({separator:",",conjunction:"and"}),Ce(/(?:\s+)/g," "),_e),new Re(Le,Ie,_e),new Re(Le,Ce(/(?:\s+)/g," "),_e),new Re(Ie,_e));new Re(Ie("all"),_e);function ze(){var t=ur(['\n <div class="page-item page-item-likert" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <table class="page-item-table">\n <colgroup>\n <col style="width: 40%">\n ',"\n </colgroup>\n ","\n <tbody>\n ","\n </tbody>\n </table>\n </div>\n "]);return ze=function(){return t},t}function Ve(){var t=ur(['\n <div class="page-item page-item-range" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <input name="','" type="range"\n ','\n class="w-100"\n ',"\n >\n </div>\n "]);return Ve=function(){return t},t}function We(){var t=ur(['\n <div class="page-item page-item-checkbox" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <table class="table-plain page-item-table">\n <colgroup>\n <col style="width: 7.5%">\n <col style="width: 92.5%">\n </colgroup>\n <tbody>\n ',"\n </tbody>\n </table>\n </div>\n "]);return We=function(){return t},t}function He(){var t=ur(['\n <div class="page-item page-item-radio" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <table class="table-plain page-item-table">\n <colgroup>\n <col style="width: 7.5%">\n <col style="width: 92.5%">\n </colgroup>\n <tbody>\n ',"\n </tbody>\n </table>\n </div>\n "]);return He=function(){return t},t}function $e(){var t=ur(['\n <div class="page-item page-item-textarea" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <textarea name="','"\n ','\n class="w-100"\n rows="3"\n ></textarea>\n </div>\n ']);return $e=function(){return t},t}function Ge(){var t=ur(['\n <div class="page-item page-item-input" id="page-item-','">\n <p class="font-weight-bold" style="margin: 1rem 0 0.25rem">\n ','\n </p>\n <p class="small text-muted hide-if-empty" style="margin: 0.25rem 0">\n ','\n </p>\n <input name="','"\n ','\n class="w-100"\n ',"\n >\n </div>\n "]);return Ge=function(){return t},t}function Ye(){var t=ur(['\n <div class="page-item page-item-divider">\n <hr>\n </div>\n ']);return Ye=function(){return t},t}function Je(){var t=ur(['\n <div class="page-item page-item-html">\n ',"\n </div>\n "]);return Je=function(){return t},t}function Ke(){var t=ur(['\n <div class="page-item page-item-image">\n <img\n src="','"\n style="'," ",'"\n >\n </div>\n ']);return Ke=function(){return t},t}function Xe(){var t=ur(['\n <div class="page-item page-item-text">\n <h3>',"</h3>\n ","\n </div>\n "]);return Xe=function(){return t},t}function Qe(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function Ze(){var t=ur(['\n <main\n class="\n content-horizontal-center\n content-vertical-center\n "\n >\n <div class="w-',' text-left">\n <form id="page-form" style="display: block;" autocomplete="off">\n ',"\n </form>\n </div>\n </main>\n ","\n "]);return Ze=function(){return t},t}function tr(){var t=ur(['\n <td class="text-center">\n <label style="height: 100%; padding: 10px 0">\n <input type="radio"\n name="',"-",'" value="','"\n ',"\n >\n </label>\n </td>\n "]);return tr=function(){return t},t}function nr(){var t=ur(['\n <tr>\n <td class="small" style="padding-left: 0">\n ',"\n </td>\n ","\n </tr>\n "]);return nr=function(){return t},t}function er(){var t=ur(['\n <th\n class="sticky-top text-center small"\n style="background-color: white"\n >\n ',"\n </th>\n "]);return er=function(){return t},t}function rr(){var t=ur(['\n <thead class="sticky-top" style="background-color: white">\n <th class="sticky-top" style="background-color: white"></th>\n ',"\n </thead>\n "]);return rr=function(){return t},t}function or(){var t=ur(['\n <tr>\n <td>\n <input\n type="checkbox"\n name="',"-",'"\n id="',"-",'"\n ','\n >\n </td>\n <td>\n <label for="',"-",'">\n ',"\n </label\n </td>\n </tr>\n "]);return or=function(){return t},t}function ir(){var t=ur(['\n <tr>\n <td>\n <input\n type="radio"\n name="','"\n value="','"\n id="',"-",'"\n ','\n >\n </td>\n <td>\n <label for="',"-",'">\n ',"\n </label\n </td>\n </tr>\n "]);return ir=function(){return t},t}function ar(){var t=ur(['\n <footer\n class="\n content-horizontal-','\n content-vertical-center\n "\n >\n <button type="submit" form="page-form">\n ',"\n </button>\n </footer>\n "]);return ar=function(){return t},t}function ur(t,n){return n||(n=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(n)}}))}function sr(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var cr=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.entries(t).map((function(t){var n=sr(t,2),e=n[0],r=n[1];return"".concat(e,'="').concat(r,'"')})).join(" ")},fr=function(t,n,e){var r=t.label,o=t.coding,i=n.name,a=n.required,u=void 0===a||a;return"radio"===e?Be(ir(),i,o,i,o,u?"required":"",i,o,r):"checkbox"===e?Be(or(),i,o,i,o,u?"required":"",i,o,r):void 0},lr=function(t,n){var e=n.rng||new pn,r=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return n?e.shuffle(t):t};return Be(Ze(),n.width||"m",t.map((function(t){return pr(t,function(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){Qe(t,n,e[n])}))}return t}({shuffleMeMaybe:r},n))})).join("\n"),function(t){var n=t.submitButtonPosition,e=void 0===n?"right":n,r=t.submitButtonText;return"hidden"!==e?Be(ar(),e,r):""}(n))},pr=function(t,n){var e=n.shuffleMeMaybe;switch(t.type){case"text":return Be(Xe(),t.title||"",t.content||"");case"image":return Be(Ke(),t.src,t.width&&"max-width: "+t.width,t.height&&"max-height: "+t.height);case"html":return Be(Je(),t.content||"");case"divider":return Be(Ye());case"input":return Be(Ge(),t.name,t.label||"",t.help||"",t.name,t.required?"required":"",cr(t.attributes));case"textarea":return Be($e(),t.name,t.label||"",t.help||"",t.name,t.required?"required":"");case"radio":return Be(He(),t.name,t.label||"",t.help||"",e(t.options||[],t.shuffle).map((function(n){return fr(n,t,"radio")})).join("\n"));case"checkbox":return Be(We(),t.name,t.label||"",t.help||"",e(t.options||[],t.shuffle).map((function(n){return fr(n,t,"checkbox")})).join("\n"));case"slider":return Be(Ve(),t.name,t.label||"",t.help||"",t.name,t.required?"required":"",cr(t.attributes));case"likert":return Be(ze(),t.name,t.label||"",t.help||"",Zt()(t.width).map((function(){return'<col style="width: '.concat(60/t.width,'%">')})).join("\n"),function(t){var n=t.width,e=t.anchors;return e.every((function(t){return!t}))?"":Be(rr(),Zt()(n).map((function(t){return Be(er(),e[t]||"")})).join("\n"))}(t),e(t.items||[],t.shuffle).map((function(n){return function(t,n){var e=t.label,r=t.coding,o=n.name,i=n.width,a=n.required,u=void 0===a||a;return Be(nr(),e,Zt()(1,Number(i)+1).map((function(t){return Be(tr(),o,r,t,u?"required":"")})).join("\n"))}(n,t)})).join("\n"));default:console.error("Unknown page item type",t.type)}};function hr(t){return(hr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function dr(t,n,e){return(dr="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,n,e){var r=function(t,n){for(;!Object.prototype.hasOwnProperty.call(t,n)&&null!==(t=xr(t)););return t}(t,n);if(r){var o=Object.getOwnPropertyDescriptor(r,n);return o.get?o.get.call(e):o.value}})(t,n,e||t)}function vr(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){gr(t,n,e[n])}))}return t}function gr(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function yr(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function mr(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function br(t,n,e){return n&&mr(t.prototype,n),e&&mr(t,e),t}function wr(t,n){return!n||"object"!==hr(n)&&"function"!=typeof n?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):n}function xr(t){return(xr=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Or(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&Sr(t,n)}function Sr(t,n){return(Sr=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}var jr=function(t){function Screen(t){return yr(this,Screen),wr(this,xr(Screen).call(this,vr({content:null,contentUrl:null},t)))}return Or(Screen,t),br(Screen,[{key:"onBeforePrepare",value:function(){var t=this;return Promise.resolve().then((function(){return t.options.contentUrl?fetch(t.options.contentUrl).then((function(t){return t.text()})).then((function(n){return t.options.content=n})).catch((function(t){return console.log("Error while loading content: ",t)})):null}))}},{key:"onRun",value:function(){this.options.el.innerHTML=this.options.content}}]),Screen}(se);jr.metadata={module:["html"],nestedComponents:[],parsableOptions:{content:{}}};var Form=function(t){function Form(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return yr(this,Form),(t=wr(this,xr(Form).call(this,vr({validator:function(){return!0},scrollTop:!0},n)))).options.events['click button[type="submit"]']=function(n){if(n.target.getAttribute("form")){var e=t.options.el.querySelector("form#".concat(n.target.getAttribute("form")));if(e){n.preventDefault(),n.stopPropagation();var r=document.createElement("input");return r.type="submit",r.style.display="none",e.appendChild(r),r.click(),e.removeChild(r),!1}}return!0},t.options.events["submit form"]=function(n){return t.submit(n)},t}return Or(Form,t),br(Form,[{key:"onRun",value:function(){dr(xr(Form.prototype),"onRun",this).call(this);var t=this.options.el.querySelector("[autofocus]");t&&t.focus()}},{key:"submit",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return t&&t.preventDefault&&t.preventDefault(),this.validate()?(Object.assign(this.data,this.serialize()),this.end("form submission")):Array.from(this.options.el.querySelectorAll("form")).forEach((function(t){return t.setAttribute("data-labjs-validated","")})),!1}},{key:"serialize",value:function(){var t=this.options.el.querySelectorAll("form"),n={};return Array.from(t).forEach((function(t){Array.from(t.elements).forEach((function(t){switch(t.nodeName.toLowerCase()){case"input":switch(t.type){case"checkbox":n[t.name]=t.checked;break;case"radio":t.checked&&(n[t.name]=t.value);break;default:n[t.name]=t.value}break;case"textarea":n[t.name]=t.value;break;case"select":switch(t.type){case"select-one":n[t.name]=t.value;break;case"select-multiple":n[t.name]=Array.from(t.options).filter((function(t){return t.selected})).map((function(t){return t.value}))}}}))})),n}},{key:"validate",value:function(){var t=this.options.el.querySelectorAll("form");return this.options.validator(this.serialize())&&Array.from(t).every((function(t){return t.checkValidity()}))}}]),Form}(jr);Form.metadata={module:["html"],nestedComponents:[]};var Er=function(t){function Frame(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return yr(this,Frame),wr(this,xr(Frame).call(this,vr({content:null,context:"",contextSelector:""},t)))}return Or(Frame,t),br(Frame,[{key:"onPrepare",value:async function(){var t=this,n=new DOMParser;this.internals.parsedContext=n.parseFromString(this.options.context,"text/html"),this.options.content.options.el=this.internals.parsedContext.querySelector(this.options.contextSelector),this.internals.contentEndHandler=function(){return t.end()},this.options.content.on("after:end",this.internals.contentEndHandler),await Se([this.options.content],this)}},{key:"onRun",value:async function(t,n){var e=this;this.options.el.innerHTML="",Array.from(this.internals.parsedContext.body.children).forEach((function(t){return e.options.el.appendChild(t)})),await this.options.content.run(t,n)}},{key:"onEnd",value:function(){return this.options.content.status<ie.done?(this.options.content.off("after:end",this.internals.contentEndHandler),this.options.content.end("abort by frame")):Promise.resolve()}},{key:"progress",get:function(){return this.options.content.progress}}]),Frame}(se);Er.metadata={module:["html"],nestedComponents:["content"],parsableOptions:{context:{}}};var Ar=function(t){function Page(){return yr(this,Page),wr(this,xr(Page).apply(this,arguments))}return Or(Page,t),br(Page,[{key:"onPrepare",value:function(){var t=this;this.options.content=lr(this.options.items,{submitButtonText:this.options.submitButtonText,submitButtonPosition:this.options.submitButtonPosition,width:this.options.width,rng:this.random}),this.options.items.filter((function(t){return"image"===t.type&&t.src})).forEach((function(n){return t.options.media.images.push(n.src)}))}}]),Page}(Form);function kr(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}Ar.metadata={module:["html"],nestedComponents:[],parsableOptions:{items:{type:"array",content:{type:"object",content:{"*":"string",attributes:{type:"object",content:{"*":"string"}},options:{type:"array",content:{type:"object",content:{"*":"string"}}},items:{type:"array",content:{type:"object",content:{"*":"string"}}}}}}}};var Tr=function(t){return Math.PI*(t/180)},Pr=function(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[0,0],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,i=Tr(e*(360/t)+o);return[n*Math.sin(i)+r[0],n*Math.cos(i)+r[1]]};function Rr(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _r(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){Mr(t,n,e[n])}))}return t}function Mr(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}var Ir=function(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=_r({translateOrigin:!0,viewportScale:"auto",devicePixelScaling:!0,canvasClientRect:{left:0,top:0}},e),o=r.translateOrigin?t[0]/2:0,i=r.translateOrigin?t[1]/2:0,a=r.devicePixelScaling?window.devicePixelRatio:1,u="auto"===r.viewportScale?Math.min(t[0]/(a*n[0]),t[1]/(a*n[1])):r.viewportScale,s=u*a;return{translateX:o,translateY:i,scale:s,viewportScale:u,pixelRatio:a}},Cr=function(t,n,e){var r=Ir(t,n,e),o=r.translateX,i=r.translateY,a=r.scale,u=r.viewportScale,s=!0===e.fromOffset?{left:0,top:0}:e.canvasClientRect;return[1/u,0,0,1/u,-o/a-s.left/u,-i/a-s.top/u]},Fr=function(t,n){var e=Rr(n,2),r=e[0],o=e[1];return([r*t[0]+o*t[2]+t[4],r*t[1]+o*t[3]+t[5]])},Nr=function(t,n){return function(e,r,o){return(t||[]).forEach((function(t){return function(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};switch(t.save(),t.beginPath(),t.translate(n.left,n.top),t.rotate(Tr(n.angle)),n.type){case"line":t.moveTo(-n.width/2,0),t.lineTo(+n.width/2,0);break;case"rect":t.rect(-n.width/2,-n.height/2,n.width,n.height);break;case"triangle":t.moveTo(-n.width/2,n.height/2),t.lineTo(0,-n.height/2),t.lineTo(n.width/2,n.height/2),t.closePath();break;case"circle":t.arc(0,0,n.width/2,0,Tr(360));break;case"ellipse":t.ellipse(0,0,n.width/2,n.height/2,0,0,Tr(360));break;case"text":case"i-text":t.font="".concat(n.fontStyle||"normal"," ")+"".concat(n.fontWeight||"normal"," ")+"".concat(n.fontSize||32,"px ")+"".concat(n.fontFamily||"sans-serif"),t.textAlign=n.textAlign||"center",t.textBaseline="middle";break;case"image":var r=e.images.readSync(n.src),o=Rr(r,2),i=o[0],a=o[1],u="width"===n.autoScale?i.naturalWidth*(n.height/i.naturalHeight):n.width,s="height"===n.autoScale?i.naturalHeight*(n.width/i.naturalWidth):n.height;t.drawImage(a||i,-u/2,-s/2,u,s);break;default:throw new Error("Unknown content type")}n.fill&&(t.fillStyle=n.fill,"i-text"!==n.type&&"text"!==n.type?t.fill():n.text.split("\n").forEach((function(e,r,o){t.fillText(e,0,(r-.5*(o.length-1))*(n.fontSize||32)*(n.lineHeight||1.16))}))),n.stroke&&n.strokeWidth&&(t.strokeStyle=n.stroke,t.lineWidth=n.strokeWidth||1,"i-text"!==n.type&&"text"!==n.type?t.stroke():n.text.split("\n").forEach((function(e,r,o){t.strokeText(e,0,(r-.5*(o.length-1))*(n.fontSize||32)*(n.lineHeight||1.16))}))),t.restore()}(o,t,n)}))}},Lr=void 0!==window.DOMMatrixReadOnly?new window.DOMMatrixReadOnly:document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGMatrix(),Dr=function(t,n){var e=new Path2D;switch(n.type){case"aoi":e.rect(-n.width/2,-n.height/2,n.width,n.height);break;default:console.error("Content type not yet implemented")}var r=new Path2D;return r.addPath(e,Lr.translate(n.left,n.top).rotate(n.angle)),r};function Ur(t){return(Ur="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function qr(t){return function(t){if(Array.isArray(t)){for(var n=0,e=new Array(t.length);n<t.length;n++)e[n]=t[n];return e}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function Br(t,n){return function(t){if(Array.isArray(t))return t}(t)||function(t,n){if(!(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t)))return;var e=[],r=!0,o=!1,i=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done)&&(e.push(a.value),!n||e.length!==n);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return e}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function zr(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function Vr(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function Wr(t,n,e){return n&&Vr(t.prototype,n),e&&Vr(t,e),t}function Hr(t,n){return!n||"object"!==Ur(n)&&"function"!=typeof n?Gr(t):n}function $r(t){return($r=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Gr(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Yr(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(n&&n.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),n&&Jr(t,n)}function Jr(t,n){return(Jr=Object.setPrototypeOf||function(t,n){return t.__proto__=n,t})(t,n)}function Kr(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){Xr(t,n,e[n])}))}return t}function Xr(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}var Qr=function(t){return Kr({canvas:null,ctxType:"2d",ctx:null,insertCanvasOnRun:!1,translateOrigin:!0,viewport:[800,600],viewportScale:"auto",viewportEdge:!1,devicePixelScaling:null},t)},Zr=function(){null===this.options.canvas&&(this.options.canvas=document.createElement("canvas"),this.options.insertCanvasOnRun=!0),null===this.options.devicePixelScaling&&(this.options.devicePixelScaling=!0)},to=function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;if(this.options.insertCanvasOnRun){var e=this.options.devicePixelScaling?window.devicePixelRatio:1;n=n||this.options.el,t&&(n.innerHTML="");var r=window.getComputedStyle(n),o=n.clientWidth-parseInt(r.paddingLeft)-parseInt(r.paddingRight),i=n.clientHeight-parseInt(r.paddingTop)-parseInt(r.paddingBottom);this.options.canvas.width=o*e,this.options.canvas.height=i*e,this.options.canvas.style.display="block",this.options.canvas.style.width="".concat(o,"px"),this.options.canvas.style.height="".concat(i,"px"),t&&n.appendChild(this.options.canvas)}},no=function(t){function Screen(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return zr(this,Screen),(t=Hr(this,$r(Screen).call(this,Kr({content:null,renderFunction:null,clearCanvas:!0},Qr(n))))).internals.frameRequest=null,t.render=t.render.bind(Gr(t)),t}return Yr(Screen,t),Wr(Screen,[{key:"onPrepare",value:function(){var t=this;(this.options.content||[]).filter((function(t){return O()(t)&&"image"===t.type&&t.src})).forEach((function(n){return t.options.media.images.push(n.src)})),Zr.apply(this),this.internals.domConnection.processEvent=function(n){var e=Br(n,3),r=e[0],o=e[1],i=e[2];if(i&&i.startsWith("@")){var a=t.options.devicePixelScaling?window.devicePixelRatio:1;return{eventName:r,filters:o,selector:"canvas",moreChecks:[function(n){return t.options.ctx.isPointInPath(t.internals.paths[i.slice(1)],n.offsetX*a,n.offsetY*a)}]}}return{eventName:r,filters:o,selector:i}},null===this.options.renderFunction&&(this.options.renderFunction=Nr((this.options.content||[]).filter((function(t){return O()(t)&&"aoi"!==t.type})),this.internals.controller.cache))}},{key:"onRun",value:function(){var t;to.apply(this),this.options.ctx=this.options.canvas.getContext(this.options.ctxType),this.options.ctx.save(),this.internals.transformationMatrix=function(t,n,e){var r=Ir(t,n,e),o=r.translateX,i=r.translateY,a=r.scale;return[a,0,0,a,o,i]}([this.options.canvas.width,this.options.canvas.height],this.options.viewport,{translateOrigin:this.options.translateOrigin,viewportScale:this.options.viewportScale,devicePixelScaling:this.options.devicePixelScaling}),(t=this.options.ctx).setTransform.apply(t,qr(this.internals.transformationMatrix))}},{key:"onRender",value:function(t){return this.options.clearCanvas&&this.clear(),this.options.viewportEdge&&(this.options.ctx.save(),this.options.ctx.strokeStyle="rgb(229, 229, 229)",this.options.ctx.strokeRect(this.options.translateOrigin?-this.options.viewport[0]/2:0,this.options.translateOrigin?-this.options.viewport[1]/2:0,this.options.viewport[0],this.options.viewport[1]),this.options.ctx.restore()),this.options.renderFunction.call(this,t-this.internals.timestamps.render,this.options.canvas,this.options.ctx,this)}},{key:"onShow",value:function(){this.internals.paths=function(t){return function(n,e,r){return dn()(t.filter((function(t){return t.label&&["aoi"].includes(t.type)})).map((function(t){return[t.label,Dr(0,t)]})))}}(this.options.content||[])(0,this.options.canvas,this.options.ctx)}},{key:"queueAnimationFrame",value:function(){var t=this;this.internals.frameRequest=window.requestAnimationFrame((function(n){t.options.clearCanvas&&t.clear(),t.options.renderFunction.call(t,n-t.internals.timestamps.render,t.options.canvas,t.options.ctx,t)}))}},{key:"onEnd",value:function(){this.options.ctx&&this.options.ctx.restore()}},{key:"onEpilogue",value:function(){delete this.options.ctx,delete this.options.canvas}},{key:"clear",value:function(){this.options.ctx.save(),this.options.ctx.setTransform(1,0,0,1,0,0),this.options.ctx.clearRect(0,0,this.options.canvas.width,this.options.canvas.height),this.options.ctx.restore()}},{key:"transform",value:function(t){if(!this.internals.transformationMatrix)throw new Error("No transformation matrix set");return Fr(this.internals.transformationMatrix,t)}},{key:"transformInverse",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this.internals.transformationMatrix)throw new Error("No transformation matrix set");var e=Cr([this.options.canvas.width,this.options.canvas.height],this.options.viewport,{translateOrigin:this.options.translateOrigin,viewportScale:this.options.viewportScale,devicePixelScaling:this.options.devicePixelScaling,canvasClientRect:this.options.canvas.getBoundingClientRect(),fromOffset:n});return Fr(e,t)}},{key:"transformCanvasEvent",value:function(t){var n=t.offsetX,e=t.offsetY;return this.transformInverse([n,e],!0)}}]),Screen}(se);no.metadata={module:["canvas"],nestedComponents:[],parsableOptions:{content:{type:"array",content:{type:"object",content:{text:{},fill:{},stroke:{},left:{type:"number"},top:{type:"number"},width:{type:"number"},height:{type:"number"},angle:{type:"number"},src:{},fontSize:{type:"number"}}}}}};var eo=function(t){function Frame(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return zr(this,Frame),(t=Hr(this,$r(Frame).call(this,Qr(Kr({context:"<canvas></canvas>"},n))))).options.handMeDowns.includes("canvas")||t.options.handMeDowns.push("canvas","devicePixelScaling"),t}return Yr(Frame,t),Wr(Frame,[{key:"onPrepare",value:async function(){var t=this;if(!Hn(this,(function(n,e){return n&&(e===t||e instanceof no||e instanceof je||e instanceof Ee||e instanceof Ae)}),!0))throw new Error("CanvasFrame may only contain flow or canvas-based components");var n=new DOMParser;if(this.internals.parsedContext=n.parseFromString(this.options.context,"text/html"),this.options.canvas=this.internals.parsedContext.querySelector("canvas"),!this.options.canvas)throw new Error("No canvas found in context");this.options.content.options.el=null===this.options.canvas.parentElement||"BODY"===this.options.canvas.parentElement.tagName?this.options.el:this.options.canvas.parentElement,this.internals.contentEndHandler=function(){return t.end()},this.options.content.on("after:end",this.internals.contentEndHandler),Zr.apply(this),this.options.insertCanvasOnRun=!0,await Se([this.options.content],this)}},{key:"onRun",value:async function(t,n){var e=this;this.options.el.innerHTML="",Array.from(this.internals.parsedContext.body.children).forEach((function(t){return e.options.el.appendChild(t)})),to.apply(this,[!1,this.options.canvas.parentElement]),await this.options.content.run(t,n)}},{key:"onEpilogue",value:function(){delete this.options.canvas,delete this.internals.parsedContext}}]),Frame}(Er);eo.metadata={module:["canvas"],nestedComponents:["content"]};var fromObject=e(303),ro=function(t){return t.reduce((function(t,n){return t+n}),0)},oo=function(t){return ro(t)/t.length},io=function(t){var n=oo(t);return oo(t.map((function(t){return Math.pow(t-n,2)})))},ao=(e(218),e(304)),uo=e.n(ao);function so(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function co(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function fo(t){return(fo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var lo=function(t){return(t.length>80?'<div class="labjs-debug-trunc">'.concat(t.substr(0,100),"</div>"):t).replace(/,/g,",​")},po=function(t){return"<td>".concat(function(t){switch(fo(t)){case"number":return t>150?t.toFixed(0):t.toFixed(2);case"string":return lo(t);case"undefined":return"";case"object":if(mn()(t))return lo(JSON.stringify(t));default:return t}}(t),"</td>")},ho=function(){function Debug(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.filePrefix,e=void 0===n?"study":n;so(this,Debug),this.filePrefix=e}return function(t,n,e){n&&co(t.prototype,n),e&&co(t,e)}(Debug,[{key:"handle",value:function(t,n){switch(n){case"plugin:init":return this.onInit(t);case"prepare":return this.onPrepare();default:return null}}},{key:"onInit",value:function(t){var n=this;this.isVisible=!1,this.context=t,this.container=document.createElement("div"),this.container.id="labjs-debug",this.container.innerHTML='<style type="text/css">\n .labjs-debug-opener {\n font-size: 1.2rem;\n color: #8d8d8d;\n /* Box formatting */\n width: 40px;\n height: 32px;\n padding: 6px 8px;\n border-radius: 3px;\n border: 1px solid #e5e5e5;\n z-index: 3;\n background-color: white;\n /* Fixed position */\n position: fixed;\n bottom: 36px;\n right: -5px;\n /* Content centering */\n display: flex;\n align-items: center;\n justify-content: left;\n }\n\n .labjs-debug-toggle {\n cursor: pointer;\n }\n\n body.labjs-debugtools-visible .labjs-debug-opener {\n display: none;\n }\n\n .labjs-debug-overlay {\n font-family: "Arial", sans-serif;\n color: black;\n /* Box formatting */\n width: 100vw;\n height: 30vh;\n position: fixed;\n bottom: 0;\n left: 0;\n z-index: 2;\n background-color: white;\n border-top: 2px solid #e5e5e5;\n display: none;\n overflow: scroll;\n }\n\n #labjs-debug.labjs-debug-large .labjs-debug-overlay {\n height: 100vh;\n }\n\n .labjs-debug-overlay-menu {\n font-size: 0.8rem;\n color: #8d8d8d;\n padding: 8px 12px 6px;\n border-bottom: 1px solid #e5e5e5;\n }\n\n .labjs-debug-overlay-menu a {\n color: #8d8d8d;\n }\n\n .labjs-debug-overlay-menu .pull-right {\n font-size: 1rem;\n float: right;\n }\n\n body.labjs-debugtools-visible .labjs-debug-overlay {\n display: block;\n }\n\n .labjs-debug-overlay-contents {\n padding: 12px;\n }\n\n .labjs-debug-overlay-contents table {\n font-size: 0.8rem;\n }\n\n .labjs-debug-overlay-contents table tr.labjs-debug-state {\n background-color: #f8f8f8;\n }\n\n /* Truncated cells */\n .labjs-debug-trunc {\n min-width: 200px;\n max-width: 400px;\n }\n .labjs-debug-trunc::after {\n content: "...";\n opacity: 0.5;\n }\n</style>\n<div class="labjs-debug-opener labjs-debug-toggle"><div>≡</div></div>\n<div class="labjs-debug-overlay">\n <div class="labjs-debug-overlay-menu">\n <div class="pull-right">\n <span class="labjs-debug-toggle">×</span>\n </div>\n <code>lab.js</code> ·\n data preview ·\n <a href="#" class="labjs-debug-data-download">download csv</a>\n </div>\n <div class="labjs-debug-overlay-contents">\n Contents\n </div>\n</div>',Array.from(this.container.querySelectorAll(".labjs-debug-toggle")).forEach((function(t){return t.addEventListener("click",(function(){return n.toggle()}))})),this.container.querySelector(".labjs-debug-overlay-menu").addEventListener("dblclick",(function(){return n.container.classList.toggle("labjs-debug-large")})),this.container.querySelector(".labjs-debug-data-download").addEventListener("click",(function(e){e.preventDefault(),n.context.options.datastore?n.context.options.datastore.download("csv",t.options.datastore.makeFilename(n.filePrefix,"csv")):alert("No datastore to download from")})),document.body.appendChild(this.container)}},{key:"onPrepare",value:function(){var t=this;if(this.context.options.datastore){var n=uo()((function(){return t.render()}),100);this.context.options.datastore.on("set",n),this.context.options.datastore.on("commit",n),this.context.options.datastore.on("update",n)}}},{key:"toggle",value:function(){this.isVisible=!this.isVisible,this.render(),document.body.classList.toggle("labjs-debugtools-visible")}},{key:"render",value:function(){var t;this.isVisible&&(t=this.context.options.datastore?function(t){var n=t.keys(!0),e=n.map((function(t){return"<th>".concat(t,"</th>")})),r=n.map((function(n){return po(t.state[n])})),o=t.data.slice().reverse().map((function(t){return"<tr> ".concat(n.map((function(n){return po(t[n])})).join("")," </tr>")}));return"\n <table>\n <tr>".concat(e.join("\n"),'</tr>\n <tr class="labjs-debug-state">').concat(r.join("\n"),"</tr>\n ").concat(o.join("\n"),"\n </table>\n ")}(this.context.options.datastore):function(t){return'\n <div style="display: flex; width: 100%; height: 100%; align-items: center; justify-content: center;">\n '.concat(t,"\n </div>")}("No data store found in component"),this.container.querySelector(".labjs-debug-overlay-contents").innerHTML=t)}}]),Debug}();function vo(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function go(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var yo=function(t){var n="Are you sure you want to close this window?";return t.returnValue=n,n},Download=function(){function Download(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.filePrefix,e=t.fileType;vo(this,Download),this.el=null,this.filePrefix=n||"study",this.fileType=e||"csv"}return function(t,n,e){n&&go(t.prototype,n),e&&go(t,e)}(Download,[{key:"handle",value:function(t,n){var e=this;"end"===n&&t.options.datastore&&(window.addEventListener("beforeunload",yo),this.el=document.createElement("div"),this.el.className="popover",this.el.innerHTML='\n <div class="alert text-center">\n <strong>Download data</strong>\n </div>\n ',this.el.addEventListener("click",(function(){t.options.datastore.download(e.fileType,t.options.datastore.makeFilename(e.filePrefix,e.fileType)),window.removeEventListener("beforeunload",yo)})),t.options.el.prepend(this.el))}}]),Download}();function mo(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function bo(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var wo=function(){function t(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=n.message,r=n.hint,o=n.close;mo(this,t),this.options={message:e||"This experiment requires full screen display",hint:r||"Please click to continue in full screen mode",close:null==o||o}}return function(t,n,e){n&&bo(t.prototype,n),e&&bo(t,e)}(t,[{key:"handle",value:async function(t,n){if("before:run"!==n||document.fullscreenElement)"end"===n&&this.options.close&&lab.util.fullscreen.exit();else{var e=document.createElement("div");e.innerHTML='\n <div\n class="modal w-m content-horizontal-center content-vertical-center text-center"\n >\n <p>\n <span class="font-weight-bold">\n '.concat(this.options.message,'\n </span><br>\n <span class="text-muted">\n ').concat(this.options.hint,"\n </span>\n </p>\n </div>\n "),e.classList.add("overlay","content-vertical-center","content-horizontal-center"),document.body.appendChild(e),await new Promise((function(t){e.addEventListener("click",(async function(n){await lab.util.fullscreen.launch(document.documentElement),document.body.removeChild(e),t()}),{once:!0})}))}}}]),t}();function xo(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function Oo(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var Logger=function(){function Logger(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};xo(this,Logger),this.title=t.title}return function(t,n,e){n&&Oo(t.prototype,n),e&&Oo(t,e)}(Logger,[{key:"handle",value:function(t,n){console.log("Component ".concat(this.title," received ").concat(n))}}]),Logger}();e(213),e(261);function So(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function jo(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var Eo=function(){var t=window.Intl.DateTimeFormat().resolvedOptions();return{labjs_version:Uo,labjs_build:qo,location:window.location.href,userAgent:window.navigator.userAgent,platform:window.navigator.platform,language:window.navigator.language,locale:t.locale,timeZone:t.timeZone,timezoneOffset:(new Date).getTimezoneOffset(),screen_width:window.screen.width,screen_height:window.screen.height,scroll_width:document.body.scrollWidth,scroll_height:document.body.scrollHeight,window_innerWidth:window.innerWidth,window_innerHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio}},Metadata=function(){function Metadata(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};So(this,Metadata),this.options=t}return function(t,n,e){n&&jo(t.prototype,n),e&&jo(t,e)}(Metadata,[{key:"handle",value:function(t,n){if("prepare"===n){var e=function(t){return dn()(Array.from(new URLSearchParams(t).entries()))}(this.options.location_search||window.location.search);t.options.datastore.set({url:e,meta:Eo()})}}}]),Metadata}();function Ao(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var ko=function(t){var n="Closing this window will abort the study. Are you sure?";return t.returnValue=n,n},To=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t)}return function(t,n,e){n&&Ao(t.prototype,n),e&&Ao(t,e)}(t,[{key:"handle",value:function(t,n){"prepare"===n?window.addEventListener("beforeunload",ko):"end"===n&&window.removeEventListener("beforeunload",ko)}}]),t}();function Po(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function Ro(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var _o=function(){function t(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=n.origin,r=n.target,o=n.messageType;Po(this,t),this.origin=e||"*",this.target=r||window.parent,this.messageType=o||"labjs.data"}return function(t,n,e){n&&Ro(t.prototype,n),e&&Ro(t,e)}(t,[{key:"handle",value:function(t,n){"epilogue"===n&&this.target.postMessage({type:this.messageType,metadata:{payload:"full",url:window.location.href},raw:t.options.datastore.data,json:t.options.datastore.exportJson(),csv:t.options.datastore.exportCsv()},this.origin)}}]),t}();function Mo(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var Io=function(){function t(){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,t)}return function(t,n,e){n&&Mo(t.prototype,n),e&&Mo(t,e)}(t,[{key:"handle",value:function(t,n){if("after:end"===n&&t.options.datastore){var e=document.querySelector('form[name="labjs-data"]');try{var r=new ClipboardEvent("").clipboardData||new DataTransfer;r.items.add(new File([t.options.datastore.exportCsv()],"data.csv")),e.elements.dataFile.files=r.files}catch(n){console.log("Couldn't append data file to form falling back to direkt insertion. Error was",n),e.elements.dataRaw.value=t.options.datastore.exportCsv()}e.submit()}}}]),t}();function Co(t){for(var n=1;n<arguments.length;n++){var e=null!=arguments[n]?Object(arguments[n]):{},r=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(e).filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})))),r.forEach((function(n){Fo(t,n,e[n])}))}return t}function Fo(t,n,e){return n in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function No(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}function Lo(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var Do=function(){function Transmit(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};No(this,Transmit),this.url=t.url,this.metadata=t.metadata||{},this.metadata.id=this.metadata.id||fn(),this.updates={incremental:!(t.updates&&!1===t.updates.incremental),full:!(t.updates&&!1===t.updates.full)},this.callbacks=t.callbacks||{},this.headers=t.headers||{},this.encoding=t.encoding||"json"}return function(t,n,e){n&&Lo(t.prototype,n),e&&Lo(t,e)}(Transmit,[{key:"handle",value:function(t,n){var e=this,r=this.url,o=this.metadata;switch(n){case"prepare":this.updates.incremental&&t.options.datastore.on("idle",(function(){this.queueIncrementalTransmission(r,Co({},o,{payload:"incremental"}),{headers:this.headers,encoding:this.encoding})})),this.callbacks.setup&&this.callbacks.setup.call(this);break;case"epilogue":this.updates.full&&t.options.datastore.transmit(r,Co({},o,{payload:"full"}),{headers:this.headers,encoding:this.encoding}).then((function(n){return e.updates.incremental&&t.options.datastore.flushIncrementalTransmissionQueue(),n})).then(this.callbacks.full)}}}]),Transmit}();e.d(n,"version",(function(){return Uo})),e.d(n,"build",(function(){return qo})),e.d(n,"core",(function(){return Bo})),e.d(n,"canvas",(function(){return zo})),e.d(n,"html",(function(){return Vo})),e.d(n,"flow",(function(){return Wo})),e.d(n,"plugins",(function(){return Ho})),e.d(n,"data",(function(){return $o})),e.d(n,"util",(function(){return Go}));var Uo="20.1.1",qo={flavor:"production",commit:"c48ac4ada3769e8d34489594ab03097d5f256ac7"},Bo={Component:se,Dummy:Dummy},zo={Frame:eo,Screen:no},Vo={Screen:jr,Form:Form,Frame:Er,Page:Ar},Wo={Sequence:je,Parallel:Ae,Loop:Ee},Ho={Debug:ho,Download:Download,Fullscreen:wo,Logger:Logger,Metadata:Metadata,NavigationGuard:To,PostMessage:_o,Submit:Io,Transmit:Do},$o={Store:nt},Go={Random:pn,fromObject:fromObject.a,canvas:{makeRenderFunction:Nr,transform:Fr},combinatorics:{product:function*(){for(var t=arguments.length,n=new Array(t),e=0;e<t;e++)n[e]=arguments[e];for(var r=n.map((function(t){return Math.max(t.length,1)})).reverse().reduce((function(t,n,e){return t.concat([(t[e-1]||1)*n])}),[]).reverse(),o=function*(t){yield n.map((function(n,e){return n[Math.floor(t/(r[e+1]||1))%n.length]}))},i=0;i<r[0];i++)yield*o(i)}},events:{logTimestamp:function(t){return function(n){n.preventDefault(),this.data[t]=mt(n.timeStamp)}}},fullscreen:{launch:function(t){return t.requestFullscreen?t.requestFullscreen():t.mozRequestFullScreen?t.mozRequestFullScreen():t.webkitRequestFullscreen?t.webkitRequestFullscreen():t.msRequestFullscreen?t.msRequestFullscreen():void 0},exit:function(){return document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen?document.webkitExitFullscreen():void 0}},geometry:{distance:function(t,n){var e=kr(t,2),r=e[0],o=e[1],i=kr(n,2),a=i[0],u=i[1];return Math.sqrt(Math.pow(r-a,2)+Math.pow(o-u,2))},polygon:function(t,n){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[0,0],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return Zt()(t).map((function(o){return Pr(t,n,o,e,r)}))},polygonVertex:Pr,toRadians:Tr},stats:{sum:ro,mean:oo,variance:io,std:function(t){return Math.sqrt(io(t))}},timing:{FrameTimeout:Ot},tree:{traverse:Wn,reduce:Hn}}}])}));
//# sourceMappingURL=lab.js.map
|
import React from 'react';
import classes from './Button.css';
const button = (props) => (
<button
disabled={props.disabled}
className={[classes.Button, classes[props.btnType]].join(' ')}
onClick={props.clicked}
>
{props.children}
</button>
);
export default button;
|
/*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}
this.each(function() {
jQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return jQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = jQuery.isFunction( value );
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !isFunc && typeof value !== "string" ) {
value = jQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 ) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/*jshint validthis:true */
var prop, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.cur && hooks.cur.finish ) {
hooks.cur.finish.call( this );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.documentElement;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from models import User , UserProfile
class SignUpForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password' , 'email' , 'first_name', 'last_name',]
widgets = {
'password': forms.PasswordInput(),
}
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['picture']
|
/*
* File: EditorCentralWid.h
* Module:
* Author: james
* Email:
* File Description:
*
* Created on December 23, 2015, 7:13 PM
* Last Modified:
*/
#ifndef EDITOR_CENTRAL_WID_H
#define EDITOR_CENTRAL_WID_H
#include <QWidget>
#include <QTextEdit> //TODO: replace these with a custom textedit from PrettyPrint
#include <QString>
#include <QGridLayout>
#include "FileGui.h"
class EditorCentralWid : public QWidget
{
Q_OBJECT
private:
FileGui* oldFileGuiPtr;
FileGui* newFileGuiPtr;
QGridLayout* outerLayout;
public:
EditorCentralWid(QWidget* parent = 0);
QString* toString();
~EditorCentralWid();
};
#endif /* EDITOR_CENTRAL_WID_H */
|
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:jsx-a11y/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 13,
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint', 'jsx-a11y'],
rules: {
'@typescript/no-explicit-any': 'off',
},
};
|
from django.urls import path
from sql_api import views
urlpatterns = [
path('info', views.info),
path('debug', views.debug)
]
|
import robothelper
import numpy as np
import cv2
import pickle
import environment.collisionmodel as cm
if __name__ == '__main__':
yhx = robothelper.RobotHelperX(usereal=False)
yhx.pxc.triggerframe()
bgdepth = yhx.pxc.getdepthimg()
pickle.dump(bgdepth, open("../../databackground/bgdepthlow.pkl", "wb"))
bgpcd = yhx.pxc.getpcd()
pickle.dump(bgpcd, open("../../databackground/bgpcddepthlow.pkl", "wb"))
|
/**
* angular-ui-ace - This directive allows you to add ACE editor elements.
* @version v0.1.0 - 2013-12-28
* @link http://angular-ui.github.com
* @license MIT
*/
"use strict";angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(a){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",require:"?ngModel",link:function(b,c,d,e){var f,g,h,i,j;f=a.ace||{},g=angular.extend({},f,b.$eval(d.uiAce)),h=window.ace.edit(c[0]),i=h.getSession(),j=function(a){return function(c){var f=i.getValue();f===b.$eval(d.value)||b.$$phase||b.$root.$$phase||(angular.isDefined(e)&&b.$apply(function(){e.$setViewValue(f)}),angular.isDefined(a)&&b.$apply(function(){if(!angular.isFunction(a))throw new Error("ui-ace use a function as callback.");a(c,h)}))}},angular.isDefined(g.showGutter)&&h.renderer.setShowGutter(g.showGutter),angular.isDefined(g.useWrapMode)&&i.setUseWrapMode(g.useWrapMode),angular.isFunction(g.onLoad)&&g.onLoad(h),angular.isString(g.theme)&&h.setTheme("ace/theme/"+g.theme),angular.isString(g.mode)&&i.setMode("ace/mode/"+g.mode),d.$observe("readonly",function(a){h.setReadOnly("true"===a)}),angular.isDefined(e)&&(e.$formatters.push(function(a){if(angular.isUndefined(a)||null===a)return"";if(angular.isObject(a)||angular.isArray(a))throw new Error("ui-ace cannot use an object or an array as a model");return a}),e.$render=function(){i.setValue(e.$viewValue)}),i.on("change",j(g.onChange)),c.on("$destroy",function(){h.session.$stopWorker(),h.destroy()})}}}]);
|
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t
}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle);
u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
|
/*! @license Firebase v4.0.0
Build: rev-c054dab
Terms: https://firebase.google.com/terms/ */
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _errors = require('../../app/errors');
var _errors2 = require('./errors');
var _errors3 = _interopRequireDefault(_errors2);
var _arrayBufferToBase = require('../helpers/array-buffer-to-base64');
var _arrayBufferToBase2 = _interopRequireDefault(_arrayBufferToBase);
var _fcmDetails = require('./fcm-details');
var _fcmDetails2 = _interopRequireDefault(_fcmDetails);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FCM_TOKEN_DETAILS_DB = 'fcm_token_details_db';
var FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';
var FCM_TOKEN_DETAILS_DB_VERSION = 1;
var TokenManager = function () {
function TokenManager() {
_classCallCheck(this, TokenManager);
this.errorFactory_ = new _errors.ErrorFactory('messaging', 'Messaging', _errors3.default.map);
this.openDbPromise_ = null;
}
/**
* Get the indexedDB as a promsie.
* @private
* @return {Promise<IDBDatabase>} The IndexedDB database
*/
_createClass(TokenManager, [{
key: 'openDatabase_',
value: function openDatabase_() {
if (this.openDbPromise_) {
return this.openDbPromise_;
}
this.openDbPromise_ = new Promise(function (resolve, reject) {
var request = indexedDB.open(FCM_TOKEN_DETAILS_DB, FCM_TOKEN_DETAILS_DB_VERSION);
request.onerror = function (event) {
reject(event.target.error);
};
request.onsuccess = function (event) {
resolve(event.target.result);
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {
keyPath: 'swScope'
});
// Make sure the sender ID can be searched
objectStore.createIndex('fcmSenderId', 'fcmSenderId', {
unique: false
});
objectStore.createIndex('fcmToken', 'fcmToken', {
unique: true
});
};
});
return this.openDbPromise_;
}
/**
* Close the currently open database.
* @return {Promise<?>} Returns the result of the promise chain.
*/
}, {
key: 'closeDatabase',
value: function closeDatabase() {
var _this = this;
if (this.openDbPromise_) {
return this.openDbPromise_.then(function (db) {
db.close();
_this.openDbPromise_ = null;
});
}
return Promise.resolve();
}
/**
* Given a token, this method will look up the details in indexedDB.
* @public
* @param {string} fcmToken
* @return {Promise<Object>} The details associated with that token.
*/
}, {
key: 'getTokenDetailsFromToken',
value: function getTokenDetailsFromToken(fcmToken) {
return this.openDatabase_().then(function (db) {
return new Promise(function (resolve, reject) {
var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);
var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);
var index = objectStore.index('fcmToken');
var request = index.get(fcmToken);
request.onerror = function (event) {
reject(event.target.error);
};
request.onsuccess = function (event) {
resolve(event.target.result);
};
});
});
}
}, {
key: 'getTokenDetailsFromSWScope_',
value: function getTokenDetailsFromSWScope_(swScope) {
return this.openDatabase_().then(function (db) {
return new Promise(function (resolve, reject) {
var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);
var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);
var scopeRequest = objectStore.get(swScope);
scopeRequest.onerror = function (event) {
reject(event.target.error);
};
scopeRequest.onsuccess = function (event) {
resolve(event.target.result);
};
});
});
}
}, {
key: 'getAllTokenDetailsForSenderId_',
value: function getAllTokenDetailsForSenderId_(senderId) {
return this.openDatabase_().then(function (db) {
return new Promise(function (resolve, reject) {
var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);
var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);
var senderIdTokens = [];
var cursorRequest = objectStore.openCursor();
cursorRequest.onerror = function (event) {
reject(event.target.error);
};
cursorRequest.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
if (cursor.value['fcmSenderId'] === senderId) {
senderIdTokens.push(cursor.value);
}
cursor.continue();
} else {
resolve(senderIdTokens);
}
};
});
});
}
/**
* Given a PushSubscription and messagingSenderId, get an FCM token.
* @public
* @param {string} senderId The 'messagingSenderId' to tie the token to.
* @param {PushSubscription} subscription The PushSusbcription to "federate".
* @param {string=} pushSet If defined this will swap the subscription for
* matching FCM token.
* @return {Promise<!Object>} Returns the FCM token to be used in place
* of the PushSubscription.
*/
}, {
key: 'subscribeToFCM',
value: function subscribeToFCM(senderId, subscription, pushSet) {
var _this2 = this;
var p256dh = (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh'));
var auth = (0, _arrayBufferToBase2.default)(subscription['getKey']('auth'));
var fcmSubscribeBody = 'authorized_entity=' + senderId + '&' + ('endpoint=' + subscription.endpoint + '&') + ('encryption_key=' + p256dh + '&') + ('encryption_auth=' + auth);
if (pushSet) {
fcmSubscribeBody += '&pushSet=' + pushSet;
}
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
var subscribeOptions = {
method: 'POST',
headers: headers,
body: fcmSubscribeBody
};
return fetch(_fcmDetails2.default.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions).then(function (response) {
return response.json();
}).then(function (response) {
var fcmTokenResponse = response;
if (fcmTokenResponse['error']) {
var message = fcmTokenResponse['error']['message'];
throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_FAILED, { 'message': message });
}
if (!fcmTokenResponse['token']) {
throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_NO_TOKEN);
}
if (!fcmTokenResponse['pushSet']) {
throw _this2.errorFactory_.create(_errors3.default.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);
}
return {
'token': fcmTokenResponse['token'],
'pushSet': fcmTokenResponse['pushSet']
};
});
}
/**
* Checks the that fields in the PushSubscription are equivalent to the
* details stores in the masterTokenDetails.
* @private
* @param {PushSubscription} subscription The push subscription we expect
* the master token to match.
* @param {Object} masterTokenDetails The saved details we wish to compare
* with the PushSubscription
* @return {boolean} true if the subscription and token details are
* equivalent.
*/
}, {
key: 'isSameSubscription_',
value: function isSameSubscription_(subscription, masterTokenDetails) {
// getKey() isn't defined in the PushSubscription externs file, hence
// subscription['getKey']('<key name>').
return subscription.endpoint === masterTokenDetails['endpoint'] && (0, _arrayBufferToBase2.default)(subscription['getKey']('auth')) === masterTokenDetails['auth'] && (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh')) === masterTokenDetails['p256dh'];
}
/**
* Save the details for the fcm token for re-use at a later date.
* @private
* @param {string} senderId The 'messagingSenderId' used for this project
* @param {ServiceWorkerRegistration} swRegistration The service worker
* used to subscribe the user for web push
* @param {PushSubscription} subscription The push subscription passed to
* FCM for the current token.
* @param {string} fcmToken The FCM token currently used on this
* device.
* @param {string} fcmPushSet The FCM push tied to the fcm token.
* @return {Promise<void>}
*/
}, {
key: 'saveTokenDetails_',
value: function saveTokenDetails_(senderId, swRegistration, subscription, fcmToken, fcmPushSet) {
var details = {
'swScope': swRegistration.scope,
'endpoint': subscription.endpoint,
'auth': (0, _arrayBufferToBase2.default)(subscription['getKey']('auth')),
'p256dh': (0, _arrayBufferToBase2.default)(subscription['getKey']('p256dh')),
'fcmToken': fcmToken,
'fcmPushSet': fcmPushSet,
'fcmSenderId': senderId
};
return this.openDatabase_().then(function (db) {
return new Promise(function (resolve, reject) {
var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');
var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);
var request = objectStore.put(details);
request.onerror = function (event) {
reject(event.target.error);
};
request.onsuccess = function () {
resolve();
};
});
});
}
/**
* Returns the saved FCM Token if one is available and still valid,
* otherwise `null` is returned.
* @param {string} senderId This should be the sender ID associated with the
* FCM Token being retrieved.
* @param {ServiceWorkerRegistration} swRegistration Registration to be used
* to subscribe the user to push.
* @return {Promise<string> | Promise} Returns the saved FCM Token if
* avilable and valid.
* @export
*/
}, {
key: 'getSavedToken',
value: function getSavedToken(senderId, swRegistration) {
var _this3 = this;
if (!(swRegistration instanceof ServiceWorkerRegistration)) {
return Promise.reject(this.errorFactory_.create(_errors3.default.codes.SW_REGISTRATION_EXPECTED));
}
if (typeof senderId !== 'string' || senderId.length === 0) {
return Promise.reject(this.errorFactory_.create(_errors3.default.codes.BAD_SENDER_ID));
}
return this.getAllTokenDetailsForSenderId_(senderId).then(function (allTokenDetails) {
if (allTokenDetails.length === 0) {
return;
}
var index = allTokenDetails.findIndex(function (tokenDetails) {
return swRegistration.scope === tokenDetails['swScope'] && senderId === tokenDetails['fcmSenderId'];
});
if (index === -1) {
return;
}
return allTokenDetails[index];
}).then(function (tokenDetails) {
if (!tokenDetails) {
return;
}
return swRegistration.pushManager.getSubscription().catch(function () {
throw _this3.errorFactory_.create(_errors3.default.codes.GET_SUBSCRIPTION_FAILED);
}).then(function (subscription) {
if (subscription && _this3.isSameSubscription_(subscription, tokenDetails)) {
return tokenDetails['fcmToken'];
}
});
});
}
/**
* Creates a new FCM token.
*/
}, {
key: 'createToken',
value: function createToken(senderId, swRegistration) {
var _this4 = this;
if (typeof senderId !== 'string' || senderId.length === 0) {
return Promise.reject(this.errorFactory_.create(_errors3.default.codes.BAD_SENDER_ID));
}
if (!(swRegistration instanceof ServiceWorkerRegistration)) {
return Promise.reject(this.errorFactory_.create(_errors3.default.codes.SW_REGISTRATION_EXPECTED));
}
// Check for existing subscription first
var subscription = void 0;
var fcmTokenDetails = void 0;
return swRegistration.pushManager.getSubscription().then(function (subscription) {
if (subscription) {
return subscription;
}
return swRegistration.pushManager.subscribe(_fcmDetails2.default.SUBSCRIPTION_OPTIONS);
}).then(function (sub) {
subscription = sub;
return _this4.subscribeToFCM(senderId, subscription);
}).then(function (tokenDetails) {
fcmTokenDetails = tokenDetails;
return _this4.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);
}).then(function () {
return fcmTokenDetails['token'];
});
}
/**
* This method deletes details of the current FCM token.
* It's returning a promise in case we need to move to an async
* method for deleting at a later date.
* @param {string} token Token to be deleted
* @return {Promise<Object>} Resolves once the FCM token details have been
* deleted and returns the deleted details.
*/
}, {
key: 'deleteToken',
value: function deleteToken(token) {
var _this5 = this;
if (typeof token !== 'string' || token.length === 0) {
return Promise.reject(this.errorFactory_.create(_errors3.default.codes.INVALID_DELETE_TOKEN));
}
return this.getTokenDetailsFromToken(token).then(function (details) {
if (!details) {
throw _this5.errorFactory_.create(_errors3.default.codes.DELETE_TOKEN_NOT_FOUND);
}
return _this5.openDatabase_().then(function (db) {
return new Promise(function (resolve, reject) {
var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');
var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);
var request = objectStore.delete(details['swScope']);
request.onerror = function (event) {
reject(event.target.error);
};
request.onsuccess = function (event) {
if (event.target.result === 0) {
reject(_this5.errorFactory_.create(_errors3.default.codes.FAILED_TO_DELETE_TOKEN));
return;
}
resolve(details);
};
});
});
});
}
}]);
return TokenManager;
}();
exports.default = TokenManager;
module.exports = exports['default'];
//# sourceMappingURL=token-manager.js.map
|
'''
Gesture recognition
===================
This class allows you to easily create new
gestures and compare them::
from kivy.gesture import Gesture, GestureDatabase
# Create a gesture
g = Gesture()
g.add_stroke(point_list=[(1,1), (3,4), (2,1)])
g.normalize()
# Add it to the database
gdb = GestureDatabase()
gdb.add_gesture(g)
# And for the next gesture, try to find it!
g2 = Gesture()
# ...
gdb.find(g2)
.. warning::
You don't really want to do this: it's more of an example of how
to construct gestures dynamically. Typically, you would
need a lot more points, so it's better to record gestures in a file and
reload them to compare later. Look in the examples/gestures directory for
an example of how to do that.
'''
__all__ = ('Gesture', 'GestureDatabase', 'GesturePoint', 'GestureStroke')
import pickle
import base64
import zlib
import math
from kivy.vector import Vector
from io import BytesIO
class GestureDatabase(object):
'''Class to handle a gesture database.'''
def __init__(self):
self.db = []
def add_gesture(self, gesture):
'''Add a new gesture to the database.'''
self.db.append(gesture)
def find(self, gesture, minscore=0.9, rotation_invariant=True):
'''Find a matching gesture in the database.'''
if not gesture:
return
best = None
bestscore = minscore
for g in self.db:
score = g.get_score(gesture, rotation_invariant)
if score < bestscore:
continue
bestscore = score
best = g
if not best:
return
return (bestscore, best)
def gesture_to_str(self, gesture):
'''Convert a gesture into a unique string.'''
io = BytesIO()
p = pickle.Pickler(io)
p.dump(gesture)
data = base64.b64encode(zlib.compress(io.getvalue(), 9))
return data
def str_to_gesture(self, data):
'''Convert a unique string to a gesture.'''
io = BytesIO(zlib.decompress(base64.b64decode(data)))
p = pickle.Unpickler(io)
gesture = p.load()
return gesture
class GesturePoint:
def __init__(self, x, y):
'''Stores the x,y coordinates of a point in the gesture.'''
self.x = float(x)
self.y = float(y)
def scale(self, factor):
''' Scales the point by the given factor.'''
self.x *= factor
self.y *= factor
return self
def __repr__(self):
return 'Mouse_point: %f,%f' % (self.x, self.y)
class GestureStroke:
''' Gestures can be made up of multiple strokes.'''
def __init__(self):
''' A stroke in the gesture.'''
self.points = list()
self.screenpoints = list()
# These return the min and max coordinates of the stroke
@property
def max_x(self):
if len(self.points) == 0:
return 0
return max(self.points, key=lambda pt: pt.x).x
@property
def min_x(self):
if len(self.points) == 0:
return 0
return min(self.points, key=lambda pt: pt.x).x
@property
def max_y(self):
if len(self.points) == 0:
return 0
return max(self.points, key=lambda pt: pt.y).y
@property
def min_y(self):
if len(self.points) == 0:
return 0
return min(self.points, key=lambda pt: pt.y).y
def add_point(self, x, y):
'''
add_point(x=x_pos, y=y_pos)
Adds a point to the stroke.
'''
self.points.append(GesturePoint(x, y))
self.screenpoints.append((x, y))
def scale_stroke(self, scale_factor):
'''
scale_stroke(scale_factor=float)
Scales the stroke down by scale_factor.
'''
self.points = [pt.scale(scale_factor) for pt in self.points]
def points_distance(self, point1, point2):
'''
points_distance(point1=GesturePoint, point2=GesturePoint)
Returns the distance between two GesturePoints.
'''
x = point1.x - point2.x
y = point1.y - point2.y
return math.sqrt(x * x + y * y)
def stroke_length(self, point_list=None):
'''Finds the length of the stroke. If a point list is given,
finds the length of that list.
'''
if point_list is None:
point_list = self.points
gesture_length = 0.0
if len(point_list) <= 1: # If there is only one point -> no length
return gesture_length
for i in range(len(point_list) - 1):
gesture_length += self.points_distance(
point_list[i], point_list[i + 1])
return gesture_length
def normalize_stroke(self, sample_points=32):
'''Normalizes strokes so that every stroke has a standard number of
points. Returns True if stroke is normalized, False if it can't be
normalized. sample_points controls the resolution of the stroke.
'''
# If there is only one point or the length is 0, don't normalize
if len(self.points) <= 1 or self.stroke_length(self.points) == 0.0:
return False
# Calculate how long each point should be in the stroke
target_stroke_size = \
self.stroke_length(self.points) / float(sample_points)
new_points = list()
new_points.append(self.points[0])
# We loop on the points
prev = self.points[0]
src_distance = 0.0
dst_distance = target_stroke_size
for curr in self.points[1:]:
d = self.points_distance(prev, curr)
if d > 0:
prev = curr
src_distance = src_distance + d
# The new point need to be inserted into the
# segment [prev, curr]
while dst_distance < src_distance:
x_dir = curr.x - prev.x
y_dir = curr.y - prev.y
ratio = (src_distance - dst_distance) / d
to_x = x_dir * ratio + prev.x
to_y = y_dir * ratio + prev.y
new_points.append(GesturePoint(to_x, to_y))
dst_distance = self.stroke_length(self.points) / \
float(sample_points) * len(new_points)
# If this happens, we are into troubles...
if not len(new_points) == sample_points:
raise ValueError('Invalid number of strokes points; got '
'%d while it should be %d' %
(len(new_points), sample_points))
self.points = new_points
return True
def center_stroke(self, offset_x, offset_y):
'''Centers the stroke by offseting the points.'''
for point in self.points:
point.x -= offset_x
point.y -= offset_y
class Gesture:
'''A python implementation of a gesture recognition algorithm by
Oleg Dopertchouk: http://www.gamedev.net/reference/articles/article2039.asp
Implemented by Jeiel Aranal (chemikhazi@gmail.com),
released into the public domain.
'''
# Tolerance for evaluation using the '==' operator
DEFAULT_TOLERANCE = 0.1
def __init__(self, tolerance=None):
'''
Gesture([tolerance=float])
Creates a new gesture with an optional matching tolerance value.
'''
self.width = 0.
self.height = 0.
self.gesture_product = 0.
self.strokes = list()
if tolerance is None:
self.tolerance = Gesture.DEFAULT_TOLERANCE
else:
self.tolerance = tolerance
def _scale_gesture(self):
''' Scales down the gesture to a unit of 1.'''
# map() creates a list of min/max coordinates of the strokes
# in the gesture and min()/max() pulls the lowest/highest value
min_x = min([stroke.min_x for stroke in self.strokes])
max_x = max([stroke.max_x for stroke in self.strokes])
min_y = min([stroke.min_y for stroke in self.strokes])
max_y = max([stroke.max_y for stroke in self.strokes])
x_len = max_x - min_x
self.width = x_len
y_len = max_y - min_y
self.height = y_len
scale_factor = max(x_len, y_len)
if scale_factor <= 0.0:
return False
scale_factor = 1.0 / scale_factor
for stroke in self.strokes:
stroke.scale_stroke(scale_factor)
return True
def _center_gesture(self):
''' Centers the Gesture.points of the gesture.'''
total_x = 0.0
total_y = 0.0
total_points = 0
for stroke in self.strokes:
# adds up all the points inside the stroke
stroke_y = sum([pt.y for pt in stroke.points])
stroke_x = sum([pt.x for pt in stroke.points])
total_y += stroke_y
total_x += stroke_x
total_points += len(stroke.points)
if total_points == 0:
return False
# Average to get the offset
total_x /= total_points
total_y /= total_points
# Apply the offset to the strokes
for stroke in self.strokes:
stroke.center_stroke(total_x, total_y)
return True
def add_stroke(self, point_list=None):
'''Adds a stroke to the gesture and returns the Stroke instance.
Optional point_list argument is a list of the mouse points for
the stroke.
'''
self.strokes.append(GestureStroke())
if isinstance(point_list, list) or isinstance(point_list, tuple):
for point in point_list:
if isinstance(point, GesturePoint):
self.strokes[-1].points.append(point)
elif isinstance(point, list) or isinstance(point, tuple):
if len(point) != 2:
raise ValueError("Stroke entry must have 2 values max")
self.strokes[-1].add_point(point[0], point[1])
else:
raise TypeError("The point list should either be "
"tuples of x and y or a list of "
"GesturePoint objects")
elif point_list is not None:
raise ValueError("point_list should be a tuple/list")
return self.strokes[-1]
def normalize(self, stroke_samples=32):
'''Runs the gesture normalization algorithm and calculates the dot
product with self.
'''
if not self._scale_gesture() or not self._center_gesture():
self.gesture_product = False
return False
for stroke in self.strokes:
stroke.normalize_stroke(stroke_samples)
self.gesture_product = self.dot_product(self)
def get_rigid_rotation(self, dstpts):
'''
Extract the rotation to apply to a group of points to minimize the
distance to a second group of points. The two groups of points are
assumed to be centered. This is a simple version that just picks
an angle based on the first point of the gesture.
'''
if len(self.strokes) < 1 or len(self.strokes[0].points) < 1:
return 0
if len(dstpts.strokes) < 1 or len(dstpts.strokes[0].points) < 1:
return 0
p = dstpts.strokes[0].points[0]
target = Vector([p.x, p.y])
source = Vector([p.x, p.y])
return source.angle(target)
def dot_product(self, comparison_gesture):
''' Calculates the dot product of the gesture with another gesture.'''
if len(comparison_gesture.strokes) != len(self.strokes):
return -1
if getattr(comparison_gesture, 'gesture_product', True) is False or \
getattr(self, 'gesture_product', True) is False:
return -1
dot_product = 0.0
for stroke_index, (my_stroke, cmp_stroke) in enumerate(
list(zip(self.strokes, comparison_gesture.strokes))):
for pt_index, (my_point, cmp_point) in enumerate(
list(zip(my_stroke.points, cmp_stroke.points))):
dot_product += (my_point.x * cmp_point.x +
my_point.y * cmp_point.y)
return dot_product
def rotate(self, angle):
g = Gesture()
for stroke in self.strokes:
tmp = []
for j in stroke.points:
v = Vector([j.x, j.y]).rotate(angle)
tmp.append(v)
g.add_stroke(tmp)
g.gesture_product = g.dot_product(g)
return g
def get_score(self, comparison_gesture, rotation_invariant=True):
''' Returns the matching score of the gesture against another gesture.
'''
if isinstance(comparison_gesture, Gesture):
if rotation_invariant:
# get orientation
angle = self.get_rigid_rotation(comparison_gesture)
# rotate the gesture to be in the same frame.
comparison_gesture = comparison_gesture.rotate(angle)
# this is the normal "orientation" code.
score = self.dot_product(comparison_gesture)
if score <= 0:
return score
score /= math.sqrt(
self.gesture_product * comparison_gesture.gesture_product)
return score
def __eq__(self, comparison_gesture):
''' Allows easy comparisons between gesture instances.'''
if isinstance(comparison_gesture, Gesture):
# If the gestures don't have the same number of strokes, its
# definitely not the same gesture
score = self.get_score(comparison_gesture)
if (score > (1.0 - self.tolerance) and
score < (1.0 + self.tolerance)):
return True
else:
return False
else:
return NotImplemented
def __ne__(self, comparison_gesture):
result = self.__eq__(comparison_gesture)
if result is NotImplemented:
return result
else:
return not result
def __lt__(self, comparison_gesture):
raise TypeError("Gesture cannot be evaluated with <")
def __gt__(self, comparison_gesture):
raise TypeError("Gesture cannot be evaluated with >")
def __le__(self, comparison_gesture):
raise TypeError("Gesture cannot be evaluated with <=")
def __ge__(self, comparison_gesture):
raise TypeError("Gesture cannot be evaluated with >=")
|
const path = require('path');
const distPath = path.join(__dirname, '/dist');
const config = {
entry: {
main: './src/index.js'
},
output: {
filename: 'bundle.js',
path: distPath,
libraryTarget: "umd",
globalObject: "this",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
}
}
]
},
devServer: {
contentBase: distPath,
port: 9000,
compress: true
}
};
module.exports = config;
|
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: developers@cryptoapis.io
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import cryptoapis
from cryptoapis.model.banned_ip_address_details import BannedIpAddressDetails
globals()['BannedIpAddressDetails'] = BannedIpAddressDetails
from cryptoapis.model.banned_ip_address import BannedIpAddress
class TestBannedIpAddress(unittest.TestCase):
"""BannedIpAddress unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testBannedIpAddress(self):
"""Test BannedIpAddress"""
# FIXME: construct object with mandatory attributes with example values
# model = BannedIpAddress() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
from .http_client_pool_interface import HttpClientPoolInterface
|
import logging
import voluptuous as vol
import esphomeyaml.config_validation as cv
from esphomeyaml.const import CONF_ID, CONF_OTA, CONF_PASSWORD, CONF_PORT, CONF_SAFE_MODE
from esphomeyaml.core import CORE
from esphomeyaml.cpp_generator import Pvariable, add
from esphomeyaml.cpp_types import App, Component, esphomelib_ns
_LOGGER = logging.getLogger(__name__)
OTAComponent = esphomelib_ns.class_('OTAComponent', Component)
CONFIG_SCHEMA = vol.Schema({
cv.GenerateID(): cv.declare_variable_id(OTAComponent),
vol.Optional(CONF_SAFE_MODE, default=True): cv.boolean,
vol.Optional(CONF_PORT): cv.port,
vol.Optional(CONF_PASSWORD): cv.string,
})
def to_code(config):
rhs = App.init_ota()
ota = Pvariable(config[CONF_ID], rhs)
if CONF_PASSWORD in config:
add(ota.set_auth_password(config[CONF_PASSWORD]))
if CONF_PORT in config:
add(ota.set_port(config[CONF_PORT]))
if config[CONF_SAFE_MODE]:
add(ota.start_safe_mode())
def get_port(config):
if CONF_PORT in config[CONF_OTA]:
return config[CONF_OTA][CONF_PORT]
if CORE.is_esp32:
return 3232
if CORE.is_esp8266:
return 8266
raise NotImplementedError
def get_auth(config):
return config[CONF_OTA].get(CONF_PASSWORD, '')
BUILD_FLAGS = '-DUSE_OTA'
REQUIRED_BUILD_FLAGS = '-DUSE_NEW_OTA'
def lib_deps(config):
if CORE.is_esp32:
return ['Update', 'ESPmDNS']
if CORE.is_esp8266:
return ['Hash', 'ESP8266mDNS']
raise NotImplementedError
|
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Tests of the ZopeStarter class """
import cStringIO
import errno
import logging
import os
import random
import sys
import tempfile
import unittest
import ZConfig
from ZConfig.components.logger.tests import test_logger
from ZConfig.components.logger.loghandler import NullHandler
import Zope2.Startup
import Products
from App.config import getConfiguration, setConfiguration
TEMPNAME = tempfile.mktemp()
TEMPPRODUCTS = os.path.join(TEMPNAME, "Products")
def getSchema():
startup = os.path.dirname(Zope2.Startup.__file__)
schemafile = os.path.join(startup, 'zopeschema.xml')
return ZConfig.loadSchema(schemafile)
# try to preserve logging state so we don't screw up other unit tests
# that come later
logger_states = {}
for name in (None, 'trace', 'access'):
logger = logging.getLogger(name)
logger_states[name] = {'level':logger.level,
'propagate':logger.propagate,
'handlers':logger.handlers,
'filters':logger.filters}
class ZopeStarterTestCase(test_logger.LoggingTestBase):
schema = None
def setUp(self):
from ZConfig.components.logger import loghandler
if self.schema is None:
ZopeStarterTestCase.schema = getSchema()
test_logger.LoggingTestBase.setUp(self)
def tearDown(self):
try:
os.rmdir(TEMPPRODUCTS)
os.rmdir(TEMPNAME)
except:
pass
Products.__path__ = [d for d in Products.__path__
if os.path.exists(d)]
test_logger.LoggingTestBase.tearDown(self)
# reset logger states
for name in (None, 'access', 'trace'):
logger = logging.getLogger(name)
logger.__dict__.update(logger_states[name])
def _clearHandlers(self):
from ZConfig.components.logger import loghandler
del loghandler._reopenable_handlers[:]
def get_starter(self, conf):
starter = Zope2.Startup.get_starter()
starter.setConfiguration(conf)
return starter
def load_config_text(self, text):
# We have to create a directory of our own since the existence
# of the directory is checked. This handles this in a
# platform-independent way.
schema = self.schema
sio = cStringIO.StringIO(
text.replace("<<INSTANCE_HOME>>", TEMPNAME))
try:
os.mkdir(TEMPNAME)
os.mkdir(TEMPPRODUCTS)
except OSError, why:
if why == 17:
# already exists
pass
conf, self.handler = ZConfig.loadConfigFile(schema, sio)
self.assertEqual(conf.instancehome, TEMPNAME)
return conf
def testSetupLocale(self):
# XXX this almost certainly won't work on all systems
import locale
try:
try:
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
locale en_GB""")
except ZConfig.DataConversionError, e:
# Skip this test if we don't have support.
if e.message.startswith(
'The specified locale "en_GB" is not supported'):
return
raise
starter = self.get_starter(conf)
starter.setupLocale()
self.assertEqual(tuple(locale.getlocale()), ('en_GB', 'ISO8859-1'))
finally:
# reset to system-defined locale
locale.setlocale(locale.LC_ALL, '')
def testSetupStartupHandler(self):
if sys.platform[:3].lower() == "win":
return
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
debug-mode on
<eventlog>
level info
<logfile>
path <<INSTANCE_HOME>>/event.log
level info
</logfile>
<logfile>
path <<INSTANCE_HOME>>/event2.log
level blather
</logfile>
</eventlog>""")
starter = self.get_starter(conf)
starter.setupInitialLogging()
# startup handler should take on the level of the event log handler
# with the lowest level
logger = starter.event_logger
self.assertEqual(starter.startup_handler.level, 15) # 15 is BLATHER
self.assert_(starter.startup_handler in logger.handlers)
self.assertEqual(logger.level, 15)
# We expect a debug handler and the startup handler:
self.assertEqual(len(logger.handlers), 2)
# XXX need to check that log messages get written to
# sys.stderr, not that the stream identity for the startup
# handler matches
#self.assertEqual(starter.startup_handler.stream, sys.stderr)
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
debug-mode off
<eventlog>
level info
<logfile>
path <<INSTANCE_HOME>>/event.log
level info
</logfile>
</eventlog>""")
starter = self.get_starter(conf)
starter.setupInitialLogging()
# XXX need to check that log messages get written to
# sys.stderr, not that the stream identity for the startup
# handler matches
#self.assertNotEqual(starter.startup_handler.stream, sys.stderr)
def testSetupZServerThreads(self):
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
zserver-threads 10""")
starter = self.get_starter(conf)
starter.setupZServer()
from ZServer.PubCore import _n
self.assertEqual(_n, 10)
def testSetupServers(self):
# We generate a random port number to test against, so that multiple
# test runs of this at the same time can succeed
port = random.randint(10000, 50000)
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
<http-server>
address %(http)s
</http-server>
<ftp-server>
address %(ftp)s
</ftp-server>""" % dict(http=port, ftp=port+1)
)
starter = self.get_starter(conf)
# do the job the 'handler' would have done (call prepare)
for server in conf.servers:
server.prepare('', None, 'Zope2', {}, None)
try:
starter.setupServers()
import ZServer
self.assertEqual(conf.servers[0].__class__,
ZServer.HTTPServer.zhttp_server)
self.assertEqual(conf.servers[1].__class__,
ZServer.FTPServer)
finally:
del conf.servers # should release servers
pass
def testDropPrivileges(self):
# somewhat incomplete because we we're never running as root
# when we test, but we test as much as we can
if os.name != 'posix':
return
_old_getuid = os.getuid
def _return0():
return 0
def make_starter(conf):
# remove the debug handler, since we don't want junk on
# stderr for the tests
starter = self.get_starter(conf)
starter.event_logger.removeHandler(starter.debug_handler)
return starter
try:
os.getuid = _return0
# no effective user
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>""")
starter = make_starter(conf)
self.assertRaises(ZConfig.ConfigurationError,
starter.dropPrivileges)
# cant find user in passwd database
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
effective-user n0sucHuS3r""")
starter = make_starter(conf)
self.assertRaises(ZConfig.ConfigurationError,
starter.dropPrivileges)
# can't specify '0' as effective user
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
effective-user 0""")
starter = make_starter(conf)
self.assertRaises(ZConfig.ConfigurationError,
starter.dropPrivileges)
# setuid to test runner's uid XXX will this work cross-platform?
runnerid = _old_getuid()
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
effective-user %s""" % runnerid)
starter = make_starter(conf)
finished = starter.dropPrivileges()
self.assertTrue(finished)
finally:
os.getuid = _old_getuid
def testSetupConfiguredLoggers(self):
if sys.platform[:3].lower() == "win":
return
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
debug-mode off
<eventlog>
level info
<logfile>
path <<INSTANCE_HOME>>/event.log
level info
</logfile>
</eventlog>
<logger access>
level info
<logfile>
path <<INSTANCE_HOME>>/Z2.log
</logfile>
</logger>
<logger trace>
level info
<logfile>
path <<INSTANCE_HOME>>/trace.log
</logfile>
</logger>
""")
try:
starter = self.get_starter(conf)
starter.setupInitialLogging()
starter.info('hello')
starter.setupFinalLogging()
logger = logging.getLogger()
self.assertEqual(logger.level, logging.INFO)
l = open(os.path.join(TEMPNAME, 'event.log')).read()
self.assertTrue(l.find('hello') > -1)
self.assertTrue(os.path.exists(os.path.join(TEMPNAME, 'Z2.log')))
self.assertTrue(os.path.exists(os.path.join(TEMPNAME,'trace.log')))
finally:
for name in ('event.log', 'Z2.log', 'trace.log'):
try:
os.unlink(os.path.join(TEMPNAME, name))
except:
pass
self._clearHandlers()
def testMakeLockFile(self):
# put something in the way (it should be deleted)
name = os.path.join(TEMPNAME, 'lock')
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
lock-filename %s""" % name
)
f = open(name, 'ab')
# On Windows, the first byte of the file is locked solid, and even
# we (this process) can't read from it via a file object other
# than the one passed to lock_file. So we put a blank
# in the test value first, so we can skip over it later. Also,
# because .seek(1) isn't well-defined for files opened in text
# mode, we open the file in binary mode (above and below).
f.write(' hello')
f.close()
try:
starter = self.get_starter(conf)
starter.makeLockFile()
f = open(name, 'rb')
f.seek(1) # skip over the locked byte
guts = f.read()
f.close()
self.assertFalse(guts.find('hello') > -1)
finally:
starter.unlinkLockFile()
self.assertFalse(os.path.exists(name))
def testMakePidFile(self):
# put something in the way (it should be deleted)
name = os.path.join(TEMPNAME, 'pid')
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
pid-filename %s""" % name
)
f = open(name, 'a')
f.write('hello')
f.close()
try:
starter = self.get_starter(conf)
starter.makePidFile()
self.assertFalse(open(name).read().find('hello') > -1)
finally:
starter.unlinkPidFile()
self.assertFalse(os.path.exists(name))
def testConfigureInterpreter(self):
import sys
oldcheckinterval = sys.getcheckinterval()
newcheckinterval = oldcheckinterval + 1
conf = self.load_config_text("""
instancehome <<INSTANCE_HOME>>
python-check-interval %d
""" % newcheckinterval
)
try:
starter = self.get_starter(conf)
starter.setupInterpreter()
self.assertEqual( sys.getcheckinterval() , newcheckinterval )
finally:
sys.setcheckinterval(oldcheckinterval)
def testZopeRunConfigure(self):
old_config = getConfiguration()
try:
os.mkdir(TEMPNAME)
os.mkdir(TEMPPRODUCTS)
except OSError, why:
if why == errno.EEXIST:
# already exists
pass
old_argv = sys.argv
sys.argv = [sys.argv[0]]
try:
fname = os.path.join(TEMPNAME, 'zope.conf')
from Zope2 import configure
f = open(fname, 'w')
f.write('instancehome %s\nzserver-threads 100\n' % TEMPNAME)
f.flush()
f.close()
configure(fname)
new_config = getConfiguration()
self.assertEqual(new_config.zserver_threads, 100)
finally:
sys.argv = old_argv
try:
os.unlink(fname)
except:
pass
setConfiguration(old_config)
def test_suite():
return unittest.makeSuite(ZopeStarterTestCase)
|
# Reference: https://infocenter.nordicsemi.com/pdf/nRF24LE1_PS_v1.6.pdf
# Accession: G00035
import os
import math
import asyncio
import logging
import argparse
import struct
from collections import namedtuple
from amaranth.compat import *
from fx2.format import input_data, output_data
from ....support.logging import dump_hex
from ...interface.spi_controller import SPIControllerSubtarget, SPIControllerInterface
from ... import *
class ProgramNRF24Lx1Error(GlasgowAppletError):
pass
_MemoryArea = namedtuple("_MemoryArea", ("name", "mem_addr", "spi_addr", "size"))
_nrf24le1_map = [
_MemoryArea(name="code", mem_addr= 0x0000, spi_addr= 0x0000, size=0x4000),
_MemoryArea(name="NV data", mem_addr= 0xFC00, spi_addr= 0x4400, size=0x0400),
_MemoryArea(name="info", mem_addr=0x10000, spi_addr=0x10000, size=0x0200),
]
_nrf24lu1p_32k_map = [
_MemoryArea(name="code", mem_addr= 0x0000, spi_addr= 0x0000, size=0x7C00),
_MemoryArea(name="NV data", mem_addr= 0x7C00, spi_addr= 0x7C00, size=0x0400),
_MemoryArea(name="info", mem_addr=0x10000, spi_addr=0x10000, size=0x0200),
]
_nrf24lu1p_16k_map = [
_MemoryArea(name="code", mem_addr= 0x0000, spi_addr= 0x0000, size=0x3C00),
_MemoryArea(name="NV data", mem_addr= 0x7C00, spi_addr= 0x7C00, size=0x0400),
_MemoryArea(name="info", mem_addr=0x10000, spi_addr=0x10000, size=0x0200),
]
FSR_BIT_ENDEBUG = 0b10000000
FSR_BIT_STP = 0b01000000
FSR_BIT_WEN = 0b00100000
FSR_BIT_RDYN = 0b00010000
FSR_BIT_INFEN = 0b00001000
FSR_BIT_RDISMB = 0b00000100
class ProgramNRF24Lx1Interface:
def __init__(self, interface, logger, device, addr_dut_prog, addr_dut_reset):
self.lower = interface
self._logger = logger
self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE
self._device = device
self._addr_dut_prog = addr_dut_prog
self._addr_dut_reset = addr_dut_reset
def _log(self, message, *args):
self._logger.log(self._level, "nRF24Lx1: " + message, *args)
async def _reset(self):
await self._device.write_register(self._addr_dut_reset, 1)
await asyncio.sleep(0.001) # 0.1 us
await self._device.write_register(self._addr_dut_reset, 0)
async def reset_program(self):
self._log("reset mode=program")
await self.lower.synchronize()
await self._device.write_register(self._addr_dut_prog, 1)
await self._reset()
await self.lower.synchronize()
await self.lower.delay_us(1500)
async def reset_application(self):
self._log("reset mode=application")
await self.lower.synchronize()
await self._device.write_register(self._addr_dut_prog, 0)
await self._reset()
async def _command(self, cmd, arg=[], ret=0):
self._log("cmd=%02X arg=<%s> ret=%d", cmd, dump_hex(arg), ret)
await self.lower.write(bytearray([cmd, *arg]),
hold_ss=(ret > 0))
if ret > 0:
result = await self.lower.read(ret)
self._log("res=<%s>", dump_hex(result))
return result
async def read_status(self):
status, = await self._command(0x05, ret=1)
self._log("read status=%s", "{:#010b}".format(status))
return status
async def write_status(self, status):
self._log("write status=%s", "{:#010b}".format(status))
await self._command(0x01, arg=[status])
async def wait_status(self):
self._log("wait status")
while await self.read_status() & FSR_BIT_WEN: pass
async def write_enable(self):
self._log("write enable")
await self._command(0x06)
async def write_disable(self):
self._log("write disable")
await self._command(0x04)
async def read(self, address, length):
self._log("read address=%#06x length=%#06x", address, length)
return await self._command(0x03, arg=struct.pack(">H", address), ret=length)
async def program(self, address, data):
self._log("program address=%#06x length=%#06x", address, len(data))
await self._command(0x02, arg=struct.pack(">H", address) + bytes(data))
async def erase_page(self, page):
self._log("erase page=%#04x", page)
await self._command(0x52, arg=[page])
async def erase_all(self):
self._log("erase all")
await self._command(0x62)
async def read_unprotected_pages(self):
pages, = await self._command(0x89, ret=1)
self._log("read unprotected pages=%#04x", pages)
return pages
async def disable_read(self):
self._log("disable read")
await self._command(0x85)
async def enable_debug(self):
self._log("enable debug")
await self._command(0x86)
class ProgramNRF24Lx1Applet(GlasgowApplet, name="program-nrf24lx1"):
logger = logging.getLogger(__name__)
help = "program nRF24LE1 and nRF24LU1+ RF microcontrollers"
description = """
Program the non-volatile memory of nRF24LE1 and nRF24LU1+ microcontrollers.
"""
__pins = ("prog", "sck", "copi", "cipo", "cs", "reset")
@classmethod
def add_build_arguments(cls, parser, access):
access.add_build_arguments(parser)
# Order matches the pin order, in clockwise direction.
access.add_pin_argument(parser, "prog", default=True)
access.add_pin_argument(parser, "sck", default=True)
access.add_pin_argument(parser, "copi", default=True)
access.add_pin_argument(parser, "cipo", default=True)
access.add_pin_argument(parser, "cs", default=True)
access.add_pin_argument(parser, "reset", default=True)
parser.add_argument(
"-f", "--frequency", metavar="FREQ", type=int, default=1000,
help="set SPI frequency to FREQ kHz (default: %(default)s)")
def build(self, target, args):
dut_prog, self.__addr_dut_prog = target.registers.add_rw(1)
dut_reset, self.__addr_dut_reset = target.registers.add_rw(1)
self.mux_interface = iface = target.multiplexer.claim_interface(self, args)
pads = iface.get_pads(args, pins=self.__pins)
subtarget = iface.add_subtarget(SPIControllerSubtarget(
pads=pads,
out_fifo=iface.get_out_fifo(),
in_fifo=iface.get_in_fifo(auto_flush=True),
period_cyc=math.ceil(target.sys_clk_freq / (args.frequency * 1000)),
delay_cyc=math.ceil(target.sys_clk_freq / 1e6),
sck_idle=0,
sck_edge="rising",
cs_active=0,
))
subtarget.comb += [
pads.prog_t.o.eq(dut_prog),
pads.prog_t.oe.eq(1),
pads.reset_t.o.eq(~dut_reset),
pads.reset_t.oe.eq(1),
subtarget.bus.oe.eq(dut_prog),
]
return subtarget
async def run(self, device, args):
iface = await device.demultiplexer.claim_interface(self, self.mux_interface, args)
spi_iface = SPIControllerInterface(iface, self.logger)
nrf24lx1_iface = ProgramNRF24Lx1Interface(spi_iface, self.logger, device,
self.__addr_dut_prog, self.__addr_dut_reset)
return nrf24lx1_iface
@classmethod
def add_interact_arguments(cls, parser):
parser.add_argument(
"-d", "--device", metavar="DEVICE", required=True,
choices=("LE1", "LU1p16k", "LU1p32k"),
help="type of device to program (one of: %(choices)s)")
p_operation = parser.add_subparsers(dest="operation", metavar="OPERATION", required=True)
p_read = p_operation.add_parser(
"read", help="read MCU memory contents")
p_read.add_argument(
"file", metavar="HEX-FILE", type=argparse.FileType("wb"),
help="firmware file to write (in Intel HEX format)")
p_program = p_operation.add_parser(
"program", help="program MCU memory contents")
p_program.add_argument(
"file", metavar="HEX-FILE", type=argparse.FileType("rb"),
help="firmware file to read (in Intel HEX format)")
p_program.add_argument(
"--info-page", default=False, action="store_true",
help="erase and program info page, if present in firmware file (DANGEROUS)")
p_erase = p_operation.add_parser(
"erase", help="erase MCU memory contents")
p_erase.add_argument(
"--info-page", metavar="BACKUP-HEX-FILE", type=str,
help="back up, erase, and restore info page, removing read protection (DANGEROUS)")
p_protect_read = p_operation.add_parser(
"protect-read", help="protect MCU memory from reading via SPI")
p_enable_debug = p_operation.add_parser(
"enable-debug", help="enable MCU hardare debugging features")
async def interact(self, device, args, nrf24lx1_iface):
page_size = 512
if args.device == "LE1":
memory_map = _nrf24le1_map
buffer_size = 512
elif args.device == "LU1p32k":
memory_map = _nrf24lu1p_32k_map
buffer_size = 256
elif args.device == "LU1p16k":
memory_map = _nrf24lu1p_16k_map
buffer_size = 256
else:
assert False
try:
await nrf24lx1_iface.reset_program()
async def check_info_page(address):
old_status = await nrf24lx1_iface.read_status()
try:
await nrf24lx1_iface.write_status(FSR_BIT_INFEN)
fuse, = await nrf24lx1_iface.read(address, 1)
return fuse != 0xff
finally:
await nrf24lx1_iface.write_status(old_status)
async def check_read_protected():
if await check_info_page(0x23):
raise ProgramNRF24Lx1Error("MCU is read protected; run `erase --info-page`")
if args.operation == "read":
await check_read_protected()
chunks = []
for memory_area in memory_map:
self.logger.info("reading %s memory", memory_area.name)
if memory_area.spi_addr & 0x10000:
await nrf24lx1_iface.write_status(FSR_BIT_INFEN)
else:
await nrf24lx1_iface.write_status(0)
area_data = await nrf24lx1_iface.read(memory_area.spi_addr & 0xffff,
memory_area.size)
chunks.append((memory_area.mem_addr, area_data))
output_data(args.file, chunks, fmt="ihex")
if args.operation == "program":
await check_read_protected()
area_index = 0
memory_area = memory_map[area_index]
erased_pages = set()
for chunk_mem_addr, chunk_data in sorted(input_data(args.file, fmt="ihex"),
key=lambda c: c[0]):
if len(chunk_data) == 0:
continue
if chunk_mem_addr < memory_area.mem_addr:
raise ProgramNRF24Lx1Error("data outside of memory map at {:#06x}"
.format(chunk_mem_addr))
while chunk_mem_addr >= memory_area.mem_addr + memory_area.size:
area_index += 1
if area_index >= len(memory_area):
raise ProgramNRF24Lx1Error("data outside of memory map at {:#06x}"
.format(chunk_mem_addr))
memory_area = memory_map[area_index]
if chunk_mem_addr + len(chunk_data) > memory_area.mem_addr + memory_area.size:
raise ProgramNRF24Lx1Error("data outside of memory map at {:#06x}"
.format(memory_area.mem_addr + memory_area.size))
if memory_area.spi_addr & 0x10000 and not args.info_page:
self.logger.warn("data provided for info page, but info page programming "
"is not enabled")
continue
chunk_spi_addr = (chunk_mem_addr
- memory_area.mem_addr
+ memory_area.spi_addr) & 0xffff
if memory_area.spi_addr & 0x10000:
level = logging.WARN
await nrf24lx1_iface.write_status(FSR_BIT_INFEN)
else:
level = logging.INFO
await nrf24lx1_iface.write_status(0)
overwrite_pages = set(range(
(chunk_spi_addr // page_size),
(chunk_spi_addr + len(chunk_data) + page_size - 1) // page_size))
need_erase_pages = overwrite_pages - erased_pages
if need_erase_pages:
for page in need_erase_pages:
page_addr = (memory_area.spi_addr & 0x10000) | (page * page_size)
self.logger.log(level, "erasing %s memory at %#06x+%#06x",
memory_area.name, page_addr, page_size)
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.erase_page(page)
await nrf24lx1_iface.wait_status()
erased_pages.update(need_erase_pages)
self.logger.log(level, "programming %s memory at %#06x+%#06x",
memory_area.name, chunk_mem_addr, len(chunk_data))
while len(chunk_data) > 0:
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.program(chunk_spi_addr, chunk_data[:buffer_size])
await nrf24lx1_iface.wait_status()
chunk_data = chunk_data[buffer_size:]
chunk_spi_addr += buffer_size
if args.operation == "erase":
if args.info_page:
await nrf24lx1_iface.write_status(FSR_BIT_INFEN)
info_page = await nrf24lx1_iface.read(0x0000, 0x0100)
self.logger.warn("backing up info page to %s", args.info_page)
if os.path.isfile(args.info_page):
raise ProgramNRF24Lx1Error("info page backup file already exists")
with open(args.info_page, "wb") as f:
output_data(f, [(0x10000, info_page)])
self.logger.warn("erasing code and data memory, and info page")
else:
await check_read_protected()
await nrf24lx1_iface.write_status(0)
self.logger.info("erasing code and data memory")
try:
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.erase_all()
await nrf24lx1_iface.wait_status()
if args.info_page:
self.logger.info("restoring info page DSYS area")
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.program(0, info_page[:32]) # DSYS only
await nrf24lx1_iface.wait_status()
except:
if args.info_page:
self.logger.error("IMPORTANT: programming failed; restore DSYS manually "
"using `program --info-page %s`",
args.info_page)
raise
if args.operation == "protect-read":
if await check_info_page(0x23):
raise ProgramNRF24Lx1Error("memory read protection is already enabled")
self.logger.warn("protecting code and data memory from reads")
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.disable_read()
await nrf24lx1_iface.wait_status()
if args.operation == "enable-debug":
if await check_info_page(0x24):
raise ProgramNRF24Lx1Error("hardware debugging features already enabled")
self.logger.info("enabling hardware debugging features")
await nrf24lx1_iface.write_enable()
await nrf24lx1_iface.enable_debug()
await nrf24lx1_iface.wait_status()
finally:
await nrf24lx1_iface.reset_application()
# -------------------------------------------------------------------------------------------------
class ProgramNRF24Lx1AppletTestCase(GlasgowAppletTestCase, applet=ProgramNRF24Lx1Applet):
@synthesis_test
def test_build(self):
self.assertBuilds()
|
def valida_chutes(palavra):
senha = ''
acertos = []
chute = ''
letras = []
index_letras = 0
verifica_acertos = 0
erros = 0
percorre_palavra = ''
encontrou_letras = False
# continua_jogo = False
dica = input('de uma dica: ')
print(f'a dica é {dica} agora tente descobrir qual é a palavra, então digite uma letra: ')
for percorre_palavra in palavra:
letras.append(percorre_palavra)
acertos.append('N')
while True:
chute = input('digite a letra: ')
index_letras = 0
encontrou_letras = False
for l in letras:
if l == chute:
acertos[index_letras] = 'S'
encontrou_letras = True
index_letras += 1
if not encontrou_letras:
erros +=1
index_letras = 0
senha = ''
for i in acertos:
if i == 'S':
senha += letras[index_letras] + ' '
else:
senha += ' _ '
index_letras += 1
verifica_acertos = 0
for i in acertos:
if i == 'S':
verifica_acertos += 1
else:
verifica_acertos -= 1
jogo_forca(erros, senha, dica)
if ((verifica_acertos == len(acertos)) or (erros == 6)):
break
def tentar_denovo():
continua_jogo = input('Deseja continuar jogando? S/N')
if continua_jogo == 'S' or continua_jogo == 's':
return False
elif continua_jogo == 'N' or continua_jogo == 'n':
return True
else:
print('não entendi oque quis diser, irei para o sistema.')
return True
def jogo_forca(erros, senha, dica):
if erros == 0:
print(f'''
--------|- {dica}
|
|
|
|
|
=============
{senha}
''')
elif erros == 1:
print(f'''
--------|- {dica}
| 0
|
|
|
|
=============
{senha}
''')
elif erros == 2:
print(f'''
--------|- {dica}
| 0
| |
|
|
|
=============
{senha}
''')
elif erros == 3:
print(f'''
--------|- {dica}
| 0
| |\\
|
|
|
=============
{senha}
''')
elif erros == 4:
print(f'''
--------|- {dica}
| 0
| /|\\
|
|
|
=============
{senha}
''')
elif erros == 5:
print(f'''
--------|- {dica}
| 0
| /|\\
| /
|
|
=============
{senha}
''')
else:
print(f'''
--------|- {dica}
| 0
| /|\\
| / \\
|
|
=============
VOCÊ PERDEU
''')
|
from libqtile.config import Key
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
from grayskull.constants import MOD_KEY
key_bindings = [
# Switch between windows
Key([MOD_KEY], "h", lazy.layout.left(), desc="Move focus to left"),
Key([MOD_KEY], "l", lazy.layout.right(), desc="Move focus to right"),
Key([MOD_KEY], "j", lazy.layout.down(), desc="Move focus down"),
Key([MOD_KEY], "k", lazy.layout.up(), desc="Move focus up"),
Key(
[MOD_KEY], "space", lazy.layout.next(), desc="Move window focus to other window"
),
# Move windows between left/right columns or move up/down in current stack.
# Moving out of range in Columns layout will create new column.
Key(
[MOD_KEY, "shift"],
"h",
lazy.layout.shuffle_left(),
desc="Move window to the left",
),
Key(
[MOD_KEY, "shift"],
"l",
lazy.layout.shuffle_right(),
desc="Move window to the right",
),
Key([MOD_KEY, "shift"], "j", lazy.layout.shuffle_down(), desc="Move window down"),
Key([MOD_KEY, "shift"], "k", lazy.layout.shuffle_up(), desc="Move window up"),
# Grow windows. If current window is on the edge of screen and direction
# will be to screen edge - window would shrink.
Key(
[MOD_KEY, "control"],
"h",
lazy.layout.grow_left(),
desc="Grow window to the left",
),
Key(
[MOD_KEY, "control"],
"l",
lazy.layout.grow_right(),
desc="Grow window to the right",
),
Key([MOD_KEY, "control"], "j", lazy.layout.grow_down(), desc="Grow window down"),
Key([MOD_KEY, "control"], "k", lazy.layout.grow_up(), desc="Grow window up"),
Key([MOD_KEY], "n", lazy.layout.normalize(), desc="Reset all window sizes"),
# Toggle between split and unsplit sides of stack.
# Split = all windows displayed
# Unsplit = 1 window displayed, like Max layout, but still with
# multiple stack panes
Key(
[MOD_KEY, "shift"],
"Return",
lazy.layout.toggle_split(),
desc="Toggle between split and unsplit sides of stack",
),
Key([MOD_KEY], "Return", lazy.spawn(guess_terminal()), desc="Launch terminal"),
# Toggle between different layouts as defined below
Key([MOD_KEY], "Tab", lazy.next_layout(), desc="Toggle between layouts"),
Key([MOD_KEY], "w", lazy.window.kill(), desc="Kill focused window"),
Key([MOD_KEY, "control"], "r", lazy.restart(), desc="Restart Qtile"),
Key([MOD_KEY, "control"], "q", lazy.shutdown(), desc="Shutdown Qtile"),
Key([MOD_KEY], "r", lazy.spawncmd(), desc="Spawn a command using a prompt widget"),
# spawn combi rofi menu
Key([MOD_KEY], "slash", lazy.spawn("rofi -show combi"), desc="Show the rofi menu"),
# lock screen
Key([MOD_KEY], "space", lazy.spawn("xsecurelock"), desc="Securely lock the screen"),
# Adjust Brightness
Key(
[],
"XF86MonBrightnessUp",
lazy.spawn("xbacklight -inc 5"),
desc="Increase the monitor brightness",
),
Key(
[],
"XF86MonBrightnessDown",
lazy.spawn("xbacklight -dec 5"),
desc="Decrease the monitor brightness",
),
# Adjust Volume
Key(
[],
"XF86AudioRaiseVolume",
lazy.spawn("amixer set Master unmute"),
lazy.spawn("amixer set Master 5%+"),
desc="Raise Master volume",
),
Key(
[],
"XF86AudioLowerVolume",
lazy.spawn("amixer set Master unmute"),
lazy.spawn("amixer set Master 5%-"),
desc="Decrease Master volume",
),
Key(
[],
"XF86AudioMute",
lazy.spawn("amixer set Master toggle"),
desc="Toggle volume Mute/Unmute",
),
]
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VirtualMachineScaleSetsOperations:
"""VirtualMachineScaleSetsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.compute.v2017_12_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _create_or_update_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
parameters: "_models.VirtualMachineScaleSet",
**kwargs
) -> "_models.VirtualMachineScaleSet":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSet"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'VirtualMachineScaleSet')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
vm_scale_set_name: str,
parameters: "_models.VirtualMachineScaleSet",
**kwargs
) -> AsyncLROPoller["_models.VirtualMachineScaleSet"]:
"""Create or update a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set to create or update.
:type vm_scale_set_name: str
:param parameters: The scale set object.
:type parameters: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSet
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VirtualMachineScaleSet or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSet"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
parameters: "_models.VirtualMachineScaleSetUpdate",
**kwargs
) -> "_models.VirtualMachineScaleSet":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSet"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'VirtualMachineScaleSetUpdate')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def begin_update(
self,
resource_group_name: str,
vm_scale_set_name: str,
parameters: "_models.VirtualMachineScaleSetUpdate",
**kwargs
) -> AsyncLROPoller["_models.VirtualMachineScaleSet"]:
"""Update a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set to create or update.
:type vm_scale_set_name: str
:param parameters: The scale set object.
:type parameters: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetUpdate
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VirtualMachineScaleSet or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSet"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def _delete_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Deletes a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def get(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> "_models.VirtualMachineScaleSet":
"""Display information about a virtual machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VirtualMachineScaleSet, or the result of cls(response)
:rtype: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSet
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSet"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualMachineScaleSet', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}'} # type: ignore
async def _deallocate_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._deallocate_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_deallocate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate'} # type: ignore
async def begin_deallocate(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and
releases the compute resources. You are not billed for the compute resources that this virtual
machine scale set deallocates.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._deallocate_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_deallocate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate'} # type: ignore
async def _delete_instances_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: "_models.VirtualMachineScaleSetVMInstanceRequiredIDs",
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._delete_instances_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceRequiredIDs')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_instances_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete'} # type: ignore
async def begin_delete_instances(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: "_models.VirtualMachineScaleSetVMInstanceRequiredIDs",
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Deletes virtual machines in a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceRequiredIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_instances_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete_instances.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete'} # type: ignore
async def get_instance_view(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> "_models.VirtualMachineScaleSetInstanceView":
"""Gets the status of a VM scale set instance.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VirtualMachineScaleSetInstanceView, or the result of cls(response)
:rtype: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetInstanceView
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSetInstanceView"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
# Construct URL
url = self.get_instance_view.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualMachineScaleSetInstanceView', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_instance_view.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/instanceView'} # type: ignore
def list(
self,
resource_group_name: str,
**kwargs
) -> AsyncIterable["_models.VirtualMachineScaleSetListResult"]:
"""Gets a list of all VM scale sets under a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualMachineScaleSetListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSetListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSetListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets'} # type: ignore
def list_all(
self,
**kwargs
) -> AsyncIterable["_models.VirtualMachineScaleSetListWithLinkResult"]:
"""Gets a list of all VM Scale Sets in the subscription, regardless of the associated resource
group. Use nextLink property in the response to get the next page of VM Scale Sets. Do this
till nextLink is null to fetch all the VM Scale Sets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualMachineScaleSetListWithLinkResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetListWithLinkResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSetListWithLinkResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_all.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSetListWithLinkResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets'} # type: ignore
def list_skus(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> AsyncIterable["_models.VirtualMachineScaleSetListSkusResult"]:
"""Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM
instances allowed for each SKU.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualMachineScaleSetListSkusResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetListSkusResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSetListSkusResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_skus.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSetListSkusResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/skus'} # type: ignore
def get_os_upgrade_history(
self,
resource_group_name: str,
vm_scale_set_name: str,
**kwargs
) -> AsyncIterable["_models.VirtualMachineScaleSetListOSUpgradeHistory"]:
"""Gets list of OS upgrades on a VM scale set instance.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualMachineScaleSetListOSUpgradeHistory or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetListOSUpgradeHistory]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachineScaleSetListOSUpgradeHistory"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_os_upgrade_history.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualMachineScaleSetListOSUpgradeHistory', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
get_os_upgrade_history.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osUpgradeHistory'} # type: ignore
async def _power_off_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._power_off_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_power_off_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff'} # type: ignore
async def begin_power_off(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still
attached and you are getting charged for the resources. Instead, use deallocate to release
resources and avoid charges.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._power_off_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_power_off.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff'} # type: ignore
async def _restart_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._restart_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart'} # type: ignore
async def begin_restart(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Restarts one or more virtual machines in a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._restart_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart'} # type: ignore
async def _start_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._start_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start'} # type: ignore
async def begin_start(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Starts one or more virtual machines in a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._start_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start'} # type: ignore
async def _redeploy_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._redeploy_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_redeploy_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/redeploy'} # type: ignore
async def begin_redeploy(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node,
and powers them back on.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._redeploy_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_redeploy.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/redeploy'} # type: ignore
async def _perform_maintenance_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._perform_maintenance_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_perform_maintenance_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/performMaintenance'} # type: ignore
async def begin_perform_maintenance(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances
which are not eligible for perform maintenance will be failed. Please refer to best practices
for more details: https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-
machine-scale-sets-maintenance-notifications.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._perform_maintenance_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_perform_maintenance.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/performMaintenance'} # type: ignore
async def _update_instances_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: "_models.VirtualMachineScaleSetVMInstanceRequiredIDs",
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._update_instances_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceRequiredIDs')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_instances_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade'} # type: ignore
async def begin_update_instances(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: "_models.VirtualMachineScaleSetVMInstanceRequiredIDs",
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceRequiredIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_instances_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update_instances.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade'} # type: ignore
async def _reimage_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._reimage_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_reimage_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage'} # type: ignore
async def begin_reimage(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Reimages (upgrade the operating system) one or more virtual machines in a VM scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._reimage_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_reimage.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage'} # type: ignore
async def _reimage_all_initial(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> Optional["_models.OperationStatusResponse"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatusResponse"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._reimage_all_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if vm_instance_i_ds is not None:
body_content = self._serialize.body(vm_instance_i_ds, 'VirtualMachineScaleSetVMInstanceIDs')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_reimage_all_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall'} # type: ignore
async def begin_reimage_all(
self,
resource_group_name: str,
vm_scale_set_name: str,
vm_instance_i_ds: Optional["_models.VirtualMachineScaleSetVMInstanceIDs"] = None,
**kwargs
) -> AsyncLROPoller["_models.OperationStatusResponse"]:
"""Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This
operation is only supported for managed disks.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param vm_instance_i_ds: A list of virtual machine instance IDs from the VM scale set.
:type vm_instance_i_ds: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineScaleSetVMInstanceIDs
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: Pass in True if you'd like the AsyncARMPolling polling method,
False for no polling, or your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationStatusResponse or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResponse"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._reimage_all_initial(
resource_group_name=resource_group_name,
vm_scale_set_name=vm_scale_set_name,
vm_instance_i_ds=vm_instance_i_ds,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_reimage_all.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall'} # type: ignore
async def force_recovery_service_fabric_platform_update_domain_walk(
self,
resource_group_name: str,
vm_scale_set_name: str,
platform_update_domain: int,
**kwargs
) -> "_models.RecoveryWalkResponse":
"""Manual platform update domain walk to update virtual machines in a service fabric virtual
machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the VM scale set.
:type vm_scale_set_name: str
:param platform_update_domain: The platform update domain for which a manual recovery walk is
requested.
:type platform_update_domain: int
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RecoveryWalkResponse, or the result of cls(response)
:rtype: ~azure.mgmt.compute.v2017_12_01.models.RecoveryWalkResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoveryWalkResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-12-01"
accept = "application/json"
# Construct URL
url = self.force_recovery_service_fabric_platform_update_domain_walk.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
query_parameters['platformUpdateDomain'] = self._serialize.query("platform_update_domain", platform_update_domain, 'int')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('RecoveryWalkResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
force_recovery_service_fabric_platform_update_domain_walk.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/forceRecoveryServiceFabricPlatformUpdateDomainWalk'} # type: ignore
|
from __future__ import unicode_literals
import django
from django.test import TestCase
from storage.configuration.exceptions import InvalidWorkspaceConfiguration
from storage.configuration.json.workspace_config_1_0 import WorkspaceConfigurationV1
from storage.configuration.json.workspace_config_v6 import WorkspaceConfigurationV6
class TestWorkspaceConfigurationInit(TestCase):
def setUp(self):
django.setup()
def test_bare_min(self):
"""Tests calling WorkspaceConfiguration constructor with bare minimum JSON."""
# No exception is success
config = WorkspaceConfigurationV1({
'broker': {
'type': 'host',
'host_path': '/the/path',
},
}, do_validate=True).get_configuration()
config.validate_broker()
config = WorkspaceConfigurationV6({
'broker': {
'type': 'host',
'host_path': '/the/path',
},
}, do_validate=True).get_configuration()
config.validate_broker()
def test_bad_version(self):
"""Tests calling WorkspaceConfiguration constructor with bad version number."""
config = {
'version': 'BAD VERSION',
'broker': {
'type': 'host',
},
}
self.assertRaises(InvalidWorkspaceConfiguration, WorkspaceConfigurationV1, config)
self.assertRaises(InvalidWorkspaceConfiguration, WorkspaceConfigurationV6, config)
def test_bad_type(self):
"""Tests calling WorkspaceConfiguration constructor with bad broker type."""
config = {
'broker': {
'type': 'BAD',
},
}
self.assertRaises(InvalidWorkspaceConfiguration, WorkspaceConfigurationV1, config, True)
self.assertRaises(InvalidWorkspaceConfiguration, WorkspaceConfigurationV6, config, True)
def test_bad_host_config(self):
"""Tests calling WorkspaceConfiguration constructor with bad host broker configuration."""
config = WorkspaceConfigurationV1({
'broker': {
'type': 'host',
},
}).get_configuration()
self.assertRaises(InvalidWorkspaceConfiguration, config.validate_broker)
config = WorkspaceConfigurationV6({
'broker': {
'type': 'host',
},
}).get_configuration()
self.assertRaises(InvalidWorkspaceConfiguration, config.validate_broker)
def test_successful(self):
"""Tests calling WorkspaceConfiguration constructor successfully with all information."""
# No exception is success
config = WorkspaceConfigurationV1({
'broker': {
'type': 'host',
'host_path': '/host/path',
},
}, do_validate=True).get_configuration()
config.validate_broker()
config = WorkspaceConfigurationV6({
'broker': {
'type': 'host',
'host_path': '/host/path',
},
}, do_validate = True).get_configuration()
config.validate_broker()
|
tinymce.addI18n('nl',{
'Insert a Zotonic media item': 'Plaats een Zotonic mediabestand',
'Insert Zotonic media item': 'Plaats Zotonic mediabestand'
});
|
# Generated by Django 3.2.8 on 2021-12-16 15:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0006_alter_profile_location'),
]
operations = [
migrations.AddField(
model_name='profile',
name='internationalNumber',
field=models.CharField(blank=True, max_length=24),
),
]
|
import api from "@/api";
const getCreditAccounts = context => {
api.getUrl(context, "/api/credit-accounts", "CREDIT_ACCOUNTS_UPDATED");
};
const getCreditAccount = context => {
api.getUrl(context, "/api/credit-account", "CREDIT_ACCOUNT_UPDATED");
};
const createCreditAccount = (context, payload) => {
api.postUrl(
context,
"/api/credit-accounts",
payload,
"CREDIT_ACCOUNT_UPDATED"
);
};
const updateCreditAccount = (context, payload) => {
api.patchUrl(
context,
"/api/credit-accounts/" + payload.id,
payload,
"CREDIT_ACCOUNT_UPDATED"
);
};
const getCreditAccountDebtTypes = context => {
api.getUrl(
context,
"/api/credit-account-types",
"CREDIT_ACCOUNT_DEBT_TYPES_UPDATED"
);
};
const resetCreditAccount = context => {
context.commit("RESET_CREDIT_ACCOUNT");
};
const deleteCreditAccount = (context, payload) => {
api.deleteUrl(
context,
"/api/credit-accounts/" + payload.id,
"CREDIT_ACCOUNT_DELETED"
);
};
const creditPull = async (context, payload) => {
return await api.postUrl(
context,
"/api/credit-pull",
payload,
"CREDIT_ACCOUNTS_UPDATED"
);
};
export default {
getCreditAccounts,
getCreditAccount,
createCreditAccount,
updateCreditAccount,
getCreditAccountDebtTypes,
resetCreditAccount,
deleteCreditAccount,
creditPull
};
|
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModeMap = exports.Mode = exports.TechnicDistanceSensor = void 0;
const device_1 = require("./device");
const Consts = __importStar(require("../consts"));
/**
* @class TechnicDistanceSensor
* @extends Device
*/
class TechnicDistanceSensor extends device_1.Device {
constructor(hub, portId) {
super(hub, portId, exports.ModeMap, Consts.DeviceType.TECHNIC_DISTANCE_SENSOR);
}
receive(message) {
const mode = this._mode;
switch (mode) {
case Mode.DISTANCE:
const distance = message.readUInt16LE(4);
/**
* Emits when the detected distance changes (Slow sampling covers 40mm to 2500mm).
* @event TechnicDistanceSensor#distance
* @type {object}
* @param {number} distance Distance, from 40 to 2500mm
*/
this.notify("distance", { distance });
break;
case Mode.FAST_DISTANCE:
const fastDistance = message.readUInt16LE(4);
/**
* Emits when the detected distance changes (Fast sampling covers 50mm to 320mm).
* @event TechnicDistanceSensor#fastDistance
* @type {object}
* @param {number} fastDistance Distance, from 50 to 320mm
*/
this.notify("fastDistance", { fastDistance });
break;
}
}
/**
* Set the brightness (or turn on/off) of the lights around the eyes.
* @method TechnicDistanceSensor#setBrightness
* @param {number} topLeft Top left quadrant (above left eye). 0-100 brightness.
* @param {number} bottomLeft Bottom left quadrant (below left eye). 0-100 brightness.
* @param {number} topRight Top right quadrant (above right eye). 0-100 brightness.
* @param {number} bottomRight Bottom right quadrant (below right eye). 0-100 brightness.
* @returns {Promise} Resolved upon successful issuance of the command.
*/
setBrightness(topLeft, bottomLeft, topRight, bottomRight) {
this.writeDirect(0x05, Buffer.from([topLeft, topRight, bottomLeft, bottomRight]));
}
}
exports.TechnicDistanceSensor = TechnicDistanceSensor;
var Mode;
(function (Mode) {
Mode[Mode["DISTANCE"] = 0] = "DISTANCE";
Mode[Mode["FAST_DISTANCE"] = 1] = "FAST_DISTANCE";
})(Mode = exports.Mode || (exports.Mode = {}));
exports.ModeMap = {
"distance": Mode.DISTANCE,
"fastDistance": Mode.FAST_DISTANCE
};
//# sourceMappingURL=technicdistancesensor.js.map
|
let CONSTANTS = {
ISLOCALENVIRONMENT: true,
DATABASE: {
URL_LOCAL: 'mongodb://127.0.0.1:27017',
URL_PROD: 'mongodb+srv://motionanalysis:motionanalysis123@cluster0-jcham.mongodb.net/Production',
url: () => { return CONSTANTS.ISLOCALENVIRONMENT? CONSTANTS.DATABASE.URL_LOCAL: CONSTANTS.DATABASE.URL_PROD },
DATABASENAME: () => { return (CONSTANTS.ISLOCALENVIRONMENT? 'MotionAnalysisDB': 'Cluster0') }
}
}
exports.CONSTANTS = CONSTANTS
|
# from torch import nn
# from Models.LSTM import LSTM
# from torchcrf import CRF
#
#
# class BiLSTM_CRF_V2(nn.Module):
# def __init__(self, vocab_size, nb_labels, emb_dim, hidden_dim, bos_idx, eos_idx, pad_idx, num_lstm_layers, device):
# super().__init__()
# self.lstm = LSTM(
# vocab_size, nb_labels, device=device, emb_dim=emb_dim, hidden_dim=hidden_dim, num_layer=num_lstm_layers
# )
# self.crf = CRF(
# nb_labels,
# batch_first=True
# )
#
# def forward(self, x, mask=None):
# emissions = self.lstm(x)
# path = self.crf.decode(emissions, mask=mask.bool())
# return None, path
#
# def loss(self, x, y, mask=None):
# emissions = self.lstm(x)
# nll = -self.crf(emissions, y, mask=mask.bool())
# return nll
|
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "../_reducers";
// export const store = createStore(rootReducer, applyMiddleware(thunk));
// store.dispatch(fetchAllUsers());
export default function configureStore(initialState) {
const finalCreateStore = compose(applyMiddleware(thunk))(createStore);
const store = finalCreateStore(rootReducer, initialState);
return store;
}
|
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'app/comment/index' + location.search,
add_url: 'app/comment/add',
edit_url: 'app/comment/edit',
del_url: 'app/comment/del',
multi_url: 'app/comment/multi',
table: 'app_comment',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
columns: [
[
{checkbox: true},
{field: 'id', title: __('Id')},
{field: 'user_id', title: __('User_id')},
{field: 'article_id', title: __('Article_id')},
{field: 'pid', title: __('Pid')},
{field: 'content', title: __('Content')},
{field: 'like_count', title: __('Like_count')},
{field: 'reply_count', title: __('Reply_count')},
{field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'appuser.nickname', title: __('Appuser.nickname')},
{field: 'appuser.avatar', title: __('Appuser.avatar'), events: Table.api.events.image, formatter: Table.api.formatter.image},
{field: 'apparticle.title', title: __('Apparticle.title')},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
Controller.api.bindevent();
},
edit: function () {
Controller.api.bindevent();
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
}
}
};
return Controller;
});
|
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import { connect, Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import 'react-virtualized/styles.css';
import '@blueprintjs/core/lib/css/blueprint.css';
import '@blueprintjs/icons/lib/css/blueprint-icons.css';
import { history, store } from 'src/reducers';
import Header from 'src/components/Header';
import { backgroundColor } from 'src/style';
import Footer from 'src/components/Footer';
import PageTracker from 'src/components/PageTracker';
import Loading from 'src/components/Loading';
const Home = React.lazy(() => import('src/screens/Home'));
const Leaderboard = React.lazy(() => import('src/screens/Leaderboard'));
const SymbolDetails = React.lazy(() => import('src/screens/SymbolDetails'));
const PopularityChanges = React.lazy(() => import('src/screens/PopularityChanges'));
const DataDownload = React.lazy(() => import('src/screens/DataDownload'));
const ConnectedSwitch = connect(({ router: { location } }) => ({
location,
}))(Switch);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div style={{ height: '100%', backgroundColor }} className="bp3-dark">
<PageTracker />
<Header />
<Suspense fallback={<Loading />}>
<ConnectedSwitch>
<Route exact path="/" component={Home} />
<Route path="/leaderboard" component={Leaderboard} />
<Route path="/symbol/:symbol" component={SymbolDetails} />
<Route path="/popularity_changes" component={PopularityChanges} />
<Route path="/data-download" component={DataDownload} />
</ConnectedSwitch>
</Suspense>
<Footer />
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
|
try:
from baseline.utils import *
from baseline.w2v import *
from baseline.confusion import *
from baseline.data import *
from baseline.reader import *
from baseline.progress import *
from baseline.reporting import *
from baseline.model import *
from baseline.train import *
except ImportError:
pass
from baseline.version import __version__
|
//
// TJY_Nation.h
// TJYFoundation
//
// Created by wang_wei on 2018/5/11.
// Copyright © 2018年 wangwei. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TJY_Nation : NSObject
@property(nonatomic,copy)NSString * Id;
@property(nonatomic,copy)NSString * nation;
@property(nonatomic,copy)NSString*cSpell;
@end
|
import math
import numpy
from dexp.utils import xpArray
from dexp.utils.backends import Backend, NumpyBackend
def yang_deskew(
image: xpArray,
depth_axis: int,
lateral_axis: int,
flip_depth_axis: bool,
dx: float,
dz: float,
angle: float,
camera_orientation: int = 0,
num_split: int = 4,
internal_dtype=None,
):
"""'Yang' Deskewing as done in Yang et al. 2019 ( https://www.biorxiv.org/content/10.1101/2020.09.22.309229v2 )
Parameters
----------
image : input image (skewed 3D stack)
depth_axis : Depth axis.
lateral_axis : Lateral axis.
flip_depth_axis : Flips image to deskew in the opposite orientation (True for view 0 and False for view 1)
dz : float, scanning step (stage or galvo scanning step, not the same as the distance between the slices)
dx : float, pixel size of the camera
angle : float, incident angle of the light sheet, angle between the light sheet and the optical axis in degrees
camera_orientation : Camera orientation correction expressed
as a number of 90 deg rotations to be performed per 2D image in stack.
num_split : number of splits to break down the data into pieces (along y, axis=2) to fit into the memory of GPU
internal_dtype : internal dtype to perform computation
Returns
-------
Deskewed image
"""
# compute dimensionless parameters:
xres = dx * math.cos(angle * math.pi / 180)
resample_factor = int(round(dz / xres))
lateral_scaling = xres / dx
image = yang_deskew_dimensionless(
image=image,
depth_axis=depth_axis,
lateral_axis=lateral_axis,
flip_depth_axis=flip_depth_axis,
resample_factor=resample_factor,
lateral_scaling=lateral_scaling,
camera_orientation=camera_orientation,
num_split=num_split,
internal_dtype=internal_dtype,
)
return image
def yang_deskew_dimensionless(
image: xpArray,
depth_axis: int,
lateral_axis: int,
flip_depth_axis: bool,
resample_factor: int,
lateral_scaling: float,
camera_orientation: int = 0,
num_split: int = 4,
internal_dtype=None,
):
"""'Yang' Deskewing as done in Yang et al. 2019 ( https://www.biorxiv.org/content/10.1101/2020.09.22.309229v2 )
Parameters
----------
image : input image (skewed 3D stack)
depth_axis : Depth axis.
lateral_axis : Lateral axis.
flip_depth_axis : Flips image to deskew in the opposite orientation (True for view 0 and False for view 1)
resample_factor : Resampling factor
lateral_scaling : Lateral scaling
camera_orientation : Camera orientation correction expressed as a
number of 90 deg rotations to be performed per 2D image in stack.
num_split : number of splits to break down the data into pieces (along y, axis=2) to fit into the memory of GPU
internal_dtype : internal dtype to perform computation
Returns
-------
Deskewed image
"""
# we don't want to move the image to the backend just now,
# as it might be a very large image and we can actually defer moving it to the backend as
# after splitting...
xp = Backend.get_xp_module(image)
# We save the original dtype:
original_dtype = image.dtype
# Default internal dtype is the same as the input image:
if internal_dtype is None:
internal_dtype = image.dtype
# Numpy backend does not support float16:
if type(Backend.current()) is NumpyBackend and internal_dtype == xp.float16:
internal_dtype = xp.float32
# First we compute the permutation that will reorder the axis so that the depth and
# lateral axis are the first axis in the image:
permutation = (depth_axis, lateral_axis) + tuple(
axis for axis in range(image.ndim) if axis not in [depth_axis, lateral_axis]
)
permutation = numpy.asarray(permutation)
inverse_permutation = numpy.argsort(permutation)
# We apply the permutation:
image = xp.transpose(image, axes=permutation)
if flip_depth_axis:
image = xp.flip(image, axis=0)
# rotate the data
# Note: the weird 1+co mod 4 is due to the fact that Bin's original
# code was implemented for a different orientation...
image = xp.rot90(image, k=(1 + camera_orientation) % 4, axes=(1, 2))
# deskew and rotate
image = _resampling_vertical_split(
image,
resample_factor=resample_factor,
lateral_scaling=lateral_scaling,
num_split=num_split,
internal_dtype=internal_dtype,
)
# flip along axis x
if flip_depth_axis:
xp = Backend.get_xp_module(image)
# _resampling_vertical_split transposes axis 0 with axis 2, so we flip along 2:
image = xp.flip(image, axis=2)
# We apply the inverse permutation:
image = xp.transpose(image, axes=inverse_permutation)
# Cast back to original dtype:
image = image.astype(original_dtype, copy=False)
return image
def _resampling_vertical_split(
image, resample_factor: int, lateral_scaling: float, num_split: int = 4, internal_dtype=None
):
"""Same as resampling_vertical but splits the input image so that computation can fit in GPU memory.
Parameters
----------
image : input image (skewed 3D stack)
resample_factor : Resampling factor
lateral_scaling : Lateral scaling
internal_dtype : internal dtype to perform computation
Returns
-------
Resampled image.
Important note: for scalability reasons, the returned image is always numpy image.
"""
if num_split == 1:
output = _resampling_vertical(
image, resample_factor=resample_factor, lateral_scaling=lateral_scaling, internal_dtype=internal_dtype
)
else:
xp = Backend.get_xp_module(image)
data_gpu_splits = xp.array_split(image, num_split, axis=1)
data_cpu_splits = []
for k in range(num_split):
data_resampled = _resampling_vertical(
data_gpu_splits[k],
resample_factor=resample_factor,
lateral_scaling=lateral_scaling,
internal_dtype=internal_dtype,
)
data_cpu_splits.append(Backend.to_numpy(data_resampled, dtype=image.dtype))
output = numpy.concatenate(data_cpu_splits, axis=1)
return output
def _resampling_vertical(image, resample_factor: int, lateral_scaling: float, internal_dtype=None):
"""Resampling of the image by interpolation along vertical direction.
Here we assume the dz is integer multiple of dx * cos(angle * pi / 180),
one can also pre-interpolate the data within along the z' axis if this is not the case
Parameters
----------
image : input image (skewed 3D stack)
resample_factor : Resampling factor
lateral_scaling : Lateral scaling
internal_dtype : internal dtype to perform computation
Returns
-------
Resampled image
"""
xp = Backend.get_xp_module()
sp = Backend.get_sp_module()
# Move images to backend.
image = Backend.to_backend(image, dtype=internal_dtype)
(nz, ny, nx) = image.shape
dtype = image.dtype
nz_new, ny_new, nx_new = len(range(0, nx, resample_factor)), ny, nx + nz * resample_factor
data_reassign = xp.zeros((nz_new, ny_new, nx_new), internal_dtype)
for x in range(nx):
x_start = x
x_end = nz * resample_factor + x
data_reassign[x // resample_factor, :, x_start:x_end:resample_factor] = image[:, :, x].T
del image
# rescale the data, interpolate along z
data_rescale = sp.ndimage.zoom(data_reassign, zoom=(resample_factor, 1, 1), order=1)
del data_reassign
data_interp = xp.zeros((nz_new, ny_new, nx_new), dtype)
for z in range(nz_new):
for k in range(resample_factor):
data_interp[z, :, k::resample_factor] = data_rescale[z * resample_factor - k, :, k::resample_factor]
del data_rescale
# rescale the data, to have voxel the same along x an y;
# remove the first z slice which has artifacts due to resampling
image_final = sp.ndimage.zoom(data_interp[1:], zoom=(1, 1, lateral_scaling), order=1)
return image_final
|
import csv
import boto3
from evaluation_function import evalutate_quantitative
DATA = "E:/workspace/bank-data-challenge/data/small_set.csv"
DYNAMO_TABLE = "ConsumerComplaints"
def main():
print("Starting")
dynamo_client = boto3.client("dynamodb")
with open(DATA, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=",")
for row in reader:
print(row)
dynamo_row = {}
for key, val in row.items():
if val:
dynamo_row[key] = {"S": val}
# print(key, ":", val)
dynamo_client.put_item(TableName=DYNAMO_TABLE, Item=dynamo_row)
if __name__ == "__main__":
main()
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_COMPONENTBOUNDSCONSTRAINER_H_INCLUDED
#define JUCE_COMPONENTBOUNDSCONSTRAINER_H_INCLUDED
//==============================================================================
/**
A class that imposes restrictions on a Component's size or position.
This is used by classes such as ResizableCornerComponent,
ResizableBorderComponent and ResizableWindow.
The base class can impose some basic size and position limits, but you can
also subclass this for custom uses.
@see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
*/
class JUCE_API ComponentBoundsConstrainer
{
public:
//==============================================================================
/** When first created, the object will not impose any restrictions on the components. */
ComponentBoundsConstrainer() noexcept;
/** Destructor. */
virtual ~ComponentBoundsConstrainer();
//==============================================================================
/** Imposes a minimum width limit. */
void setMinimumWidth (int minimumWidth) noexcept;
/** Returns the current minimum width. */
int getMinimumWidth() const noexcept { return minW; }
/** Imposes a maximum width limit. */
void setMaximumWidth (int maximumWidth) noexcept;
/** Returns the current maximum width. */
int getMaximumWidth() const noexcept { return maxW; }
/** Imposes a minimum height limit. */
void setMinimumHeight (int minimumHeight) noexcept;
/** Returns the current minimum height. */
int getMinimumHeight() const noexcept { return minH; }
/** Imposes a maximum height limit. */
void setMaximumHeight (int maximumHeight) noexcept;
/** Returns the current maximum height. */
int getMaximumHeight() const noexcept { return maxH; }
/** Imposes a minimum width and height limit. */
void setMinimumSize (int minimumWidth,
int minimumHeight) noexcept;
/** Imposes a maximum width and height limit. */
void setMaximumSize (int maximumWidth,
int maximumHeight) noexcept;
/** Set all the maximum and minimum dimensions. */
void setSizeLimits (int minimumWidth,
int minimumHeight,
int maximumWidth,
int maximumHeight) noexcept;
//==============================================================================
/** Sets the amount by which the component is allowed to go off-screen.
The values indicate how many pixels must remain on-screen when dragged off
one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
when the component goes off the top of the screen, its y-position will be
clipped so that there are always at least 10 pixels on-screen. In other words,
the lowest y-position it can take would be (10 - the component's height).
If you pass 0 or less for one of these amounts, the component is allowed
to move beyond that edge completely, with no restrictions at all.
If you pass a very large number (i.e. larger that the dimensions of the
component itself), then the component won't be allowed to overlap that
edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
the component will bump into the left side of the screen and go no further.
*/
void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
int minimumWhenOffTheLeft,
int minimumWhenOffTheBottom,
int minimumWhenOffTheRight) noexcept;
/** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
/** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
/** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
/** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
//==============================================================================
/** Specifies a width-to-height ratio that the resizer should always maintain.
If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
will always be maintained as this multiple of the height.
@see setResizeLimits
*/
void setFixedAspectRatio (double widthOverHeight) noexcept;
/** Returns the aspect ratio that was set with setFixedAspectRatio().
If no aspect ratio is being enforced, this will return 0.
*/
double getFixedAspectRatio() const noexcept;
//==============================================================================
/** This callback changes the given coordinates to impose whatever the current
constraints are set to be.
@param bounds the target position that should be examined and adjusted
@param previousBounds the component's current size
@param limits the region in which the component can be positioned
@param isStretchingTop whether the top edge of the component is being resized
@param isStretchingLeft whether the left edge of the component is being resized
@param isStretchingBottom whether the bottom edge of the component is being resized
@param isStretchingRight whether the right edge of the component is being resized
*/
virtual void checkBounds (Rectangle<int>& bounds,
const Rectangle<int>& previousBounds,
const Rectangle<int>& limits,
bool isStretchingTop,
bool isStretchingLeft,
bool isStretchingBottom,
bool isStretchingRight);
/** This callback happens when the resizer is about to start dragging. */
virtual void resizeStart();
/** This callback happens when the resizer has finished dragging. */
virtual void resizeEnd();
/** Checks the given bounds, and then sets the component to the corrected size. */
void setBoundsForComponent (Component* component,
const Rectangle<int>& bounds,
bool isStretchingTop,
bool isStretchingLeft,
bool isStretchingBottom,
bool isStretchingRight);
/** Performs a check on the current size of a component, and moves or resizes
it if it fails the constraints.
*/
void checkComponentBounds (Component* component);
/** Called by setBoundsForComponent() to apply a new constrained size to a
component.
By default this just calls setBounds(), but is virtual in case it's needed for
extremely cunning purposes.
*/
virtual void applyBoundsToComponent (Component* component,
const Rectangle<int>& bounds);
private:
//==============================================================================
int minW, maxW, minH, maxH;
int minOffTop, minOffLeft, minOffBottom, minOffRight;
double aspectRatio;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer)
};
#endif // JUCE_COMPONENTBOUNDSCONSTRAINER_H_INCLUDED
|
var stats = {
type: "GROUP",
name: "Global Information",
path: "",
pathFormatted: "group_missing-name-b06d1",
stats: {
"name": "Global Information",
"numberOfRequests": {
"total": "10",
"ok": "10",
"ko": "0"
},
"minResponseTime": {
"total": "22",
"ok": "22",
"ko": "-"
},
"maxResponseTime": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"meanResponseTime": {
"total": "258",
"ok": "258",
"ko": "-"
},
"standardDeviation": {
"total": "651",
"ok": "651",
"ko": "-"
},
"percentiles1": {
"total": "34",
"ok": "34",
"ko": "-"
},
"percentiles2": {
"total": "42",
"ok": "42",
"ko": "-"
},
"percentiles3": {
"total": "1266",
"ok": "1266",
"ko": "-"
},
"percentiles4": {
"total": "2021",
"ok": "2021",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 9,
"percentage": 90
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 1,
"percentage": 10
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "2",
"ok": "2",
"ko": "-"
}
},
contents: {
"req_create-registry-9455b": {
type: "REQUEST",
name: "Create registry instance",
path: "Create registry instance",
pathFormatted: "req_create-registry-9455b",
stats: {
"name": "Create registry instance",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"maxResponseTime": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"meanResponseTime": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"percentiles2": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"percentiles3": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"percentiles4": {
"total": "2210",
"ok": "2210",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 0,
"percentage": 0
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 1,
"percentage": 100
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_check-instance--969e3": {
type: "REQUEST",
name: "Check instance status",
path: "Check instance status",
pathFormatted: "req_check-instance--969e3",
stats: {
"name": "Check instance status",
"numberOfRequests": {
"total": "2",
"ok": "2",
"ko": "0"
},
"minResponseTime": {
"total": "28",
"ok": "28",
"ko": "-"
},
"maxResponseTime": {
"total": "36",
"ok": "36",
"ko": "-"
},
"meanResponseTime": {
"total": "32",
"ok": "32",
"ko": "-"
},
"standardDeviation": {
"total": "4",
"ok": "4",
"ko": "-"
},
"percentiles1": {
"total": "32",
"ok": "32",
"ko": "-"
},
"percentiles2": {
"total": "34",
"ok": "34",
"ko": "-"
},
"percentiles3": {
"total": "36",
"ok": "36",
"ko": "-"
},
"percentiles4": {
"total": "36",
"ok": "36",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 2,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.4",
"ok": "0.4",
"ko": "-"
}
}
},"req_get-instance-ur-a10da": {
type: "REQUEST",
name: "Get instance url",
path: "Get instance url",
pathFormatted: "req_get-instance-ur-a10da",
stats: {
"name": "Get instance url",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "27",
"ok": "27",
"ko": "-"
},
"maxResponseTime": {
"total": "27",
"ok": "27",
"ko": "-"
},
"meanResponseTime": {
"total": "27",
"ok": "27",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "27",
"ok": "27",
"ko": "-"
},
"percentiles2": {
"total": "27",
"ok": "27",
"ko": "-"
},
"percentiles3": {
"total": "27",
"ok": "27",
"ko": "-"
},
"percentiles4": {
"total": "27",
"ok": "27",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_get-developer-p-78700": {
type: "REQUEST",
name: "Get Developer principalId",
path: "Get Developer principalId",
pathFormatted: "req_get-developer-p-78700",
stats: {
"name": "Get Developer principalId",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "113",
"ok": "113",
"ko": "-"
},
"maxResponseTime": {
"total": "113",
"ok": "113",
"ko": "-"
},
"meanResponseTime": {
"total": "113",
"ok": "113",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "113",
"ok": "113",
"ko": "-"
},
"percentiles2": {
"total": "113",
"ok": "113",
"ko": "-"
},
"percentiles3": {
"total": "113",
"ok": "113",
"ko": "-"
},
"percentiles4": {
"total": "113",
"ok": "113",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_grant-access-to-d887f": {
type: "REQUEST",
name: "Grant access to Developer principalId",
path: "Grant access to Developer principalId",
pathFormatted: "req_grant-access-to-d887f",
stats: {
"name": "Grant access to Developer principalId",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "22",
"ok": "22",
"ko": "-"
},
"maxResponseTime": {
"total": "22",
"ok": "22",
"ko": "-"
},
"meanResponseTime": {
"total": "22",
"ok": "22",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "22",
"ok": "22",
"ko": "-"
},
"percentiles2": {
"total": "22",
"ok": "22",
"ko": "-"
},
"percentiles3": {
"total": "22",
"ok": "22",
"ko": "-"
},
"percentiles4": {
"total": "22",
"ok": "22",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_create-artifact-d711b": {
type: "REQUEST",
name: "Create artifact",
path: "Create artifact",
pathFormatted: "req_create-artifact-d711b",
stats: {
"name": "Create artifact",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "39",
"ok": "39",
"ko": "-"
},
"maxResponseTime": {
"total": "39",
"ok": "39",
"ko": "-"
},
"meanResponseTime": {
"total": "39",
"ok": "39",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "39",
"ok": "39",
"ko": "-"
},
"percentiles2": {
"total": "39",
"ok": "39",
"ko": "-"
},
"percentiles3": {
"total": "39",
"ok": "39",
"ko": "-"
},
"percentiles4": {
"total": "39",
"ok": "39",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_search-artifact-e819f": {
type: "REQUEST",
name: "Search artifacts",
path: "Search artifacts",
pathFormatted: "req_search-artifact-e819f",
stats: {
"name": "Search artifacts",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "31",
"ok": "31",
"ko": "-"
},
"maxResponseTime": {
"total": "31",
"ok": "31",
"ko": "-"
},
"meanResponseTime": {
"total": "31",
"ok": "31",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "31",
"ok": "31",
"ko": "-"
},
"percentiles2": {
"total": "31",
"ok": "31",
"ko": "-"
},
"percentiles3": {
"total": "31",
"ok": "31",
"ko": "-"
},
"percentiles4": {
"total": "31",
"ok": "31",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_get-artifact-by-916aa": {
type: "REQUEST",
name: "Get artifact by ID",
path: "Get artifact by ID",
pathFormatted: "req_get-artifact-by-916aa",
stats: {
"name": "Get artifact by ID",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "26",
"ok": "26",
"ko": "-"
},
"maxResponseTime": {
"total": "26",
"ok": "26",
"ko": "-"
},
"meanResponseTime": {
"total": "26",
"ok": "26",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "26",
"ok": "26",
"ko": "-"
},
"percentiles2": {
"total": "26",
"ok": "26",
"ko": "-"
},
"percentiles3": {
"total": "26",
"ok": "26",
"ko": "-"
},
"percentiles4": {
"total": "26",
"ok": "26",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
},"req_delete-registry-2fda3": {
type: "REQUEST",
name: "Delete registry instance",
path: "Delete registry instance",
pathFormatted: "req_delete-registry-2fda3",
stats: {
"name": "Delete registry instance",
"numberOfRequests": {
"total": "1",
"ok": "1",
"ko": "0"
},
"minResponseTime": {
"total": "43",
"ok": "43",
"ko": "-"
},
"maxResponseTime": {
"total": "43",
"ok": "43",
"ko": "-"
},
"meanResponseTime": {
"total": "43",
"ok": "43",
"ko": "-"
},
"standardDeviation": {
"total": "0",
"ok": "0",
"ko": "-"
},
"percentiles1": {
"total": "43",
"ok": "43",
"ko": "-"
},
"percentiles2": {
"total": "43",
"ok": "43",
"ko": "-"
},
"percentiles3": {
"total": "43",
"ok": "43",
"ko": "-"
},
"percentiles4": {
"total": "43",
"ok": "43",
"ko": "-"
},
"group1": {
"name": "t < 800 ms",
"count": 1,
"percentage": 100
},
"group2": {
"name": "800 ms < t < 1200 ms",
"count": 0,
"percentage": 0
},
"group3": {
"name": "t > 1200 ms",
"count": 0,
"percentage": 0
},
"group4": {
"name": "failed",
"count": 0,
"percentage": 0
},
"meanNumberOfRequestsPerSecond": {
"total": "0.2",
"ok": "0.2",
"ko": "-"
}
}
}
}
}
function fillStats(stat){
$("#numberOfRequests").append(stat.numberOfRequests.total);
$("#numberOfRequestsOK").append(stat.numberOfRequests.ok);
$("#numberOfRequestsKO").append(stat.numberOfRequests.ko);
$("#minResponseTime").append(stat.minResponseTime.total);
$("#minResponseTimeOK").append(stat.minResponseTime.ok);
$("#minResponseTimeKO").append(stat.minResponseTime.ko);
$("#maxResponseTime").append(stat.maxResponseTime.total);
$("#maxResponseTimeOK").append(stat.maxResponseTime.ok);
$("#maxResponseTimeKO").append(stat.maxResponseTime.ko);
$("#meanResponseTime").append(stat.meanResponseTime.total);
$("#meanResponseTimeOK").append(stat.meanResponseTime.ok);
$("#meanResponseTimeKO").append(stat.meanResponseTime.ko);
$("#standardDeviation").append(stat.standardDeviation.total);
$("#standardDeviationOK").append(stat.standardDeviation.ok);
$("#standardDeviationKO").append(stat.standardDeviation.ko);
$("#percentiles1").append(stat.percentiles1.total);
$("#percentiles1OK").append(stat.percentiles1.ok);
$("#percentiles1KO").append(stat.percentiles1.ko);
$("#percentiles2").append(stat.percentiles2.total);
$("#percentiles2OK").append(stat.percentiles2.ok);
$("#percentiles2KO").append(stat.percentiles2.ko);
$("#percentiles3").append(stat.percentiles3.total);
$("#percentiles3OK").append(stat.percentiles3.ok);
$("#percentiles3KO").append(stat.percentiles3.ko);
$("#percentiles4").append(stat.percentiles4.total);
$("#percentiles4OK").append(stat.percentiles4.ok);
$("#percentiles4KO").append(stat.percentiles4.ko);
$("#meanNumberOfRequestsPerSecond").append(stat.meanNumberOfRequestsPerSecond.total);
$("#meanNumberOfRequestsPerSecondOK").append(stat.meanNumberOfRequestsPerSecond.ok);
$("#meanNumberOfRequestsPerSecondKO").append(stat.meanNumberOfRequestsPerSecond.ko);
}
|
import axios from 'axios';
const config = {
app: {
title: process.env.APP_TITLE || ' | Umana Admin',
environment: process.env.ENVIRONMENT || 'development',
api_url: process.env.API_URL || 'http://localhost:3026/api/v1',
},
};
export default config;
|
class Solution:
def XXX(self, num: int) -> str:
ans = ""
dic = {(0,1):"I",(0,5):"V",(1,1):"X",(1,5):"L",(2,1):"C",(2,5):"D",(3,1):"M"}
for i in range(4):
left = num % 10
num = num // 10
if left==0:
continue
elif left<=3:
ans = dic[(i,1)]*left + ans
elif left==4:
ans = dic[(i,1)] + dic[(i,5)] + ans
elif left<9:
ans = dic[(i,5)] + (left-5)*dic[(i,1)] + ans
else:
ans = dic[(i,1)] + dic[(i+1,1)] + ans
if num == 0:
return ans
|
import berries from './berries.json';
import contests from './contests.json';
import encounters from './encounters.json';
import evolution from './evolution.json';
import games from './games.json';
import items from './items.json';
import locations from './locations.json';
import machines from './machines.json';
import moves from './moves.json';
import pokemon from './pokemon.json';
import resourceLists from './resource-lists.json';
import utility from './utility.json';
export default [
{
name: 'Resource Lists/Pagination',
resources: resourceLists,
description:
"Calling any API endpoint without a resource ID or name will return a paginated list of available resources for that API. By default, a list \"page\" will contain up to 20 resources. If you would like to change this just add a 'limit' query parameter to the GET request, e.g. `?limit=60`. You can use 'offset' to move to the next page, e.g. `?limit=60&offset=60`.",
endOfSection: true,
},
{name: 'Berries', resources: berries},
{name: 'Contests', resources: contests},
{name: 'Encounters', resources: encounters},
{name: 'Evolution', resources: evolution},
{name: 'Games', resources: games},
{name: 'Items', resources: items},
{name: 'Locations', resources: locations},
{name: 'Machines', resources: machines},
{name: 'Moves', resources: moves},
{name: 'Pokémon', resources: pokemon, endOfSection: true},
{name: 'Utility', resources: utility},
];
|
from collections import OrderedDict
import copy
import os
from dash.development.base_component import _explicitize_args
from dash.exceptions import NonExistentEventException
from ._all_keywords import python_keywords
from .base_component import Component
# pylint: disable=unused-argument
def generate_class_string(typename, props, description, namespace):
"""Dynamically generate class strings to have nicely formatted docstrings,
keyword arguments, and repr.
Inspired by http://jameso.be/2013/08/06/namedtuple.html
Parameters
----------
typename
props
description
namespace
Returns
-------
string
"""
# TODO _prop_names, _type, _namespace, and available_properties
# can be modified by a Dash JS developer via setattr
# TODO - Tab out the repr for the repr of these components to make it
# look more like a hierarchical tree
# TODO - Include "description" "defaultValue" in the repr and docstring
#
# TODO - Handle "required"
#
# TODO - How to handle user-given `null` values? I want to include
# an expanded docstring like Dropdown(value=None, id=None)
# but by templating in those None values, I have no way of knowing
# whether a property is None because the user explicitly wanted
# it to be `null` or whether that was just the default value.
# The solution might be to deal with default values better although
# not all component authors will supply those.
c = '''class {typename}(Component):
"""{docstring}"""
@_explicitize_args
def __init__(self, {default_argtext}):
self._prop_names = {list_of_valid_keys}
self._type = '{typename}'
self._namespace = '{namespace}'
self._valid_wildcard_attributes =\
{list_of_valid_wildcard_attr_prefixes}
self.available_properties = {list_of_valid_keys}
self.available_wildcard_properties =\
{list_of_valid_wildcard_attr_prefixes}
_explicit_args = kwargs.pop('_explicit_args')
_locals = locals()
_locals.update(kwargs) # For wildcard attrs
args = {{k: _locals[k] for k in _explicit_args if k != 'children'}}
for k in {required_props}:
if k not in args:
raise TypeError(
'Required argument `' + k + '` was not specified.')
super({typename}, self).__init__({argtext})
'''
filtered_props = reorder_props(filter_props(props))
wildcard_prefixes = repr(parse_wildcards(props))
list_of_valid_keys = repr(list(map(str, filtered_props.keys())))
docstring = create_docstring(
component_name=typename, props=filtered_props, description=description
).replace("\r\n", "\n")
prohibit_events(props)
# pylint: disable=unused-variable
prop_keys = list(props.keys())
if "children" in props:
prop_keys.remove("children")
default_argtext = "children=None, "
argtext = "children=children, **args"
else:
default_argtext = ""
argtext = "**args"
default_argtext += ", ".join(
[
(
"{:s}=Component.REQUIRED".format(p)
if props[p]["required"]
else "{:s}=Component.UNDEFINED".format(p)
)
for p in prop_keys
if not p.endswith("-*") and p not in python_keywords and p != "setProps"
]
+ ["**kwargs"]
)
required_args = required_props(props)
return c.format(
typename=typename,
namespace=namespace,
filtered_props=filtered_props,
list_of_valid_wildcard_attr_prefixes=wildcard_prefixes,
list_of_valid_keys=list_of_valid_keys,
docstring=docstring,
default_argtext=default_argtext,
argtext=argtext,
required_props=required_args,
)
def generate_class_file(typename, props, description, namespace):
"""Generate a python class file (.py) given a class string.
Parameters
----------
typename
props
description
namespace
Returns
-------
"""
import_string = (
"# AUTO GENERATED FILE - DO NOT EDIT\n\n"
+ "from dash.development.base_component import "
+ "Component, _explicitize_args\n\n\n"
)
class_string = generate_class_string(typename, props, description, namespace)
file_name = "{:s}.py".format(typename)
file_path = os.path.join(namespace, file_name)
with open(file_path, "w") as f:
f.write(import_string)
f.write(class_string)
print("Generated {}".format(file_name))
def generate_imports(project_shortname, components):
with open(os.path.join(project_shortname, "_imports_.py"), "w") as f:
imports_string = "{}\n\n{}".format(
"\n".join("from .{0} import {0}".format(x) for x in components),
"__all__ = [\n{}\n]".format(
",\n".join(' "{}"'.format(x) for x in components)
),
)
f.write(imports_string)
def generate_classes_files(project_shortname, metadata, *component_generators):
components = []
for component_path, component_data in metadata.items():
component_name = component_path.split("/")[-1].split(".")[0]
components.append(component_name)
for generator in component_generators:
generator(
component_name,
component_data["props"],
component_data["description"],
project_shortname,
)
return components
def generate_class(typename, props, description, namespace):
"""Generate a python class object given a class string.
Parameters
----------
typename
props
description
namespace
Returns
-------
"""
string = generate_class_string(typename, props, description, namespace)
scope = {"Component": Component, "_explicitize_args": _explicitize_args}
# pylint: disable=exec-used
exec(string, scope)
result = scope[typename]
return result
def required_props(props):
"""Pull names of required props from the props object.
Parameters
----------
props: dict
Returns
-------
list
List of prop names (str) that are required for the Component
"""
return [prop_name for prop_name, prop in list(props.items()) if prop["required"]]
def create_docstring(component_name, props, description):
"""Create the Dash component docstring.
Parameters
----------
component_name: str
Component name
props: dict
Dictionary with {propName: propMetadata} structure
description: str
Component description
Returns
-------
str
Dash component docstring
"""
# Ensure props are ordered with children first
props = reorder_props(props=props)
return (
"""A{n} {name} component.\n{description}
Keyword arguments:\n{args}"""
).format(
n="n" if component_name[0].lower() in ["a", "e", "i", "o", "u"] else "",
name=component_name,
description=description,
args="\n".join(
create_prop_docstring(
prop_name=p,
type_object=prop["type"] if "type" in prop else prop["flowType"],
required=prop["required"],
description=prop["description"],
default=prop.get("defaultValue"),
indent_num=0,
is_flow_type="flowType" in prop and "type" not in prop,
)
for p, prop in list(filter_props(props).items())
),
)
def prohibit_events(props):
"""Events have been removed. Raise an error if we see dashEvents or
fireEvents.
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Raises
-------
?
"""
if "dashEvents" in props or "fireEvents" in props:
raise NonExistentEventException(
"Events are no longer supported by dash. Use properties instead, "
"eg `n_clicks` instead of a `click` event."
)
def parse_wildcards(props):
"""Pull out the wildcard attributes from the Component props.
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
list
List of Dash valid wildcard prefixes
"""
list_of_valid_wildcard_attr_prefixes = []
for wildcard_attr in ["data-*", "aria-*"]:
if wildcard_attr in props:
list_of_valid_wildcard_attr_prefixes.append(wildcard_attr[:-1])
return list_of_valid_wildcard_attr_prefixes
def reorder_props(props):
"""If "children" is in props, then move it to the front to respect dash
convention.
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
dict
Dictionary with {propName: propMetadata} structure
"""
if "children" in props:
# Constructing an OrderedDict with duplicate keys, you get the order
# from the first one but the value from the last.
# Doing this to avoid mutating props, which can cause confusion.
props = OrderedDict([("children", "")] + list(props.items()))
return props
def filter_props(props):
"""Filter props from the Component arguments to exclude:
- Those without a "type" or a "flowType" field
- Those with arg.type.name in {'func', 'symbol', 'instanceOf'}
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
dict
Filtered dictionary with {propName: propMetadata} structure
Examples
--------
```python
prop_args = {
'prop1': {
'type': {'name': 'bool'},
'required': False,
'description': 'A description',
'flowType': {},
'defaultValue': {'value': 'false', 'computed': False},
},
'prop2': {'description': 'A prop without a type'},
'prop3': {
'type': {'name': 'func'},
'description': 'A function prop',
},
}
# filtered_prop_args is now
# {
# 'prop1': {
# 'type': {'name': 'bool'},
# 'required': False,
# 'description': 'A description',
# 'flowType': {},
# 'defaultValue': {'value': 'false', 'computed': False},
# },
# }
filtered_prop_args = filter_props(prop_args)
```
"""
filtered_props = copy.deepcopy(props)
for arg_name, arg in list(filtered_props.items()):
if "type" not in arg and "flowType" not in arg:
filtered_props.pop(arg_name)
continue
# Filter out functions and instances --
# these cannot be passed from Python
if "type" in arg: # These come from PropTypes
arg_type = arg["type"]["name"]
if arg_type in {"func", "symbol", "instanceOf"}:
filtered_props.pop(arg_name)
elif "flowType" in arg: # These come from Flow & handled differently
arg_type_name = arg["flowType"]["name"]
if arg_type_name == "signature":
# This does the same as the PropTypes filter above, but "func"
# is under "type" if "name" is "signature" vs just in "name"
if "type" not in arg["flowType"] or arg["flowType"]["type"] != "object":
filtered_props.pop(arg_name)
else:
raise ValueError
return filtered_props
# pylint: disable=too-many-arguments
def create_prop_docstring(
prop_name,
type_object,
required,
description,
default,
indent_num,
is_flow_type=False,
):
"""Create the Dash component prop docstring.
Parameters
----------
prop_name: str
Name of the Dash component prop
type_object: dict
react-docgen-generated prop type dictionary
required: bool
Component is required?
description: str
Dash component description
default: dict
Either None if a default value is not defined, or
dict containing the key 'value' that defines a
default value for the prop
indent_num: int
Number of indents to use for the context block
(creates 2 spaces for every indent)
is_flow_type: bool
Does the prop use Flow types? Otherwise, uses PropTypes
Returns
-------
str
Dash component prop docstring
"""
py_type_name = js_to_py_type(
type_object=type_object, is_flow_type=is_flow_type, indent_num=indent_num + 1
)
indent_spacing = " " * indent_num
if default is None:
default = ""
else:
default = default["value"]
if default in ["true", "false"]:
default = default.title()
is_required = "optional"
if required:
is_required = "required"
elif default and default not in ["null", "{}", "[]"]:
is_required = "default {}".format(default.replace("\n", "\n" + indent_spacing))
if "\n" in py_type_name:
return (
"{indent_spacing}- {name} (dict; {is_required}): "
"{description}{period}"
"{name} has the following type: {type}".format(
indent_spacing=indent_spacing,
name=prop_name,
type=py_type_name,
description=description.strip().strip("."),
period=". " if description else "",
is_required=is_required,
)
)
return "{indent_spacing}- {name} ({type}{is_required}){description}".format(
indent_spacing=indent_spacing,
name=prop_name,
type="{}; ".format(py_type_name) if py_type_name else "",
description=(": {}".format(description) if description != "" else ""),
is_required=is_required,
)
def map_js_to_py_types_prop_types(type_object):
"""Mapping from the PropTypes js type object to the Python type."""
def shape_or_exact():
return "dict containing keys {}.\n{}".format(
", ".join("'{}'".format(t) for t in list(type_object["value"].keys())),
"Those keys have the following types:\n{}".format(
"\n".join(
create_prop_docstring(
prop_name=prop_name,
type_object=prop,
required=prop["required"],
description=prop.get("description", ""),
default=prop.get("defaultValue"),
indent_num=1,
)
for prop_name, prop in list(type_object["value"].items())
)
),
)
return dict(
array=lambda: "list",
bool=lambda: "boolean",
number=lambda: "number",
string=lambda: "string",
object=lambda: "dict",
any=lambda: "boolean | number | string | dict | list",
element=lambda: "dash component",
node=lambda: "a list of or a singular dash component, string or number",
# React's PropTypes.oneOf
enum=lambda: "a value equal to: {}".format(
", ".join("{}".format(str(t["value"])) for t in type_object["value"])
),
# React's PropTypes.oneOfType
union=lambda: "{}".format(
" | ".join(
"{}".format(js_to_py_type(subType))
for subType in type_object["value"]
if js_to_py_type(subType) != ""
)
),
# React's PropTypes.arrayOf
arrayOf=lambda: (
"list"
+ (
" of {}".format(
js_to_py_type(type_object["value"]) + "s"
if js_to_py_type(type_object["value"]).split(" ")[0] != "dict"
else js_to_py_type(type_object["value"]).replace("dict", "dicts", 1)
)
if js_to_py_type(type_object["value"]) != ""
else ""
)
),
# React's PropTypes.objectOf
objectOf=lambda: "dict with strings as keys and values of type {}".format(
js_to_py_type(type_object["value"])
),
# React's PropTypes.shape
shape=shape_or_exact,
# React's PropTypes.exact
exact=shape_or_exact,
)
def map_js_to_py_types_flow_types(type_object):
"""Mapping from the Flow js types to the Python type."""
return dict(
array=lambda: "list",
boolean=lambda: "boolean",
number=lambda: "number",
string=lambda: "string",
Object=lambda: "dict",
any=lambda: "bool | number | str | dict | list",
Element=lambda: "dash component",
Node=lambda: "a list of or a singular dash component, string or number",
# React's PropTypes.oneOfType
union=lambda: "{}".format(
" | ".join(
"{}".format(js_to_py_type(subType))
for subType in type_object["elements"]
if js_to_py_type(subType) != ""
)
),
# Flow's Array type
Array=lambda: "list{}".format(
" of {}s".format(js_to_py_type(type_object["elements"][0]))
if js_to_py_type(type_object["elements"][0]) != ""
else ""
),
# React's PropTypes.shape
signature=lambda indent_num: "dict containing keys {}.\n{}".format(
", ".join(
"'{}'".format(d["key"]) for d in type_object["signature"]["properties"]
),
"{}Those keys have the following types:\n{}".format(
" " * indent_num,
"\n".join(
create_prop_docstring(
prop_name=prop["key"],
type_object=prop["value"],
required=prop["value"]["required"],
description=prop["value"].get("description", ""),
default=prop.get("defaultValue"),
indent_num=indent_num,
is_flow_type=True,
)
for prop in type_object["signature"]["properties"]
),
),
),
)
def js_to_py_type(type_object, is_flow_type=False, indent_num=0):
"""Convert JS types to Python types for the component definition.
Parameters
----------
type_object: dict
react-docgen-generated prop type dictionary
is_flow_type: bool
Does the prop use Flow types? Otherwise, uses PropTypes
indent_num: int
Number of indents to use for the docstring for the prop
Returns
-------
str
Python type string
"""
js_type_name = type_object["name"]
js_to_py_types = (
map_js_to_py_types_flow_types(type_object=type_object)
if is_flow_type
else map_js_to_py_types_prop_types(type_object=type_object)
)
if (
"computed" in type_object
and type_object["computed"]
or type_object.get("type", "") == "function"
):
return ""
if js_type_name in js_to_py_types:
if js_type_name == "signature": # This is a Flow object w/ signature
return js_to_py_types[js_type_name](indent_num)
# All other types
return js_to_py_types[js_type_name]()
return ""
|
// Validates various CSS property values
var Splitter = require('../utils/splitter');
var widthKeywords = ['thin', 'thick', 'medium', 'inherit', 'initial'];
var allUnits = ['px', '%', 'em', 'in', 'cm', 'mm', 'ex', 'pt', 'pc', 'ch', 'rem', 'vh', 'vm', 'vmin', 'vmax', 'vw'];
var cssUnitRegexStr = '(\\-?\\.?\\d+\\.?\\d*(' + allUnits.join('|') + '|)|auto|inherit)';
var cssCalcRegexStr = '(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)';
var cssFunctionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(([A-Z]|[0-9]|\\ |\\,|\\#|\\+|\\-|\\%|\\.|\\(|\\))*\\)';
var cssFunctionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(([A-Z]|[0-9]|\\ |\\,|\\#|\\+|\\-|\\%|\\.|\\(|\\))*\\)';
var cssVariableRegexStr = 'var\\(\\-\\-[^\\)]+\\)';
var cssFunctionAnyRegexStr = '(' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')';
var cssUnitOrCalcRegexStr = '(' + cssUnitRegexStr + '|' + cssCalcRegexStr + ')';
var cssUnitAnyRegexStr = '(none|' + widthKeywords.join('|') + '|' + cssUnitRegexStr + '|' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')';
var cssFunctionNoVendorRegex = new RegExp('^' + cssFunctionNoVendorRegexStr + '$', 'i');
var cssFunctionVendorRegex = new RegExp('^' + cssFunctionVendorRegexStr + '$', 'i');
var cssVariableRegex = new RegExp('^' + cssVariableRegexStr + '$', 'i');
var cssFunctionAnyRegex = new RegExp('^' + cssFunctionAnyRegexStr + '$', 'i');
var cssUnitRegex = new RegExp('^' + cssUnitRegexStr + '$', 'i');
var cssUnitOrCalcRegex = new RegExp('^' + cssUnitOrCalcRegexStr + '$', 'i');
var cssUnitAnyRegex = new RegExp('^' + cssUnitAnyRegexStr + '$', 'i');
var backgroundRepeatKeywords = ['repeat', 'no-repeat', 'repeat-x', 'repeat-y', 'inherit'];
var backgroundAttachmentKeywords = ['inherit', 'scroll', 'fixed', 'local'];
var backgroundPositionKeywords = ['center', 'top', 'bottom', 'left', 'right'];
var backgroundSizeKeywords = ['contain', 'cover'];
var backgroundBoxKeywords = ['border-box', 'content-box', 'padding-box'];
var styleKeywords = ['auto', 'inherit', 'hidden', 'none', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset'];
var listStyleTypeKeywords = ['armenian', 'circle', 'cjk-ideographic', 'decimal', 'decimal-leading-zero', 'disc', 'georgian', 'hebrew', 'hiragana', 'hiragana-iroha', 'inherit', 'katakana', 'katakana-iroha', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'none', 'square', 'upper-alpha', 'upper-latin', 'upper-roman'];
var listStylePositionKeywords = ['inside', 'outside', 'inherit'];
function Validator(compatibility) {
var validUnits = allUnits.slice(0).filter(function (value) {
return !(value in compatibility.units) || compatibility.units[value] === true;
});
var compatibleCssUnitRegexStr = '(\\-?\\.?\\d+\\.?\\d*(' + validUnits.join('|') + '|)|auto|inherit)';
this.compatibleCssUnitRegex = new RegExp('^' + compatibleCssUnitRegexStr + '$', 'i');
this.compatibleCssUnitAnyRegex = new RegExp('^(none|' + widthKeywords.join('|') + '|' + compatibleCssUnitRegexStr + '|' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')$', 'i');
}
Validator.prototype.isValidHexColor = function (s) {
return (s.length === 4 || s.length === 7) && s[0] === '#';
};
Validator.prototype.isValidRgbaColor = function (s) {
s = s.split(' ').join('');
return s.length > 0 && s.indexOf('rgba(') === 0 && s.indexOf(')') === s.length - 1;
};
Validator.prototype.isValidHslaColor = function (s) {
s = s.split(' ').join('');
return s.length > 0 && s.indexOf('hsla(') === 0 && s.indexOf(')') === s.length - 1;
};
Validator.prototype.isValidNamedColor = function (s) {
// We don't really check if it's a valid color value, but allow any letters in it
return s !== 'auto' && (s === 'transparent' || s === 'inherit' || /^[a-zA-Z]+$/.test(s));
};
Validator.prototype.isValidVariable = function (s) {
return cssVariableRegex.test(s);
};
Validator.prototype.isValidColor = function (s) {
return this.isValidNamedColor(s) ||
this.isValidHexColor(s) ||
this.isValidRgbaColor(s) ||
this.isValidHslaColor(s) ||
this.isValidVariable(s) ||
this.isValidVendorPrefixedValue(s);
};
Validator.prototype.isValidUrl = function (s) {
// NOTE: at this point all URLs are replaced with placeholders by clean-css, so we check for those placeholders
return s.indexOf('__ESCAPED_URL_CLEAN_CSS') === 0;
};
Validator.prototype.isValidUnit = function (s) {
return cssUnitAnyRegex.test(s);
};
Validator.prototype.isValidUnitWithoutFunction = function (s) {
return cssUnitRegex.test(s);
};
Validator.prototype.isValidAndCompatibleUnit = function (s) {
return this.compatibleCssUnitAnyRegex.test(s);
};
Validator.prototype.isValidAndCompatibleUnitWithoutFunction = function (s) {
return this.compatibleCssUnitRegex.test(s);
};
Validator.prototype.isValidFunctionWithoutVendorPrefix = function (s) {
return cssFunctionNoVendorRegex.test(s);
};
Validator.prototype.isValidFunctionWithVendorPrefix = function (s) {
return cssFunctionVendorRegex.test(s);
};
Validator.prototype.isValidFunction = function (s) {
return cssFunctionAnyRegex.test(s);
};
Validator.prototype.isValidBackgroundRepeat = function (s) {
return backgroundRepeatKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidBackgroundAttachment = function (s) {
return backgroundAttachmentKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidBackgroundBox = function (s) {
return backgroundBoxKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidBackgroundPositionPart = function (s) {
return backgroundPositionKeywords.indexOf(s) >= 0 || cssUnitOrCalcRegex.test(s) || this.isValidVariable(s);
};
Validator.prototype.isValidBackgroundPosition = function (s) {
if (s === 'inherit')
return true;
var parts = s.split(' ');
for (var i = 0, l = parts.length; i < l; i++) {
if (parts[i] === '')
continue;
if (this.isValidBackgroundPositionPart(parts[i]) || this.isValidVariable(parts[i]))
continue;
return false;
}
return true;
};
Validator.prototype.isValidBackgroundSizePart = function (s) {
return backgroundSizeKeywords.indexOf(s) >= 0 || cssUnitRegex.test(s) || this.isValidVariable(s);
};
Validator.prototype.isValidBackgroundPositionAndSize = function (s) {
if (s.indexOf('/') < 0)
return false;
var twoParts = new Splitter('/').split(s);
return this.isValidBackgroundSizePart(twoParts.pop()) && this.isValidBackgroundPositionPart(twoParts.pop());
};
Validator.prototype.isValidListStyleType = function (s) {
return listStyleTypeKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidListStylePosition = function (s) {
return listStylePositionKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidStyle = function (s) {
return styleKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidWidth = function (s) {
return this.isValidUnit(s) || widthKeywords.indexOf(s) >= 0 || this.isValidVariable(s);
};
Validator.prototype.isValidVendorPrefixedValue = function (s) {
return /^-([A-Za-z0-9]|-)*$/gi.test(s);
};
Validator.prototype.areSameFunction = function (a, b) {
if (!this.isValidFunction(a) || !this.isValidFunction(b))
return false;
var f1name = a.substring(0, a.indexOf('('));
var f2name = b.substring(0, b.indexOf('('));
return f1name === f2name;
};
module.exports = Validator;
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.file_search_result
class FileSearchResults(object):
"""Implementation of the 'FileSearchResults' model.
Specifies an array of found files and folders. In addition, a count is
provided to indicate if additional requests must be made to get
the full result.
Attributes:
files (list of FileSearchResult): Array of Files and Folders.
Specifies the list of files and folders returned by this request
that match the specified search and filter criteria. The number of
files returned is limited by the pageCount field.
total_count (long|int): Specifies the total number of files and
folders that match the filter and search criteria. Use this value
to determine how many additional requests are required to get the
full result.
"""
# Create a mapping from Model property names to API property names
_names = {
"files":'files',
"total_count":'totalCount'
}
def __init__(self,
files=None,
total_count=None):
"""Constructor for the FileSearchResults class"""
# Initialize members of the class
self.files = files
self.total_count = total_count
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
files = None
if dictionary.get('files') != None:
files = list()
for structure in dictionary.get('files'):
files.append(cohesity_management_sdk.models.file_search_result.FileSearchResult.from_dictionary(structure))
total_count = dictionary.get('totalCount')
# Return an object of this model
return cls(files,
total_count)
|
namaPembeli = str(input("nama pembeli: "))
nomorHP = int(input("nomor handphone: "))
kodeJurusan = str(input("Kode Jurusan: "))
jumlahTiket = int(input("Jumlah Tiket: "))
if(kodeJurusan == "SBY" or kodeJurusan == "sby"):
harga_tiket = "300000"
total_harga = harga_tiket * jumlahTiket
if(jumlahTiket >= 3):
diskon = 0.1 * total_harga
else:
total_harga = 0
total_bayar = total_harga - diskon
print("Nama : " , namaPembeli)
print("Nomor HP : " , nomorHP)
print("Kode jurusan : " , kodeJurusan)
print("Harga : " , total_bayar)
print("Potongan : ", diskon)
print("Total : " , total_harga)
|