text
stringlengths
3
1.05M
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ define(function(require, exports, module) { ! function(a, b) { "object" == typeof module && "object" == typeof module.exports ? module.exports = a.document ? b(a, !0) : function(a) { if (!a.document) throw new Error("jQuery requires a window with a document"); return b(a) } : b(a) }("undefined" != typeof window ? window : this, function(a, b) { var c = [], d = c.slice, e = c.concat, f = c.push, g = c.indexOf, h = {}, i = h.toString, j = h.hasOwnProperty, k = "".trim, l = {}, m = "1.11.0", n = function(a, b) { return new n.fn.init(a, b) }, o = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, p = /^-ms-/, q = /-([\da-z])/gi, r = function(a, b) { return b.toUpperCase() }; n.fn = n.prototype = { jquery: m, constructor: n, selector: "", length: 0, toArray: function() { return d.call(this) }, get: function(a) { return null != a ? 0 > a ? this[a + this.length] : this[a] : d.call(this) }, pushStack: function(a) { var b = n.merge(this.constructor(), a); return b.prevObject = this, b.context = this.context, b }, each: function(a, b) { return n.each(this, a, b) }, map: function(a) { return this.pushStack(n.map(this, function(b, c) { return a.call(b, c, b) })) }, slice: function() { return this.pushStack(d.apply(this, arguments)) }, first: function() { return this.eq(0) }, last: function() { return this.eq(-1) }, eq: function(a) { var b = this.length, c = +a + (0 > a ? b : 0); return this.pushStack(c >= 0 && b > c ? [this[c]] : []) }, end: function() { return this.prevObject || this.constructor(null) }, push: f, sort: c.sort, splice: c.splice }, n.extend = n.fn.extend = function() { var a, b, c, d, e, f, g = arguments[0] || {}, h = 1, i = arguments.length, j = !1; for ("boolean" == typeof g && (j = g, g = arguments[h] || {}, h++), "object" == typeof g || n.isFunction(g) || (g = {}), h === i && (g = this, h--); i > h; h++) if (null != (e = arguments[h])) for (d in e) a = g[d], c = e[d], g !== c && (j && c && (n.isPlainObject(c) || (b = n.isArray(c))) ? (b ? (b = !1, f = a && n.isArray(a) ? a : []) : f = a && n.isPlainObject(a) ? a : {}, g[d] = n.extend(j, f, c)) : void 0 !== c && (g[d] = c)); return g }, n.extend({ expando: "jQuery" + (m + Math.random()).replace(/\D/g, ""), isReady: !0, error: function(a) { throw new Error(a) }, noop: function() {}, isFunction: function(a) { return "function" === n.type(a) }, isArray: Array.isArray || function(a) { return "array" === n.type(a) }, isWindow: function(a) { return null != a && a == a.window }, isNumeric: function(a) { return a - parseFloat(a) >= 0 }, isEmptyObject: function(a) { var b; for (b in a) return !1; return !0 }, isPlainObject: function(a) { var b; if (!a || "object" !== n.type(a) || a.nodeType || n.isWindow(a)) return !1; try { if (a.constructor && !j.call(a, "constructor") && !j.call(a.constructor.prototype, "isPrototypeOf")) return !1 } catch (c) { return !1 } if (l.ownLast) for (b in a) return j.call(a, b); for (b in a); return void 0 === b || j.call(a, b) }, type: function(a) { return null == a ? a + "" : "object" == typeof a || "function" == typeof a ? h[i.call(a)] || "object" : typeof a }, globalEval: function(b) { b && n.trim(b) && (a.execScript || function(b) { a.eval.call(a, b) })(b) }, camelCase: function(a) { return a.replace(p, "ms-").replace(q, r) }, nodeName: function(a, b) { return a.nodeName && a.nodeName.toLowerCase() === b.toLowerCase() }, each: function(a, b, c) { var d, e = 0, f = a.length, g = s(a); if (c) { if (g) { for (; f > e; e++) if (d = b.apply(a[e], c), d === !1) break } else for (e in a) if (d = b.apply(a[e], c), d === !1) break } else if (g) { for (; f > e; e++) if (d = b.call(a[e], e, a[e]), d === !1) break } else for (e in a) if (d = b.call(a[e], e, a[e]), d === !1) break; return a }, trim: k && !k.call("\ufeff\xa0") ? function(a) { return null == a ? "" : k.call(a) } : function(a) { return null == a ? "" : (a + "").replace(o, "") }, makeArray: function(a, b) { var c = b || []; return null != a && (s(Object(a)) ? n.merge(c, "string" == typeof a ? [a] : a) : f.call(c, a)), c }, inArray: function(a, b, c) { var d; if (b) { if (g) return g.call(b, a, c); for (d = b.length, c = c ? 0 > c ? Math.max(0, d + c) : c : 0; d > c; c++) if (c in b && b[c] === a) return c } return -1 }, merge: function(a, b) { var c = +b.length, d = 0, e = a.length; while (c > d) a[e++] = b[d++]; if (c !== c) while (void 0 !== b[d]) a[e++] = b[d++]; return a.length = e, a }, grep: function(a, b, c) { for (var d, e = [], f = 0, g = a.length, h = !c; g > f; f++) d = !b(a[f], f), d !== h && e.push(a[f]); return e }, map: function(a, b, c) { var d, f = 0, g = a.length, h = s(a), i = []; if (h) for (; g > f; f++) d = b(a[f], f, c), null != d && i.push(d); else for (f in a) d = b(a[f], f, c), null != d && i.push(d); return e.apply([], i) }, guid: 1, proxy: function(a, b) { var c, e, f; return "string" == typeof b && (f = a[b], b = a, a = f), n.isFunction(a) ? (c = d.call(arguments, 2), e = function() { return a.apply(b || this, c.concat(d.call(arguments))) }, e.guid = a.guid = a.guid || n.guid++, e) : void 0 }, now: function() { return +new Date }, support: l }), n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(a, b) { h["[object " + b + "]"] = b.toLowerCase() }); function s(a) { var b = a.length, c = n.type(a); return "function" === c || n.isWindow(a) ? !1 : 1 === a.nodeType && b ? !0 : "array" === c || 0 === b || "number" == typeof b && b > 0 && b - 1 in a } var t = function(a) { var b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s = "sizzle" + -new Date, t = a.document, u = 0, v = 0, w = eb(), x = eb(), y = eb(), z = function(a, b) { return a === b && (j = !0), 0 }, A = "undefined", B = 1 << 31, C = {}.hasOwnProperty, D = [], E = D.pop, F = D.push, G = D.push, H = D.slice, I = D.indexOf || function(a) { for (var b = 0, c = this.length; c > b; b++) if (this[b] === a) return b; return -1 }, J = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", K = "[\\x20\\t\\r\\n\\f]", L = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", M = L.replace("w", "w#"), N = "\\[" + K + "*(" + L + ")" + K + "*(?:([*^$|!~]?=)" + K + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + M + ")|)|)" + K + "*\\]", O = ":(" + L + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + N.replace(3, 8) + ")*)|.*)\\)|)", P = new RegExp("^" + K + "+|((?:^|[^\\\\])(?:\\\\.)*)" + K + "+$", "g"), Q = new RegExp("^" + K + "*," + K + "*"), R = new RegExp("^" + K + "*([>+~]|" + K + ")" + K + "*"), S = new RegExp("=" + K + "*([^\\]'\"]*?)" + K + "*\\]", "g"), T = new RegExp(O), U = new RegExp("^" + M + "$"), V = { ID: new RegExp("^#(" + L + ")"), CLASS: new RegExp("^\\.(" + L + ")"), TAG: new RegExp("^(" + L.replace("w", "w*") + ")"), ATTR: new RegExp("^" + N), PSEUDO: new RegExp("^" + O), CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + K + "*(even|odd|(([+-]|)(\\d*)n|)" + K + "*(?:([+-]|)" + K + "*(\\d+)|))" + K + "*\\)|)", "i"), bool: new RegExp("^(?:" + J + ")$", "i"), needsContext: new RegExp("^" + K + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + K + "*((?:-\\d)?\\d*)" + K + "*\\)|)(?=[^-]|$)", "i") }, W = /^(?:input|select|textarea|button)$/i, X = /^h\d$/i, Y = /^[^{]+\{\s*\[native \w/, Z = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, $ = /[+~]/, _ = /'|\\/g, ab = new RegExp("\\\\([\\da-f]{1,6}" + K + "?|(" + K + ")|.)", "ig"), bb = function(a, b, c) { var d = "0x" + b - 65536; return d !== d || c ? b : 0 > d ? String.fromCharCode(d + 65536) : String.fromCharCode(d >> 10 | 55296, 1023 & d | 56320) }; try { G.apply(D = H.call(t.childNodes), t.childNodes), D[t.childNodes.length].nodeType } catch (cb) { G = { apply: D.length ? function(a, b) { F.apply(a, H.call(b)) } : function(a, b) { var c = a.length, d = 0; while (a[c++] = b[d++]); a.length = c - 1 } } } function db(a, b, d, e) { var f, g, h, i, j, m, p, q, u, v; if ((b ? b.ownerDocument || b : t) !== l && k(b), b = b || l, d = d || [], !a || "string" != typeof a) return d; if (1 !== (i = b.nodeType) && 9 !== i) return []; if (n && !e) { if (f = Z.exec(a)) if (h = f[1]) { if (9 === i) { if (g = b.getElementById(h), !g || !g.parentNode) return d; if (g.id === h) return d.push(g), d } else if (b.ownerDocument && (g = b.ownerDocument.getElementById(h)) && r(b, g) && g.id === h) return d.push(g), d } else { if (f[2]) return G.apply(d, b.getElementsByTagName(a)), d; if ((h = f[3]) && c.getElementsByClassName && b.getElementsByClassName) return G.apply(d, b.getElementsByClassName(h)), d } if (c.qsa && (!o || !o.test(a))) { if (q = p = s, u = b, v = 9 === i && a, 1 === i && "object" !== b.nodeName.toLowerCase()) { m = ob(a), (p = b.getAttribute("id")) ? q = p.replace(_, "\\$&") : b.setAttribute("id", q), q = "[id='" + q + "'] ", j = m.length; while (j--) m[j] = q + pb(m[j]); u = $.test(a) && mb(b.parentNode) || b, v = m.join(",") } if (v) try { return G.apply(d, u.querySelectorAll(v)), d } catch (w) {} finally { p || b.removeAttribute("id") } } } return xb(a.replace(P, "$1"), b, d, e) } function eb() { var a = []; function b(c, e) { return a.push(c + " ") > d.cacheLength && delete b[a.shift()], b[c + " "] = e } return b } function fb(a) { return a[s] = !0, a } function gb(a) { var b = l.createElement("div"); try { return !!a(b) } catch (c) { return !1 } finally { b.parentNode && b.parentNode.removeChild(b), b = null } } function hb(a, b) { var c = a.split("|"), e = a.length; while (e--) d.attrHandle[c[e]] = b } function ib(a, b) { var c = b && a, d = c && 1 === a.nodeType && 1 === b.nodeType && (~b.sourceIndex || B) - (~a.sourceIndex || B); if (d) return d; if (c) while (c = c.nextSibling) if (c === b) return -1; return a ? 1 : -1 } function jb(a) { return function(b) { var c = b.nodeName.toLowerCase(); return "input" === c && b.type === a } } function kb(a) { return function(b) { var c = b.nodeName.toLowerCase(); return ("input" === c || "button" === c) && b.type === a } } function lb(a) { return fb(function(b) { return b = +b, fb(function(c, d) { var e, f = a([], c.length, b), g = f.length; while (g--) c[e = f[g]] && (c[e] = !(d[e] = c[e])) }) }) } function mb(a) { return a && typeof a.getElementsByTagName !== A && a } c = db.support = {}, f = db.isXML = function(a) { var b = a && (a.ownerDocument || a).documentElement; return b ? "HTML" !== b.nodeName : !1 }, k = db.setDocument = function(a) { var b, e = a ? a.ownerDocument || a : t, g = e.defaultView; return e !== l && 9 === e.nodeType && e.documentElement ? (l = e, m = e.documentElement, n = !f(e), g && g !== g.top && (g.addEventListener ? g.addEventListener("unload", function() { k() }, !1) : g.attachEvent && g.attachEvent("onunload", function() { k() })), c.attributes = gb(function(a) { return a.className = "i", !a.getAttribute("className") }), c.getElementsByTagName = gb(function(a) { return a.appendChild(e.createComment("")), !a.getElementsByTagName("*").length }), c.getElementsByClassName = Y.test(e.getElementsByClassName) && gb(function(a) { return a.innerHTML = "<div class='a'></div><div class='a i'></div>", a.firstChild.className = "i", 2 === a.getElementsByClassName("i").length }), c.getById = gb(function(a) { return m.appendChild(a).id = s, !e.getElementsByName || !e.getElementsByName(s).length }), c.getById ? (d.find.ID = function(a, b) { if (typeof b.getElementById !== A && n) { var c = b.getElementById(a); return c && c.parentNode ? [c] : [] } }, d.filter.ID = function(a) { var b = a.replace(ab, bb); return function(a) { return a.getAttribute("id") === b } }) : (delete d.find.ID, d.filter.ID = function(a) { var b = a.replace(ab, bb); return function(a) { var c = typeof a.getAttributeNode !== A && a.getAttributeNode("id"); return c && c.value === b } }), d.find.TAG = c.getElementsByTagName ? function(a, b) { return typeof b.getElementsByTagName !== A ? b.getElementsByTagName(a) : void 0 } : function(a, b) { var c, d = [], e = 0, f = b.getElementsByTagName(a); if ("*" === a) { while (c = f[e++]) 1 === c.nodeType && d.push(c); return d } return f }, d.find.CLASS = c.getElementsByClassName && function(a, b) { return typeof b.getElementsByClassName !== A && n ? b.getElementsByClassName(a) : void 0 }, p = [], o = [], (c.qsa = Y.test(e.querySelectorAll)) && (gb(function(a) { a.innerHTML = "<select t=''><option selected=''></option></select>", a.querySelectorAll("[t^='']").length && o.push("[*^$]=" + K + "*(?:''|\"\")"), a.querySelectorAll("[selected]").length || o.push("\\[" + K + "*(?:value|" + J + ")"), a.querySelectorAll(":checked").length || o.push(":checked") }), gb(function(a) { var b = e.createElement("input"); b.setAttribute("type", "hidden"), a.appendChild(b).setAttribute("name", "D"), a.querySelectorAll("[name=d]").length && o.push("name" + K + "*[*^$|!~]?="), a.querySelectorAll(":enabled").length || o.push(":enabled", ":disabled"), a.querySelectorAll("*,:x"), o.push(",.*:") })), (c.matchesSelector = Y.test(q = m.webkitMatchesSelector || m.mozMatchesSelector || m.oMatchesSelector || m.msMatchesSelector)) && gb(function(a) { c.disconnectedMatch = q.call(a, "div"), q.call(a, "[s!='']:x"), p.push("!=", O) }), o = o.length && new RegExp(o.join("|")), p = p.length && new RegExp(p.join("|")), b = Y.test(m.compareDocumentPosition), r = b || Y.test(m.contains) ? function(a, b) { var c = 9 === a.nodeType ? a.documentElement : a, d = b && b.parentNode; return a === d || !(!d || 1 !== d.nodeType || !(c.contains ? c.contains(d) : a.compareDocumentPosition && 16 & a.compareDocumentPosition(d))) } : function(a, b) { if (b) while (b = b.parentNode) if (b === a) return !0; return !1 }, z = b ? function(a, b) { if (a === b) return j = !0, 0; var d = !a.compareDocumentPosition - !b.compareDocumentPosition; return d ? d : (d = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1, 1 & d || !c.sortDetached && b.compareDocumentPosition(a) === d ? a === e || a.ownerDocument === t && r(t, a) ? -1 : b === e || b.ownerDocument === t && r(t, b) ? 1 : i ? I.call(i, a) - I.call(i, b) : 0 : 4 & d ? -1 : 1) } : function(a, b) { if (a === b) return j = !0, 0; var c, d = 0, f = a.parentNode, g = b.parentNode, h = [a], k = [b]; if (!f || !g) return a === e ? -1 : b === e ? 1 : f ? -1 : g ? 1 : i ? I.call(i, a) - I.call(i, b) : 0; if (f === g) return ib(a, b); c = a; while (c = c.parentNode) h.unshift(c); c = b; while (c = c.parentNode) k.unshift(c); while (h[d] === k[d]) d++; return d ? ib(h[d], k[d]) : h[d] === t ? -1 : k[d] === t ? 1 : 0 }, e) : l }, db.matches = function(a, b) { return db(a, null, null, b) }, db.matchesSelector = function(a, b) { if ((a.ownerDocument || a) !== l && k(a), b = b.replace(S, "='$1']"), !(!c.matchesSelector || !n || p && p.test(b) || o && o.test(b))) try { var d = q.call(a, b); if (d || c.disconnectedMatch || a.document && 11 !== a.document.nodeType) return d } catch (e) {} return db(b, l, null, [a]).length > 0 }, db.contains = function(a, b) { return (a.ownerDocument || a) !== l && k(a), r(a, b) }, db.attr = function(a, b) { (a.ownerDocument || a) !== l && k(a); var e = d.attrHandle[b.toLowerCase()], f = e && C.call(d.attrHandle, b.toLowerCase()) ? e(a, b, !n) : void 0; return void 0 !== f ? f : c.attributes || !n ? a.getAttribute(b) : (f = a.getAttributeNode(b)) && f.specified ? f.value : null }, db.error = function(a) { throw new Error("Syntax error, unrecognized expression: " + a) }, db.uniqueSort = function(a) { var b, d = [], e = 0, f = 0; if (j = !c.detectDuplicates, i = !c.sortStable && a.slice(0), a.sort(z), j) { while (b = a[f++]) b === a[f] && (e = d.push(f)); while (e--) a.splice(d[e], 1) } return i = null, a }, e = db.getText = function(a) { var b, c = "", d = 0, f = a.nodeType; if (f) { if (1 === f || 9 === f || 11 === f) { if ("string" == typeof a.textContent) return a.textContent; for (a = a.firstChild; a; a = a.nextSibling) c += e(a) } else if (3 === f || 4 === f) return a.nodeValue } else while (b = a[d++]) c += e(b); return c }, d = db.selectors = { cacheLength: 50, createPseudo: fb, match: V, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: !0 }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: !0 }, "~": { dir: "previousSibling" } }, preFilter: { ATTR: function(a) { return a[1] = a[1].replace(ab, bb), a[3] = (a[4] || a[5] || "").replace(ab, bb), "~=" === a[2] && (a[3] = " " + a[3] + " "), a.slice(0, 4) }, CHILD: function(a) { return a[1] = a[1].toLowerCase(), "nth" === a[1].slice(0, 3) ? (a[3] || db.error(a[0]), a[4] = +(a[4] ? a[5] + (a[6] || 1) : 2 * ("even" === a[3] || "odd" === a[3])), a[5] = +(a[7] + a[8] || "odd" === a[3])) : a[3] && db.error(a[0]), a }, PSEUDO: function(a) { var b, c = !a[5] && a[2]; return V.CHILD.test(a[0]) ? null : (a[3] && void 0 !== a[4] ? a[2] = a[4] : c && T.test(c) && (b = ob(c, !0)) && (b = c.indexOf(")", c.length - b) - c.length) && (a[0] = a[0].slice(0, b), a[2] = c.slice(0, b)), a.slice(0, 3)) } }, filter: { TAG: function(a) { var b = a.replace(ab, bb).toLowerCase(); return "*" === a ? function() { return !0 } : function(a) { return a.nodeName && a.nodeName.toLowerCase() === b } }, CLASS: function(a) { var b = w[a + " "]; return b || (b = new RegExp("(^|" + K + ")" + a + "(" + K + "|$)")) && w(a, function(a) { return b.test("string" == typeof a.className && a.className || typeof a.getAttribute !== A && a.getAttribute("class") || "") }) }, ATTR: function(a, b, c) { return function(d) { var e = db.attr(d, a); return null == e ? "!=" === b : b ? (e += "", "=" === b ? e === c : "!=" === b ? e !== c : "^=" === b ? c && 0 === e.indexOf(c) : "*=" === b ? c && e.indexOf(c) > -1 : "$=" === b ? c && e.slice(-c.length) === c : "~=" === b ? (" " + e + " ").indexOf(c) > -1 : "|=" === b ? e === c || e.slice(0, c.length + 1) === c + "-" : !1) : !0 } }, CHILD: function(a, b, c, d, e) { var f = "nth" !== a.slice(0, 3), g = "last" !== a.slice(-4), h = "of-type" === b; return 1 === d && 0 === e ? function(a) { return !!a.parentNode } : function(b, c, i) { var j, k, l, m, n, o, p = f !== g ? "nextSibling" : "previousSibling", q = b.parentNode, r = h && b.nodeName.toLowerCase(), t = !i && !h; if (q) { if (f) { while (p) { l = b; while (l = l[p]) if (h ? l.nodeName.toLowerCase() === r : 1 === l.nodeType) return !1; o = p = "only" === a && !o && "nextSibling" } return !0 } if (o = [g ? q.firstChild : q.lastChild], g && t) { k = q[s] || (q[s] = {}), j = k[a] || [], n = j[0] === u && j[1], m = j[0] === u && j[2], l = n && q.childNodes[n]; while (l = ++n && l && l[p] || (m = n = 0) || o.pop()) if (1 === l.nodeType && ++m && l === b) { k[a] = [u, n, m]; break } } else if (t && (j = (b[s] || (b[s] = {}))[a]) && j[0] === u) m = j[1]; else while (l = ++n && l && l[p] || (m = n = 0) || o.pop()) if ((h ? l.nodeName.toLowerCase() === r : 1 === l.nodeType) && ++m && (t && ((l[s] || (l[s] = {}))[a] = [u, m]), l === b)) break; return m -= e, m === d || m % d === 0 && m / d >= 0 } } }, PSEUDO: function(a, b) { var c, e = d.pseudos[a] || d.setFilters[a.toLowerCase()] || db.error("unsupported pseudo: " + a); return e[s] ? e(b) : e.length > 1 ? (c = [a, a, "", b], d.setFilters.hasOwnProperty(a.toLowerCase()) ? fb(function(a, c) { var d, f = e(a, b), g = f.length; while (g--) d = I.call(a, f[g]), a[d] = !(c[d] = f[g]) }) : function(a) { return e(a, 0, c) }) : e } }, pseudos: { not: fb(function(a) { var b = [], c = [], d = g(a.replace(P, "$1")); return d[s] ? fb(function(a, b, c, e) { var f, g = d(a, null, e, []), h = a.length; while (h--)(f = g[h]) && (a[h] = !(b[h] = f)) }) : function(a, e, f) { return b[0] = a, d(b, null, f, c), !c.pop() } }), has: fb(function(a) { return function(b) { return db(a, b).length > 0 } }), contains: fb(function(a) { return function(b) { return (b.textContent || b.innerText || e(b)).indexOf(a) > -1 } }), lang: fb(function(a) { return U.test(a || "") || db.error("unsupported lang: " + a), a = a.replace(ab, bb).toLowerCase(), function(b) { var c; do if (c = n ? b.lang : b.getAttribute("xml:lang") || b.getAttribute("lang")) return c = c.toLowerCase(), c === a || 0 === c.indexOf(a + "-"); while ((b = b.parentNode) && 1 === b.nodeType); return !1 } }), target: function(b) { var c = a.location && a.location.hash; return c && c.slice(1) === b.id }, root: function(a) { return a === m }, focus: function(a) { return a === l.activeElement && (!l.hasFocus || l.hasFocus()) && !!(a.type || a.href || ~a.tabIndex) }, enabled: function(a) { return a.disabled === !1 }, disabled: function(a) { return a.disabled === !0 }, checked: function(a) { var b = a.nodeName.toLowerCase(); return "input" === b && !!a.checked || "option" === b && !!a.selected }, selected: function(a) { return a.parentNode && a.parentNode.selectedIndex, a.selected === !0 }, empty: function(a) { for (a = a.firstChild; a; a = a.nextSibling) if (a.nodeType < 6) return !1; return !0 }, parent: function(a) { return !d.pseudos.empty(a) }, header: function(a) { return X.test(a.nodeName) }, input: function(a) { return W.test(a.nodeName) }, button: function(a) { var b = a.nodeName.toLowerCase(); return "input" === b && "button" === a.type || "button" === b }, text: function(a) { var b; return "input" === a.nodeName.toLowerCase() && "text" === a.type && (null == (b = a.getAttribute("type")) || "text" === b.toLowerCase()) }, first: lb(function() { return [0] }), last: lb(function(a, b) { return [b - 1] }), eq: lb(function(a, b, c) { return [0 > c ? c + b : c] }), even: lb(function(a, b) { for (var c = 0; b > c; c += 2) a.push(c); return a }), odd: lb(function(a, b) { for (var c = 1; b > c; c += 2) a.push(c); return a }), lt: lb(function(a, b, c) { for (var d = 0 > c ? c + b : c; --d >= 0;) a.push(d); return a }), gt: lb(function(a, b, c) { for (var d = 0 > c ? c + b : c; ++d < b;) a.push(d); return a }) } }, d.pseudos.nth = d.pseudos.eq; for (b in { radio: !0, checkbox: !0, file: !0, password: !0, image: !0 }) d.pseudos[b] = jb(b); for (b in { submit: !0, reset: !0 }) d.pseudos[b] = kb(b); function nb() {} nb.prototype = d.filters = d.pseudos, d.setFilters = new nb; function ob(a, b) { var c, e, f, g, h, i, j, k = x[a + " "]; if (k) return b ? 0 : k.slice(0); h = a, i = [], j = d.preFilter; while (h) { (!c || (e = Q.exec(h))) && (e && (h = h.slice(e[0].length) || h), i.push(f = [])), c = !1, (e = R.exec(h)) && (c = e.shift(), f.push({ value: c, type: e[0].replace(P, " ") }), h = h.slice(c.length)); for (g in d.filter) !(e = V[g].exec(h)) || j[g] && !(e = j[g](e)) || (c = e.shift(), f.push({ value: c, type: g, matches: e }), h = h.slice(c.length)); if (!c) break } return b ? h.length : h ? db.error(a) : x(a, i).slice(0) } function pb(a) { for (var b = 0, c = a.length, d = ""; c > b; b++) d += a[b].value; return d } function qb(a, b, c) { var d = b.dir, e = c && "parentNode" === d, f = v++; return b.first ? function(b, c, f) { while (b = b[d]) if (1 === b.nodeType || e) return a(b, c, f) } : function(b, c, g) { var h, i, j = [u, f]; if (g) { while (b = b[d]) if ((1 === b.nodeType || e) && a(b, c, g)) return !0 } else while (b = b[d]) if (1 === b.nodeType || e) { if (i = b[s] || (b[s] = {}), (h = i[d]) && h[0] === u && h[1] === f) return j[2] = h[2]; if (i[d] = j, j[2] = a(b, c, g)) return !0 } } } function rb(a) { return a.length > 1 ? function(b, c, d) { var e = a.length; while (e--) if (!a[e](b, c, d)) return !1; return !0 } : a[0] } function sb(a, b, c, d, e) { for (var f, g = [], h = 0, i = a.length, j = null != b; i > h; h++)(f = a[h]) && (!c || c(f, d, e)) && (g.push(f), j && b.push(h)); return g } function tb(a, b, c, d, e, f) { return d && !d[s] && (d = tb(d)), e && !e[s] && (e = tb(e, f)), fb(function(f, g, h, i) { var j, k, l, m = [], n = [], o = g.length, p = f || wb(b || "*", h.nodeType ? [h] : h, []), q = !a || !f && b ? p : sb(p, m, a, h, i), r = c ? e || (f ? a : o || d) ? [] : g : q; if (c && c(q, r, h, i), d) { j = sb(r, n), d(j, [], h, i), k = j.length; while (k--)(l = j[k]) && (r[n[k]] = !(q[n[k]] = l)) } if (f) { if (e || a) { if (e) { j = [], k = r.length; while (k--)(l = r[k]) && j.push(q[k] = l); e(null, r = [], j, i) } k = r.length; while (k--)(l = r[k]) && (j = e ? I.call(f, l) : m[k]) > -1 && (f[j] = !(g[j] = l)) } } else r = sb(r === g ? r.splice(o, r.length) : r), e ? e(null, g, r, i) : G.apply(g, r) }) } function ub(a) { for (var b, c, e, f = a.length, g = d.relative[a[0].type], i = g || d.relative[" "], j = g ? 1 : 0, k = qb(function(a) { return a === b }, i, !0), l = qb(function(a) { return I.call(b, a) > -1 }, i, !0), m = [function(a, c, d) { return !g && (d || c !== h) || ((b = c).nodeType ? k(a, c, d) : l(a, c, d)) }]; f > j; j++) if (c = d.relative[a[j].type]) m = [qb(rb(m), c)]; else { if (c = d.filter[a[j].type].apply(null, a[j].matches), c[s]) { for (e = ++j; f > e; e++) if (d.relative[a[e].type]) break; return tb(j > 1 && rb(m), j > 1 && pb(a.slice(0, j - 1).concat({ value: " " === a[j - 2].type ? "*" : "" })).replace(P, "$1"), c, e > j && ub(a.slice(j, e)), f > e && ub(a = a.slice(e)), f > e && pb(a)) } m.push(c) } return rb(m) } function vb(a, b) { var c = b.length > 0, e = a.length > 0, f = function(f, g, i, j, k) { var m, n, o, p = 0, q = "0", r = f && [], s = [], t = h, v = f || e && d.find.TAG("*", k), w = u += null == t ? 1 : Math.random() || .1, x = v.length; for (k && (h = g !== l && g); q !== x && null != (m = v[q]); q++) { if (e && m) { n = 0; while (o = a[n++]) if (o(m, g, i)) { j.push(m); break } k && (u = w) } c && ((m = !o && m) && p--, f && r.push(m)) } if (p += q, c && q !== p) { n = 0; while (o = b[n++]) o(r, s, g, i); if (f) { if (p > 0) while (q--) r[q] || s[q] || (s[q] = E.call(j)); s = sb(s) } G.apply(j, s), k && !f && s.length > 0 && p + b.length > 1 && db.uniqueSort(j) } return k && (u = w, h = t), r }; return c ? fb(f) : f } g = db.compile = function(a, b) { var c, d = [], e = [], f = y[a + " "]; if (!f) { b || (b = ob(a)), c = b.length; while (c--) f = ub(b[c]), f[s] ? d.push(f) : e.push(f); f = y(a, vb(e, d)) } return f }; function wb(a, b, c) { for (var d = 0, e = b.length; e > d; d++) db(a, b[d], c); return c } function xb(a, b, e, f) { var h, i, j, k, l, m = ob(a); if (!f && 1 === m.length) { if (i = m[0] = m[0].slice(0), i.length > 2 && "ID" === (j = i[0]).type && c.getById && 9 === b.nodeType && n && d.relative[i[1].type]) { if (b = (d.find.ID(j.matches[0].replace(ab, bb), b) || [])[0], !b) return e; a = a.slice(i.shift().value.length) } h = V.needsContext.test(a) ? 0 : i.length; while (h--) { if (j = i[h], d.relative[k = j.type]) break; if ((l = d.find[k]) && (f = l(j.matches[0].replace(ab, bb), $.test(i[0].type) && mb(b.parentNode) || b))) { if (i.splice(h, 1), a = f.length && pb(i), !a) return G.apply(e, f), e; break } } } return g(a, m)(f, b, !n, e, $.test(a) && mb(b.parentNode) || b), e } return c.sortStable = s.split("").sort(z).join("") === s, c.detectDuplicates = !!j, k(), c.sortDetached = gb(function(a) { return 1 & a.compareDocumentPosition(l.createElement("div")) }), gb(function(a) { return a.innerHTML = "<a href='#'></a>", "#" === a.firstChild.getAttribute("href") }) || hb("type|href|height|width", function(a, b, c) { return c ? void 0 : a.getAttribute(b, "type" === b.toLowerCase() ? 1 : 2) }), c.attributes && gb(function(a) { return a.innerHTML = "<input/>", a.firstChild.setAttribute("value", ""), "" === a.firstChild.getAttribute("value") }) || hb("value", function(a, b, c) { return c || "input" !== a.nodeName.toLowerCase() ? void 0 : a.defaultValue }), gb(function(a) { return null == a.getAttribute("disabled") }) || hb(J, function(a, b, c) { var d; return c ? void 0 : a[b] === !0 ? b.toLowerCase() : (d = a.getAttributeNode(b)) && d.specified ? d.value : null }), db }(a); n.find = t, n.expr = t.selectors, n.expr[":"] = n.expr.pseudos, n.unique = t.uniqueSort, n.text = t.getText, n.isXMLDoc = t.isXML, n.contains = t.contains; var u = n.expr.match.needsContext, v = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, w = /^.[^:#\[\.,]*$/; function x(a, b, c) { if (n.isFunction(b)) return n.grep(a, function(a, d) { return !!b.call(a, d, a) !== c }); if (b.nodeType) return n.grep(a, function(a) { return a === b !== c }); if ("string" == typeof b) { if (w.test(b)) return n.filter(b, a, c); b = n.filter(b, a) } return n.grep(a, function(a) { return n.inArray(a, b) >= 0 !== c }) } n.filter = function(a, b, c) { var d = b[0]; return c && (a = ":not(" + a + ")"), 1 === b.length && 1 === d.nodeType ? n.find.matchesSelector(d, a) ? [d] : [] : n.find.matches(a, n.grep(b, function(a) { return 1 === a.nodeType })) }, n.fn.extend({ find: function(a) { var b, c = [], d = this, e = d.length; if ("string" != typeof a) return this.pushStack(n(a).filter(function() { for (b = 0; e > b; b++) if (n.contains(d[b], this)) return !0 })); for (b = 0; e > b; b++) n.find(a, d[b], c); return c = this.pushStack(e > 1 ? n.unique(c) : c), c.selector = this.selector ? this.selector + " " + a : a, c }, filter: function(a) { return this.pushStack(x(this, a || [], !1)) }, not: function(a) { return this.pushStack(x(this, a || [], !0)) }, is: function(a) { return !!x(this, "string" == typeof a && u.test(a) ? n(a) : a || [], !1).length } }); var y, z = a.document, A = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, B = n.fn.init = function(a, b) { var c, d; if (!a) return this; if ("string" == typeof a) { if (c = "<" === a.charAt(0) && ">" === a.charAt(a.length - 1) && a.length >= 3 ? [null, a, null] : A.exec(a), !c || !c[1] && b) return !b || b.jquery ? (b || y).find(a) : this.constructor(b).find(a); if (c[1]) { if (b = b instanceof n ? b[0] : b, n.merge(this, n.parseHTML(c[1], b && b.nodeType ? b.ownerDocument || b : z, !0)), v.test(c[1]) && n.isPlainObject(b)) for (c in b) n.isFunction(this[c]) ? this[c](b[c]) : this.attr(c, b[c]); return this } if (d = z.getElementById(c[2]), d && d.parentNode) { if (d.id !== c[2]) return y.find(a); this.length = 1, this[0] = d } return this.context = z, this.selector = a, this } return a.nodeType ? (this.context = this[0] = a, this.length = 1, this) : n.isFunction(a) ? "undefined" != typeof y.ready ? y.ready(a) : a(n) : (void 0 !== a.selector && (this.selector = a.selector, this.context = a.context), n.makeArray(a, this)) }; B.prototype = n.fn, y = n(z); var C = /^(?:parents|prev(?:Until|All))/, D = { children: !0, contents: !0, next: !0, prev: !0 }; n.extend({ dir: function(a, b, c) { var d = [], e = a[b]; while (e && 9 !== e.nodeType && (void 0 === c || 1 !== e.nodeType || !n(e).is(c))) 1 === e.nodeType && d.push(e), e = e[b]; return d }, sibling: function(a, b) { for (var c = []; a; a = a.nextSibling) 1 === a.nodeType && a !== b && c.push(a); return c } }), n.fn.extend({ has: function(a) { var b, c = n(a, this), d = c.length; return this.filter(function() { for (b = 0; d > b; b++) if (n.contains(this, c[b])) return !0 }) }, closest: function(a, b) { for (var c, d = 0, e = this.length, f = [], g = u.test(a) || "string" != typeof a ? n(a, b || this.context) : 0; e > d; d++) for (c = this[d]; c && c !== b; c = c.parentNode) if (c.nodeType < 11 && (g ? g.index(c) > -1 : 1 === c.nodeType && n.find.matchesSelector(c, a))) { f.push(c); break } return this.pushStack(f.length > 1 ? n.unique(f) : f) }, index: function(a) { return a ? "string" == typeof a ? n.inArray(this[0], n(a)) : n.inArray(a.jquery ? a[0] : a, this) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1 }, add: function(a, b) { return this.pushStack(n.unique(n.merge(this.get(), n(a, b)))) }, addBack: function(a) { return this.add(null == a ? this.prevObject : this.prevObject.filter(a)) } }); function E(a, b) { do a = a[b]; while (a && 1 !== a.nodeType); return a } n.each({ parent: function(a) { var b = a.parentNode; return b && 11 !== b.nodeType ? b : null }, parents: function(a) { return n.dir(a, "parentNode") }, parentsUntil: function(a, b, c) { return n.dir(a, "parentNode", c) }, next: function(a) { return E(a, "nextSibling") }, prev: function(a) { return E(a, "previousSibling") }, nextAll: function(a) { return n.dir(a, "nextSibling") }, prevAll: function(a) { return n.dir(a, "previousSibling") }, nextUntil: function(a, b, c) { return n.dir(a, "nextSibling", c) }, prevUntil: function(a, b, c) { return n.dir(a, "previousSibling", c) }, siblings: function(a) { return n.sibling((a.parentNode || {}).firstChild, a) }, children: function(a) { return n.sibling(a.firstChild) }, contents: function(a) { return n.nodeName(a, "iframe") ? a.contentDocument || a.contentWindow.document : n.merge([], a.childNodes) } }, function(a, b) { n.fn[a] = function(c, d) { var e = n.map(this, b, c); return "Until" !== a.slice(-5) && (d = c), d && "string" == typeof d && (e = n.filter(d, e)), this.length > 1 && (D[a] || (e = n.unique(e)), C.test(a) && (e = e.reverse())), this.pushStack(e) } }); var F = /\S+/g, G = {}; function H(a) { var b = G[a] = {}; return n.each(a.match(F) || [], function(a, c) { b[c] = !0 }), b } n.Callbacks = function(a) { a = "string" == typeof a ? G[a] || H(a) : n.extend({}, a); var b, c, d, e, f, g, h = [], i = !a.once && [], j = function(l) { for (c = a.memory && l, d = !0, f = g || 0, g = 0, e = h.length, b = !0; h && e > f; f++) if (h[f].apply(l[0], l[1]) === !1 && a.stopOnFalse) { c = !1; break } b = !1, h && (i ? i.length && j(i.shift()) : c ? h = [] : k.disable()) }, k = { add: function() { if (h) { var d = h.length; ! function f(b) { n.each(b, function(b, c) { var d = n.type(c); "function" === d ? a.unique && k.has(c) || h.push(c) : c && c.length && "string" !== d && f(c) }) }(arguments), b ? e = h.length : c && (g = d, j(c)) } return this }, remove: function() { return h && n.each(arguments, function(a, c) { var d; while ((d = n.inArray(c, h, d)) > -1) h.splice(d, 1), b && (e >= d && e--, f >= d && f--) }), this }, has: function(a) { return a ? n.inArray(a, h) > -1 : !(!h || !h.length) }, empty: function() { return h = [], e = 0, this }, disable: function() { return h = i = c = void 0, this }, disabled: function() { return !h }, lock: function() { return i = void 0, c || k.disable(), this }, locked: function() { return !i }, fireWith: function(a, c) { return !h || d && !i || (c = c || [], c = [a, c.slice ? c.slice() : c], b ? i.push(c) : j(c)), this }, fire: function() { return k.fireWith(this, arguments), this }, fired: function() { return !!d } }; return k }, n.extend({ Deferred: function(a) { var b = [ ["resolve", "done", n.Callbacks("once memory"), "resolved"], ["reject", "fail", n.Callbacks("once memory"), "rejected"], ["notify", "progress", n.Callbacks("memory")] ], c = "pending", d = { state: function() { return c }, always: function() { return e.done(arguments).fail(arguments), this }, then: function() { var a = arguments; return n.Deferred(function(c) { n.each(b, function(b, f) { var g = n.isFunction(a[b]) && a[b]; e[f[1]](function() { var a = g && g.apply(this, arguments); a && n.isFunction(a.promise) ? a.promise().done(c.resolve).fail(c.reject).progress(c.notify) : c[f[0] + "With"](this === d ? c.promise() : this, g ? [a] : arguments) }) }), a = null }).promise() }, promise: function(a) { return null != a ? n.extend(a, d) : d } }, e = {}; return d.pipe = d.then, n.each(b, function(a, f) { var g = f[2], h = f[3]; d[f[1]] = g.add, h && g.add(function() { c = h }, b[1 ^ a][2].disable, b[2][2].lock), e[f[0]] = function() { return e[f[0] + "With"](this === e ? d : this, arguments), this }, e[f[0] + "With"] = g.fireWith }), d.promise(e), a && a.call(e, e), e }, when: function(a) { var b = 0, c = d.call(arguments), e = c.length, f = 1 !== e || a && n.isFunction(a.promise) ? e : 0, g = 1 === f ? a : n.Deferred(), h = function(a, b, c) { return function(e) { b[a] = this, c[a] = arguments.length > 1 ? d.call(arguments) : e, c === i ? g.notifyWith(b, c) : --f || g.resolveWith(b, c) } }, i, j, k; if (e > 1) for (i = new Array(e), j = new Array(e), k = new Array(e); e > b; b++) c[b] && n.isFunction(c[b].promise) ? c[b].promise().done(h(b, k, c)).fail(g.reject).progress(h(b, j, i)) : --f; return f || g.resolveWith(k, c), g.promise() } }); var I; n.fn.ready = function(a) { return n.ready.promise().done(a), this }, n.extend({ isReady: !1, readyWait: 1, holdReady: function(a) { a ? n.readyWait++ : n.ready(!0) }, ready: function(a) { if (a === !0 ? !--n.readyWait : !n.isReady) { if (!z.body) return setTimeout(n.ready); n.isReady = !0, a !== !0 && --n.readyWait > 0 || (I.resolveWith(z, [n]), n.fn.trigger && n(z).trigger("ready").off("ready")) } } }); function J() { z.addEventListener ? (z.removeEventListener("DOMContentLoaded", K, !1), a.removeEventListener("load", K, !1)) : (z.detachEvent("onreadystatechange", K), a.detachEvent("onload", K)) } function K() { (z.addEventListener || "load" === event.type || "complete" === z.readyState) && (J(), n.ready()) } n.ready.promise = function(b) { if (!I) if (I = n.Deferred(), "complete" === z.readyState) setTimeout(n.ready); else if (z.addEventListener) z.addEventListener("DOMContentLoaded", K, !1), a.addEventListener("load", K, !1); else { z.attachEvent("onreadystatechange", K), a.attachEvent("onload", K); var c = !1; try { c = null == a.frameElement && z.documentElement } catch (d) {} c && c.doScroll && ! function e() { if (!n.isReady) { try { c.doScroll("left") } catch (a) { return setTimeout(e, 50) } J(), n.ready() } }() } return I.promise(b) }; var L = "undefined", M; for (M in n(l)) break; l.ownLast = "0" !== M, l.inlineBlockNeedsLayout = !1, n(function() { var a, b, c = z.getElementsByTagName("body")[0]; c && (a = z.createElement("div"), a.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px", b = z.createElement("div"), c.appendChild(a).appendChild(b), typeof b.style.zoom !== L && (b.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1", (l.inlineBlockNeedsLayout = 3 === b.offsetWidth) && (c.style.zoom = 1)), c.removeChild(a), a = b = null) }), function() { var a = z.createElement("div"); if (null == l.deleteExpando) { l.deleteExpando = !0; try { delete a.test } catch (b) { l.deleteExpando = !1 } } a = null }(), n.acceptData = function(a) { var b = n.noData[(a.nodeName + " ").toLowerCase()], c = +a.nodeType || 1; return 1 !== c && 9 !== c ? !1 : !b || b !== !0 && a.getAttribute("classid") === b }; var N = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, O = /([A-Z])/g; function P(a, b, c) { if (void 0 === c && 1 === a.nodeType) { var d = "data-" + b.replace(O, "-$1").toLowerCase(); if (c = a.getAttribute(d), "string" == typeof c) { try { c = "true" === c ? !0 : "false" === c ? !1 : "null" === c ? null : +c + "" === c ? +c : N.test(c) ? n.parseJSON(c) : c } catch (e) {} n.data(a, b, c) } else c = void 0 } return c } function Q(a) { var b; for (b in a) if (("data" !== b || !n.isEmptyObject(a[b])) && "toJSON" !== b) return !1; return !0 } function R(a, b, d, e) { if (n.acceptData(a)) { var f, g, h = n.expando, i = a.nodeType, j = i ? n.cache : a, k = i ? a[h] : a[h] && h; if (k && j[k] && (e || j[k].data) || void 0 !== d || "string" != typeof b) return k || (k = i ? a[h] = c.pop() || n.guid++ : h), j[k] || (j[k] = i ? {} : { toJSON: n.noop }), ("object" == typeof b || "function" == typeof b) && (e ? j[k] = n.extend(j[k], b) : j[k].data = n.extend(j[k].data, b)), g = j[k], e || (g.data || (g.data = {}), g = g.data), void 0 !== d && (g[n.camelCase(b)] = d), "string" == typeof b ? (f = g[b], null == f && (f = g[n.camelCase(b)])) : f = g, f } } function S(a, b, c) { if (n.acceptData(a)) { var d, e, f = a.nodeType, g = f ? n.cache : a, h = f ? a[n.expando] : n.expando; if (g[h]) { if (b && (d = c ? g[h] : g[h].data)) { n.isArray(b) ? b = b.concat(n.map(b, n.camelCase)) : b in d ? b = [b] : (b = n.camelCase(b), b = b in d ? [b] : b.split(" ")), e = b.length; while (e--) delete d[b[e]]; if (c ? !Q(d) : !n.isEmptyObject(d)) return }(c || (delete g[h].data, Q(g[h]))) && (f ? n.cleanData([a], !0) : l.deleteExpando || g != g.window ? delete g[h] : g[h] = null) } } } n.extend({ cache: {}, noData: { "applet ": !0, "embed ": !0, "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function(a) { return a = a.nodeType ? n.cache[a[n.expando]] : a[n.expando], !!a && !Q(a) }, data: function(a, b, c) { return R(a, b, c) }, removeData: function(a, b) { return S(a, b) }, _data: function(a, b, c) { return R(a, b, c, !0) }, _removeData: function(a, b) { return S(a, b, !0) } }), n.fn.extend({ data: function(a, b) { var c, d, e, f = this[0], g = f && f.attributes; if (void 0 === a) { if (this.length && (e = n.data(f), 1 === f.nodeType && !n._data(f, "parsedAttrs"))) { c = g.length; while (c--) d = g[c].name, 0 === d.indexOf("data-") && (d = n.camelCase(d.slice(5)), P(f, d, e[d])); n._data(f, "parsedAttrs", !0) } return e } return "object" == typeof a ? this.each(function() { n.data(this, a) }) : arguments.length > 1 ? this.each(function() { n.data(this, a, b) }) : f ? P(f, a, n.data(f, a)) : void 0 }, removeData: function(a) { return this.each(function() { n.removeData(this, a) }) } }), n.extend({ queue: function(a, b, c) { var d; return a ? (b = (b || "fx") + "queue", d = n._data(a, b), c && (!d || n.isArray(c) ? d = n._data(a, b, n.makeArray(c)) : d.push(c)), d || []) : void 0 }, dequeue: function(a, b) { b = b || "fx"; var c = n.queue(a, b), d = c.length, e = c.shift(), f = n._queueHooks(a, b), g = function() { n.dequeue(a, b) }; "inprogress" === e && (e = c.shift(), d--), e && ("fx" === b && c.unshift("inprogress"), delete f.stop, e.call(a, g, f)), !d && f && f.empty.fire() }, _queueHooks: function(a, b) { var c = b + "queueHooks"; return n._data(a, c) || n._data(a, c, { empty: n.Callbacks("once memory").add(function() { n._removeData(a, b + "queue"), n._removeData(a, c) }) }) } }), n.fn.extend({ queue: function(a, b) { var c = 2; return "string" != typeof a && (b = a, a = "fx", c--), arguments.length < c ? n.queue(this[0], a) : void 0 === b ? this : this.each(function() { var c = n.queue(this, a, b); n._queueHooks(this, a), "fx" === a && "inprogress" !== c[0] && n.dequeue(this, a) }) }, dequeue: function(a) { return this.each(function() { n.dequeue(this, a) }) }, clearQueue: function(a) { return this.queue(a || "fx", []) }, promise: function(a, b) { var c, d = 1, e = n.Deferred(), f = this, g = this.length, h = function() { --d || e.resolveWith(f, [f]) }; "string" != typeof a && (b = a, a = void 0), a = a || "fx"; while (g--) c = n._data(f[g], a + "queueHooks"), c && c.empty && (d++, c.empty.add(h)); return h(), e.promise(b) } }); var T = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, U = ["Top", "Right", "Bottom", "Left"], V = function(a, b) { return a = b || a, "none" === n.css(a, "display") || !n.contains(a.ownerDocument, a) }, W = n.access = function(a, b, c, d, e, f, g) { var h = 0, i = a.length, j = null == c; if ("object" === n.type(c)) { e = !0; for (h in c) n.access(a, b, h, c[h], !0, f, g) } else if (void 0 !== d && (e = !0, n.isFunction(d) || (g = !0), j && (g ? (b.call(a, d), b = null) : (j = b, b = function(a, b, c) { return j.call(n(a), c) })), b)) for (; i > h; h++) b(a[h], c, g ? d : d.call(a[h], h, b(a[h], c))); return e ? a : j ? b.call(a) : i ? b(a[0], c) : f }, X = /^(?:checkbox|radio)$/i; ! function() { var a = z.createDocumentFragment(), b = z.createElement("div"), c = z.createElement("input"); if (b.setAttribute("className", "t"), b.innerHTML = " <link/><table></table><a href='/a'>a</a>", l.leadingWhitespace = 3 === b.firstChild.nodeType, l.tbody = !b.getElementsByTagName("tbody").length, l.htmlSerialize = !!b.getElementsByTagName("link").length, l.html5Clone = "<:nav></:nav>" !== z.createElement("nav").cloneNode(!0).outerHTML, c.type = "checkbox", c.checked = !0, a.appendChild(c), l.appendChecked = c.checked, b.innerHTML = "<textarea>x</textarea>", l.noCloneChecked = !!b.cloneNode(!0).lastChild.defaultValue, a.appendChild(b), b.innerHTML = "<input type='radio' checked='checked' name='t'/>", l.checkClone = b.cloneNode(!0).cloneNode(!0).lastChild.checked, l.noCloneEvent = !0, b.attachEvent && (b.attachEvent("onclick", function() { l.noCloneEvent = !1 }), b.cloneNode(!0).click()), null == l.deleteExpando) { l.deleteExpando = !0; try { delete b.test } catch (d) { l.deleteExpando = !1 } } a = b = c = null }(), function() { var b, c, d = z.createElement("div"); for (b in { submit: !0, change: !0, focusin: !0 }) c = "on" + b, (l[b + "Bubbles"] = c in a) || (d.setAttribute(c, "t"), l[b + "Bubbles"] = d.attributes[c].expando === !1); d = null }(); var Y = /^(?:input|select|textarea)$/i, Z = /^key/, $ = /^(?:mouse|contextmenu)|click/, _ = /^(?:focusinfocus|focusoutblur)$/, ab = /^([^.]*)(?:\.(.+)|)$/; function bb() { return !0 } function cb() { return !1 } function db() { try { return z.activeElement } catch (a) {} } n.event = { global: {}, add: function(a, b, c, d, e) { var f, g, h, i, j, k, l, m, o, p, q, r = n._data(a); if (r) { c.handler && (i = c, c = i.handler, e = i.selector), c.guid || (c.guid = n.guid++), (g = r.events) || (g = r.events = {}), (k = r.handle) || (k = r.handle = function(a) { return typeof n === L || a && n.event.triggered === a.type ? void 0 : n.event.dispatch.apply(k.elem, arguments) }, k.elem = a), b = (b || "").match(F) || [""], h = b.length; while (h--) f = ab.exec(b[h]) || [], o = q = f[1], p = (f[2] || "").split(".").sort(), o && (j = n.event.special[o] || {}, o = (e ? j.delegateType : j.bindType) || o, j = n.event.special[o] || {}, l = n.extend({ type: o, origType: q, data: d, handler: c, guid: c.guid, selector: e, needsContext: e && n.expr.match.needsContext.test(e), namespace: p.join(".") }, i), (m = g[o]) || (m = g[o] = [], m.delegateCount = 0, j.setup && j.setup.call(a, d, p, k) !== !1 || (a.addEventListener ? a.addEventListener(o, k, !1) : a.attachEvent && a.attachEvent("on" + o, k))), j.add && (j.add.call(a, l), l.handler.guid || (l.handler.guid = c.guid)), e ? m.splice(m.delegateCount++, 0, l) : m.push(l), n.event.global[o] = !0); a = null } }, remove: function(a, b, c, d, e) { var f, g, h, i, j, k, l, m, o, p, q, r = n.hasData(a) && n._data(a); if (r && (k = r.events)) { b = (b || "").match(F) || [""], j = b.length; while (j--) if (h = ab.exec(b[j]) || [], o = q = h[1], p = (h[2] || "").split(".").sort(), o) { l = n.event.special[o] || {}, o = (d ? l.delegateType : l.bindType) || o, m = k[o] || [], h = h[2] && new RegExp("(^|\\.)" + p.join("\\.(?:.*\\.|)") + "(\\.|$)"), i = f = m.length; while (f--) g = m[f], !e && q !== g.origType || c && c.guid !== g.guid || h && !h.test(g.namespace) || d && d !== g.selector && ("**" !== d || !g.selector) || (m.splice(f, 1), g.selector && m.delegateCount--, l.remove && l.remove.call(a, g)); i && !m.length && (l.teardown && l.teardown.call(a, p, r.handle) !== !1 || n.removeEvent(a, o, r.handle), delete k[o]) } else for (o in k) n.event.remove(a, o + b[j], c, d, !0); n.isEmptyObject(k) && (delete r.handle, n._removeData(a, "events")) } }, trigger: function(b, c, d, e) { var f, g, h, i, k, l, m, o = [d || z], p = j.call(b, "type") ? b.type : b, q = j.call(b, "namespace") ? b.namespace.split(".") : []; if (h = l = d = d || z, 3 !== d.nodeType && 8 !== d.nodeType && !_.test(p + n.event.triggered) && (p.indexOf(".") >= 0 && (q = p.split("."), p = q.shift(), q.sort()), g = p.indexOf(":") < 0 && "on" + p, b = b[n.expando] ? b : new n.Event(p, "object" == typeof b && b), b.isTrigger = e ? 2 : 3, b.namespace = q.join("."), b.namespace_re = b.namespace ? new RegExp("(^|\\.)" + q.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, b.result = void 0, b.target || (b.target = d), c = null == c ? [b] : n.makeArray(c, [b]), k = n.event.special[p] || {}, e || !k.trigger || k.trigger.apply(d, c) !== !1)) { if (!e && !k.noBubble && !n.isWindow(d)) { for (i = k.delegateType || p, _.test(i + p) || (h = h.parentNode); h; h = h.parentNode) o.push(h), l = h; l === (d.ownerDocument || z) && o.push(l.defaultView || l.parentWindow || a) } m = 0; while ((h = o[m++]) && !b.isPropagationStopped()) b.type = m > 1 ? i : k.bindType || p, f = (n._data(h, "events") || {})[b.type] && n._data(h, "handle"), f && f.apply(h, c), f = g && h[g], f && f.apply && n.acceptData(h) && (b.result = f.apply(h, c), b.result === !1 && b.preventDefault()); if (b.type = p, !e && !b.isDefaultPrevented() && (!k._default || k._default.apply(o.pop(), c) === !1) && n.acceptData(d) && g && d[p] && !n.isWindow(d)) { l = d[g], l && (d[g] = null), n.event.triggered = p; try { d[p]() } catch (r) {} n.event.triggered = void 0, l && (d[g] = l) } return b.result } }, dispatch: function(a) { a = n.event.fix(a); var b, c, e, f, g, h = [], i = d.call(arguments), j = (n._data(this, "events") || {})[a.type] || [], k = n.event.special[a.type] || {}; if (i[0] = a, a.delegateTarget = this, !k.preDispatch || k.preDispatch.call(this, a) !== !1) { h = n.event.handlers.call(this, a, j), b = 0; while ((f = h[b++]) && !a.isPropagationStopped()) { a.currentTarget = f.elem, g = 0; while ((e = f.handlers[g++]) && !a.isImmediatePropagationStopped())(!a.namespace_re || a.namespace_re.test(e.namespace)) && (a.handleObj = e, a.data = e.data, c = ((n.event.special[e.origType] || {}).handle || e.handler).apply(f.elem, i), void 0 !== c && (a.result = c) === !1 && (a.preventDefault(), a.stopPropagation())) } return k.postDispatch && k.postDispatch.call(this, a), a.result } }, handlers: function(a, b) { var c, d, e, f, g = [], h = b.delegateCount, i = a.target; if (h && i.nodeType && (!a.button || "click" !== a.type)) for (; i != this; i = i.parentNode || this) if (1 === i.nodeType && (i.disabled !== !0 || "click" !== a.type)) { for (e = [], f = 0; h > f; f++) d = b[f], c = d.selector + " ", void 0 === e[c] && (e[c] = d.needsContext ? n(c, this).index(i) >= 0 : n.find(c, this, null, [i]).length), e[c] && e.push(d); e.length && g.push({ elem: i, handlers: e }) } return h < b.length && g.push({ elem: this, handlers: b.slice(h) }), g }, fix: function(a) { if (a[n.expando]) return a; var b, c, d, e = a.type, f = a, g = this.fixHooks[e]; g || (this.fixHooks[e] = g = $.test(e) ? this.mouseHooks : Z.test(e) ? this.keyHooks : {}), d = g.props ? this.props.concat(g.props) : this.props, a = new n.Event(f), b = d.length; while (b--) c = d[b], a[c] = f[c]; return a.target || (a.target = f.srcElement || z), 3 === a.target.nodeType && (a.target = a.target.parentNode), a.metaKey = !!a.metaKey, g.filter ? g.filter(a, f) : a }, 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(a, b) { return null == a.which && (a.which = null != b.charCode ? b.charCode : b.keyCode), a } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function(a, b) { var c, d, e, f = b.button, g = b.fromElement; return null == a.pageX && null != b.clientX && (d = a.target.ownerDocument || z, e = d.documentElement, c = d.body, a.pageX = b.clientX + (e && e.scrollLeft || c && c.scrollLeft || 0) - (e && e.clientLeft || c && c.clientLeft || 0), a.pageY = b.clientY + (e && e.scrollTop || c && c.scrollTop || 0) - (e && e.clientTop || c && c.clientTop || 0)), !a.relatedTarget && g && (a.relatedTarget = g === a.target ? b.toElement : g), a.which || void 0 === f || (a.which = 1 & f ? 1 : 2 & f ? 3 : 4 & f ? 2 : 0), a } }, special: { load: { noBubble: !0 }, focus: { trigger: function() { if (this !== db() && this.focus) try { return this.focus(), !1 } catch (a) {} }, delegateType: "focusin" }, blur: { trigger: function() { return this === db() && this.blur ? (this.blur(), !1) : void 0 }, delegateType: "focusout" }, click: { trigger: function() { return n.nodeName(this, "input") && "checkbox" === this.type && this.click ? (this.click(), !1) : void 0 }, _default: function(a) { return n.nodeName(a.target, "a") } }, beforeunload: { postDispatch: function(a) { void 0 !== a.result && (a.originalEvent.returnValue = a.result) } } }, simulate: function(a, b, c, d) { var e = n.extend(new n.Event, c, { type: a, isSimulated: !0, originalEvent: {} }); d ? n.event.trigger(e, null, b) : n.event.dispatch.call(b, e), e.isDefaultPrevented() && c.preventDefault() } }, n.removeEvent = z.removeEventListener ? function(a, b, c) { a.removeEventListener && a.removeEventListener(b, c, !1) } : function(a, b, c) { var d = "on" + b; a.detachEvent && (typeof a[d] === L && (a[d] = null), a.detachEvent(d, c)) }, n.Event = function(a, b) { return this instanceof n.Event ? (a && a.type ? (this.originalEvent = a, this.type = a.type, this.isDefaultPrevented = a.defaultPrevented || void 0 === a.defaultPrevented && (a.returnValue === !1 || a.getPreventDefault && a.getPreventDefault()) ? bb : cb) : this.type = a, b && n.extend(this, b), this.timeStamp = a && a.timeStamp || n.now(), void(this[n.expando] = !0)) : new n.Event(a, b) }, n.Event.prototype = { isDefaultPrevented: cb, isPropagationStopped: cb, isImmediatePropagationStopped: cb, preventDefault: function() { var a = this.originalEvent; this.isDefaultPrevented = bb, a && (a.preventDefault ? a.preventDefault() : a.returnValue = !1) }, stopPropagation: function() { var a = this.originalEvent; this.isPropagationStopped = bb, a && (a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0) }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = bb, this.stopPropagation() } }, n.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function(a, b) { n.event.special[a] = { delegateType: b, bindType: b, handle: function(a) { var c, d = this, e = a.relatedTarget, f = a.handleObj; return (!e || e !== d && !n.contains(d, e)) && (a.type = f.origType, c = f.handler.apply(this, arguments), a.type = b), c } } }), l.submitBubbles || (n.event.special.submit = { setup: function() { return n.nodeName(this, "form") ? !1 : void n.event.add(this, "click._submit keypress._submit", function(a) { var b = a.target, c = n.nodeName(b, "input") || n.nodeName(b, "button") ? b.form : void 0; c && !n._data(c, "submitBubbles") && (n.event.add(c, "submit._submit", function(a) { a._submit_bubble = !0 }), n._data(c, "submitBubbles", !0)) }) }, postDispatch: function(a) { a._submit_bubble && (delete a._submit_bubble, this.parentNode && !a.isTrigger && n.event.simulate("submit", this.parentNode, a, !0)) }, teardown: function() { return n.nodeName(this, "form") ? !1 : void n.event.remove(this, "._submit") } }), l.changeBubbles || (n.event.special.change = { setup: function() { return Y.test(this.nodeName) ? (("checkbox" === this.type || "radio" === this.type) && (n.event.add(this, "propertychange._change", function(a) { "checked" === a.originalEvent.propertyName && (this._just_changed = !0) }), n.event.add(this, "click._change", function(a) { this._just_changed && !a.isTrigger && (this._just_changed = !1), n.event.simulate("change", this, a, !0) })), !1) : void n.event.add(this, "beforeactivate._change", function(a) { var b = a.target; Y.test(b.nodeName) && !n._data(b, "changeBubbles") && (n.event.add(b, "change._change", function(a) { !this.parentNode || a.isSimulated || a.isTrigger || n.event.simulate("change", this.parentNode, a, !0) }), n._data(b, "changeBubbles", !0)) }) }, handle: function(a) { var b = a.target; return this !== b || a.isSimulated || a.isTrigger || "radio" !== b.type && "checkbox" !== b.type ? a.handleObj.handler.apply(this, arguments) : void 0 }, teardown: function() { return n.event.remove(this, "._change"), !Y.test(this.nodeName) } }), l.focusinBubbles || n.each({ focus: "focusin", blur: "focusout" }, function(a, b) { var c = function(a) { n.event.simulate(b, a.target, n.event.fix(a), !0) }; n.event.special[b] = { setup: function() { var d = this.ownerDocument || this, e = n._data(d, b); e || d.addEventListener(a, c, !0), n._data(d, b, (e || 0) + 1) }, teardown: function() { var d = this.ownerDocument || this, e = n._data(d, b) - 1; e ? n._data(d, b, e) : (d.removeEventListener(a, c, !0), n._removeData(d, b)) } } }), n.fn.extend({ on: function(a, b, c, d, e) { var f, g; if ("object" == typeof a) { "string" != typeof b && (c = c || b, b = void 0); for (f in a) this.on(f, b, c, a[f], e); return this } if (null == c && null == d ? (d = b, c = b = void 0) : null == d && ("string" == typeof b ? (d = c, c = void 0) : (d = c, c = b, b = void 0)), d === !1) d = cb; else if (!d) return this; return 1 === e && (g = d, d = function(a) { return n().off(a), g.apply(this, arguments) }, d.guid = g.guid || (g.guid = n.guid++)), this.each(function() { n.event.add(this, a, d, c, b) }) }, one: function(a, b, c, d) { return this.on(a, b, c, d, 1) }, off: function(a, b, c) { var d, e; if (a && a.preventDefault && a.handleObj) return d = a.handleObj, n(a.delegateTarget).off(d.namespace ? d.origType + "." + d.namespace : d.origType, d.selector, d.handler), this; if ("object" == typeof a) { for (e in a) this.off(e, b, a[e]); return this } return (b === !1 || "function" == typeof b) && (c = b, b = void 0), c === !1 && (c = cb), this.each(function() { n.event.remove(this, a, c, b) }) }, trigger: function(a, b) { return this.each(function() { n.event.trigger(a, b, this) }) }, triggerHandler: function(a, b) { var c = this[0]; return c ? n.event.trigger(a, b, c, !0) : void 0 } }); function eb(a) { var b = fb.split("|"), c = a.createDocumentFragment(); if (c.createElement) while (b.length) c.createElement(b.pop()); return c } var fb = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", gb = / jQuery\d+="(?:null|\d+)"/g, hb = new RegExp("<(?:" + fb + ")[\\s/>]", "i"), ib = /^\s+/, jb = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, kb = /<([\w:]+)/, lb = /<tbody/i, mb = /<|&#?\w+;/, nb = /<(?:script|style|link)/i, ob = /checked\s*(?:[^=]|=\s*.checked.)/i, pb = /^$|\/(?:java|ecma)script/i, qb = /^true\/(.*)/, rb = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, sb = { 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: l.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, tb = eb(z), ub = tb.appendChild(z.createElement("div")); sb.optgroup = sb.option, sb.tbody = sb.tfoot = sb.colgroup = sb.caption = sb.thead, sb.th = sb.td; function vb(a, b) { var c, d, e = 0, f = typeof a.getElementsByTagName !== L ? a.getElementsByTagName(b || "*") : typeof a.querySelectorAll !== L ? a.querySelectorAll(b || "*") : void 0; if (!f) for (f = [], c = a.childNodes || a; null != (d = c[e]); e++) !b || n.nodeName(d, b) ? f.push(d) : n.merge(f, vb(d, b)); return void 0 === b || b && n.nodeName(a, b) ? n.merge([a], f) : f } function wb(a) { X.test(a.type) && (a.defaultChecked = a.checked) } function xb(a, b) { return n.nodeName(a, "table") && n.nodeName(11 !== b.nodeType ? b : b.firstChild, "tr") ? a.getElementsByTagName("tbody")[0] || a.appendChild(a.ownerDocument.createElement("tbody")) : a } function yb(a) { return a.type = (null !== n.find.attr(a, "type")) + "/" + a.type, a } function zb(a) { var b = qb.exec(a.type); return b ? a.type = b[1] : a.removeAttribute("type"), a } function Ab(a, b) { for (var c, d = 0; null != (c = a[d]); d++) n._data(c, "globalEval", !b || n._data(b[d], "globalEval")) } function Bb(a, b) { if (1 === b.nodeType && n.hasData(a)) { var c, d, e, f = n._data(a), g = n._data(b, f), h = f.events; if (h) { delete g.handle, g.events = {}; for (c in h) for (d = 0, e = h[c].length; e > d; d++) n.event.add(b, c, h[c][d]) } g.data && (g.data = n.extend({}, g.data)) } } function Cb(a, b) { var c, d, e; if (1 === b.nodeType) { if (c = b.nodeName.toLowerCase(), !l.noCloneEvent && b[n.expando]) { e = n._data(b); for (d in e.events) n.removeEvent(b, d, e.handle); b.removeAttribute(n.expando) } "script" === c && b.text !== a.text ? (yb(b).text = a.text, zb(b)) : "object" === c ? (b.parentNode && (b.outerHTML = a.outerHTML), l.html5Clone && a.innerHTML && !n.trim(b.innerHTML) && (b.innerHTML = a.innerHTML)) : "input" === c && X.test(a.type) ? (b.defaultChecked = b.checked = a.checked, b.value !== a.value && (b.value = a.value)) : "option" === c ? b.defaultSelected = b.selected = a.defaultSelected : ("input" === c || "textarea" === c) && (b.defaultValue = a.defaultValue) } } n.extend({ clone: function(a, b, c) { var d, e, f, g, h, i = n.contains(a.ownerDocument, a); if (l.html5Clone || n.isXMLDoc(a) || !hb.test("<" + a.nodeName + ">") ? f = a.cloneNode(!0) : (ub.innerHTML = a.outerHTML, ub.removeChild(f = ub.firstChild)), !(l.noCloneEvent && l.noCloneChecked || 1 !== a.nodeType && 11 !== a.nodeType || n.isXMLDoc(a))) for (d = vb(f), h = vb(a), g = 0; null != (e = h[g]); ++g) d[g] && Cb(e, d[g]); if (b) if (c) for (h = h || vb(a), d = d || vb(f), g = 0; null != (e = h[g]); g++) Bb(e, d[g]); else Bb(a, f); return d = vb(f, "script"), d.length > 0 && Ab(d, !i && vb(a, "script")), d = h = e = null, f }, buildFragment: function(a, b, c, d) { for (var e, f, g, h, i, j, k, m = a.length, o = eb(b), p = [], q = 0; m > q; q++) if (f = a[q], f || 0 === f) if ("object" === n.type(f)) n.merge(p, f.nodeType ? [f] : f); else if (mb.test(f)) { h = h || o.appendChild(b.createElement("div")), i = (kb.exec(f) || ["", ""])[1].toLowerCase(), k = sb[i] || sb._default, h.innerHTML = k[1] + f.replace(jb, "<$1></$2>") + k[2], e = k[0]; while (e--) h = h.lastChild; if (!l.leadingWhitespace && ib.test(f) && p.push(b.createTextNode(ib.exec(f)[0])), !l.tbody) { f = "table" !== i || lb.test(f) ? "<table>" !== k[1] || lb.test(f) ? 0 : h : h.firstChild, e = f && f.childNodes.length; while (e--) n.nodeName(j = f.childNodes[e], "tbody") && !j.childNodes.length && f.removeChild(j) } n.merge(p, h.childNodes), h.textContent = ""; while (h.firstChild) h.removeChild(h.firstChild); h = o.lastChild } else p.push(b.createTextNode(f)); h && o.removeChild(h), l.appendChecked || n.grep(vb(p, "input"), wb), q = 0; while (f = p[q++]) if ((!d || -1 === n.inArray(f, d)) && (g = n.contains(f.ownerDocument, f), h = vb(o.appendChild(f), "script"), g && Ab(h), c)) { e = 0; while (f = h[e++]) pb.test(f.type || "") && c.push(f) } return h = null, o }, cleanData: function(a, b) { for (var d, e, f, g, h = 0, i = n.expando, j = n.cache, k = l.deleteExpando, m = n.event.special; null != (d = a[h]); h++) if ((b || n.acceptData(d)) && (f = d[i], g = f && j[f])) { if (g.events) for (e in g.events) m[e] ? n.event.remove(d, e) : n.removeEvent(d, e, g.handle); j[f] && (delete j[f], k ? delete d[i] : typeof d.removeAttribute !== L ? d.removeAttribute(i) : d[i] = null, c.push(f)) } } }), n.fn.extend({ text: function(a) { return W(this, function(a) { return void 0 === a ? n.text(this) : this.empty().append((this[0] && this[0].ownerDocument || z).createTextNode(a)) }, null, a, arguments.length) }, append: function() { return this.domManip(arguments, function(a) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var b = xb(this, a); b.appendChild(a) } }) }, prepend: function() { return this.domManip(arguments, function(a) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var b = xb(this, a); b.insertBefore(a, b.firstChild) } }) }, before: function() { return this.domManip(arguments, function(a) { this.parentNode && this.parentNode.insertBefore(a, this) }) }, after: function() { return this.domManip(arguments, function(a) { this.parentNode && this.parentNode.insertBefore(a, this.nextSibling) }) }, remove: function(a, b) { for (var c, d = a ? n.filter(a, this) : this, e = 0; null != (c = d[e]); e++) b || 1 !== c.nodeType || n.cleanData(vb(c)), c.parentNode && (b && n.contains(c.ownerDocument, c) && Ab(vb(c, "script")), c.parentNode.removeChild(c)); return this }, empty: function() { for (var a, b = 0; null != (a = this[b]); b++) { 1 === a.nodeType && n.cleanData(vb(a, !1)); while (a.firstChild) a.removeChild(a.firstChild); a.options && n.nodeName(a, "select") && (a.options.length = 0) } return this }, clone: function(a, b) { return a = null == a ? !1 : a, b = null == b ? a : b, this.map(function() { return n.clone(this, a, b) }) }, html: function(a) { return W(this, function(a) { var b = this[0] || {}, c = 0, d = this.length; if (void 0 === a) return 1 === b.nodeType ? b.innerHTML.replace(gb, "") : void 0; if (!("string" != typeof a || nb.test(a) || !l.htmlSerialize && hb.test(a) || !l.leadingWhitespace && ib.test(a) || sb[(kb.exec(a) || ["", ""])[1].toLowerCase()])) { a = a.replace(jb, "<$1></$2>"); try { for (; d > c; c++) b = this[c] || {}, 1 === b.nodeType && (n.cleanData(vb(b, !1)), b.innerHTML = a); b = 0 } catch (e) {} } b && this.empty().append(a) }, null, a, arguments.length) }, replaceWith: function() { var a = arguments[0]; return this.domManip(arguments, function(b) { a = this.parentNode, n.cleanData(vb(this)), a && a.replaceChild(b, this) }), a && (a.length || a.nodeType) ? this : this.remove() }, detach: function(a) { return this.remove(a, !0) }, domManip: function(a, b) { a = e.apply([], a); var c, d, f, g, h, i, j = 0, k = this.length, m = this, o = k - 1, p = a[0], q = n.isFunction(p); if (q || k > 1 && "string" == typeof p && !l.checkClone && ob.test(p)) return this.each(function(c) { var d = m.eq(c); q && (a[0] = p.call(this, c, d.html())), d.domManip(a, b) }); if (k && (i = n.buildFragment(a, this[0].ownerDocument, !1, this), c = i.firstChild, 1 === i.childNodes.length && (i = c), c)) { for (g = n.map(vb(i, "script"), yb), f = g.length; k > j; j++) d = i, j !== o && (d = n.clone(d, !0, !0), f && n.merge(g, vb(d, "script"))), b.call(this[j], d, j); if (f) for (h = g[g.length - 1].ownerDocument, n.map(g, zb), j = 0; f > j; j++) d = g[j], pb.test(d.type || "") && !n._data(d, "globalEval") && n.contains(h, d) && (d.src ? n._evalUrl && n._evalUrl(d.src) : n.globalEval((d.text || d.textContent || d.innerHTML || "").replace(rb, ""))); i = c = null } return this } }), n.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(a, b) { n.fn[a] = function(a) { for (var c, d = 0, e = [], g = n(a), h = g.length - 1; h >= d; d++) c = d === h ? this : this.clone(!0), n(g[d])[b](c), f.apply(e, c.get()); return this.pushStack(e) } }); var Db, Eb = {}; function Fb(b, c) { var d = n(c.createElement(b)).appendTo(c.body), e = a.getDefaultComputedStyle ? a.getDefaultComputedStyle(d[0]).display : n.css(d[0], "display"); return d.detach(), e } function Gb(a) { var b = z, c = Eb[a]; return c || (c = Fb(a, b), "none" !== c && c || (Db = (Db || n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement), b = (Db[0].contentWindow || Db[0].contentDocument).document, b.write(), b.close(), c = Fb(a, b), Db.detach()), Eb[a] = c), c }! function() { var a, b, c = z.createElement("div"), d = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0"; c.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", a = c.getElementsByTagName("a")[0], a.style.cssText = "float:left;opacity:.5", l.opacity = /^0.5/.test(a.style.opacity), l.cssFloat = !!a.style.cssFloat, c.style.backgroundClip = "content-box", c.cloneNode(!0).style.backgroundClip = "", l.clearCloneStyle = "content-box" === c.style.backgroundClip, a = c = null, l.shrinkWrapBlocks = function() { var a, c, e, f; if (null == b) { if (a = z.getElementsByTagName("body")[0], !a) return; f = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px", c = z.createElement("div"), e = z.createElement("div"), a.appendChild(c).appendChild(e), b = !1, typeof e.style.zoom !== L && (e.style.cssText = d + ";width:1px;padding:1px;zoom:1", e.innerHTML = "<div></div>", e.firstChild.style.width = "5px", b = 3 !== e.offsetWidth), a.removeChild(c), a = c = e = null } return b } }(); var Hb = /^margin/, Ib = new RegExp("^(" + T + ")(?!px)[a-z%]+$", "i"), Jb, Kb, Lb = /^(top|right|bottom|left)$/; a.getComputedStyle ? (Jb = function(a) { return a.ownerDocument.defaultView.getComputedStyle(a, null) }, Kb = function(a, b, c) { var d, e, f, g, h = a.style; return c = c || Jb(a), g = c ? c.getPropertyValue(b) || c[b] : void 0, c && ("" !== g || n.contains(a.ownerDocument, a) || (g = n.style(a, b)), Ib.test(g) && Hb.test(b) && (d = h.width, e = h.minWidth, f = h.maxWidth, h.minWidth = h.maxWidth = h.width = g, g = c.width, h.width = d, h.minWidth = e, h.maxWidth = f)), void 0 === g ? g : g + "" }) : z.documentElement.currentStyle && (Jb = function(a) { return a.currentStyle }, Kb = function(a, b, c) { var d, e, f, g, h = a.style; return c = c || Jb(a), g = c ? c[b] : void 0, null == g && h && h[b] && (g = h[b]), Ib.test(g) && !Lb.test(b) && (d = h.left, e = a.runtimeStyle, f = e && e.left, f && (e.left = a.currentStyle.left), h.left = "fontSize" === b ? "1em" : g, g = h.pixelLeft + "px", h.left = d, f && (e.left = f)), void 0 === g ? g : g + "" || "auto" }); function Mb(a, b) { return { get: function() { var c = a(); if (null != c) return c ? void delete this.get : (this.get = b).apply(this, arguments) } } }! function() { var b, c, d, e, f, g, h = z.createElement("div"), i = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px", j = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0"; h.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", b = h.getElementsByTagName("a")[0], b.style.cssText = "float:left;opacity:.5", l.opacity = /^0.5/.test(b.style.opacity), l.cssFloat = !!b.style.cssFloat, h.style.backgroundClip = "content-box", h.cloneNode(!0).style.backgroundClip = "", l.clearCloneStyle = "content-box" === h.style.backgroundClip, b = h = null, n.extend(l, { reliableHiddenOffsets: function() { if (null != c) return c; var a, b, d, e = z.createElement("div"), f = z.getElementsByTagName("body")[0]; if (f) return e.setAttribute("className", "t"), e.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", a = z.createElement("div"), a.style.cssText = i, f.appendChild(a).appendChild(e), e.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", b = e.getElementsByTagName("td"), b[0].style.cssText = "padding:0;margin:0;border:0;display:none", d = 0 === b[0].offsetHeight, b[0].style.display = "", b[1].style.display = "none", c = d && 0 === b[0].offsetHeight, f.removeChild(a), e = f = null, c }, boxSizing: function() { return null == d && k(), d }, boxSizingReliable: function() { return null == e && k(), e }, pixelPosition: function() { return null == f && k(), f }, reliableMarginRight: function() { var b, c, d, e; if (null == g && a.getComputedStyle) { if (b = z.getElementsByTagName("body")[0], !b) return; c = z.createElement("div"), d = z.createElement("div"), c.style.cssText = i, b.appendChild(c).appendChild(d), e = d.appendChild(z.createElement("div")), e.style.cssText = d.style.cssText = j, e.style.marginRight = e.style.width = "0", d.style.width = "1px", g = !parseFloat((a.getComputedStyle(e, null) || {}).marginRight), b.removeChild(c) } return g } }); function k() { var b, c, h = z.getElementsByTagName("body")[0]; h && (b = z.createElement("div"), c = z.createElement("div"), b.style.cssText = i, h.appendChild(b).appendChild(c), c.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%", n.swap(h, null != h.style.zoom ? { zoom: 1 } : {}, function() { d = 4 === c.offsetWidth }), e = !0, f = !1, g = !0, a.getComputedStyle && (f = "1%" !== (a.getComputedStyle(c, null) || {}).top, e = "4px" === (a.getComputedStyle(c, null) || { width: "4px" }).width), h.removeChild(b), c = h = null) } }(), n.swap = function(a, b, c, d) { var e, f, g = {}; for (f in b) g[f] = a.style[f], a.style[f] = b[f]; e = c.apply(a, d || []); for (f in b) a.style[f] = g[f]; return e }; var Nb = /alpha\([^)]*\)/i, Ob = /opacity\s*=\s*([^)]*)/, Pb = /^(none|table(?!-c[ea]).+)/, Qb = new RegExp("^(" + T + ")(.*)$", "i"), Rb = new RegExp("^([+-])=(" + T + ")", "i"), Sb = { position: "absolute", visibility: "hidden", display: "block" }, Tb = { letterSpacing: 0, fontWeight: 400 }, Ub = ["Webkit", "O", "Moz", "ms"]; function Vb(a, b) { if (b in a) return b; var c = b.charAt(0).toUpperCase() + b.slice(1), d = b, e = Ub.length; while (e--) if (b = Ub[e] + c, b in a) return b; return d } function Wb(a, b) { for (var c, d, e, f = [], g = 0, h = a.length; h > g; g++) d = a[g], d.style && (f[g] = n._data(d, "olddisplay"), c = d.style.display, b ? (f[g] || "none" !== c || (d.style.display = ""), "" === d.style.display && V(d) && (f[g] = n._data(d, "olddisplay", Gb(d.nodeName)))) : f[g] || (e = V(d), (c && "none" !== c || !e) && n._data(d, "olddisplay", e ? c : n.css(d, "display")))); for (g = 0; h > g; g++) d = a[g], d.style && (b && "none" !== d.style.display && "" !== d.style.display || (d.style.display = b ? f[g] || "" : "none")); return a } function Xb(a, b, c) { var d = Qb.exec(b); return d ? Math.max(0, d[1] - (c || 0)) + (d[2] || "px") : b } function Yb(a, b, c, d, e) { for (var f = c === (d ? "border" : "content") ? 4 : "width" === b ? 1 : 0, g = 0; 4 > f; f += 2) "margin" === c && (g += n.css(a, c + U[f], !0, e)), d ? ("content" === c && (g -= n.css(a, "padding" + U[f], !0, e)), "margin" !== c && (g -= n.css(a, "border" + U[f] + "Width", !0, e))) : (g += n.css(a, "padding" + U[f], !0, e), "padding" !== c && (g += n.css(a, "border" + U[f] + "Width", !0, e))); return g } function Zb(a, b, c) { var d = !0, e = "width" === b ? a.offsetWidth : a.offsetHeight, f = Jb(a), g = l.boxSizing() && "border-box" === n.css(a, "boxSizing", !1, f); if (0 >= e || null == e) { if (e = Kb(a, b, f), (0 > e || null == e) && (e = a.style[b]), Ib.test(e)) return e; d = g && (l.boxSizingReliable() || e === a.style[b]), e = parseFloat(e) || 0 } return e + Yb(a, b, c || (g ? "border" : "content"), d, f) + "px" } n.extend({ cssHooks: { opacity: { get: function(a, b) { if (b) { var c = Kb(a, "opacity"); return "" === c ? "1" : c } } } }, cssNumber: { columnCount: !0, fillOpacity: !0, fontWeight: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0 }, cssProps: { "float": l.cssFloat ? "cssFloat" : "styleFloat" }, style: function(a, b, c, d) { if (a && 3 !== a.nodeType && 8 !== a.nodeType && a.style) { var e, f, g, h = n.camelCase(b), i = a.style; if (b = n.cssProps[h] || (n.cssProps[h] = Vb(i, h)), g = n.cssHooks[b] || n.cssHooks[h], void 0 === c) return g && "get" in g && void 0 !== (e = g.get(a, !1, d)) ? e : i[b]; if (f = typeof c, "string" === f && (e = Rb.exec(c)) && (c = (e[1] + 1) * e[2] + parseFloat(n.css(a, b)), f = "number"), null != c && c === c && ("number" !== f || n.cssNumber[h] || (c += "px"), l.clearCloneStyle || "" !== c || 0 !== b.indexOf("background") || (i[b] = "inherit"), !(g && "set" in g && void 0 === (c = g.set(a, c, d))))) try { i[b] = "", i[b] = c } catch (j) {} } }, css: function(a, b, c, d) { var e, f, g, h = n.camelCase(b); return b = n.cssProps[h] || (n.cssProps[h] = Vb(a.style, h)), g = n.cssHooks[b] || n.cssHooks[h], g && "get" in g && (f = g.get(a, !0, c)), void 0 === f && (f = Kb(a, b, d)), "normal" === f && b in Tb && (f = Tb[b]), "" === c || c ? (e = parseFloat(f), c === !0 || n.isNumeric(e) ? e || 0 : f) : f } }), n.each(["height", "width"], function(a, b) { n.cssHooks[b] = { get: function(a, c, d) { return c ? 0 === a.offsetWidth && Pb.test(n.css(a, "display")) ? n.swap(a, Sb, function() { return Zb(a, b, d) }) : Zb(a, b, d) : void 0 }, set: function(a, c, d) { var e = d && Jb(a); return Xb(a, c, d ? Yb(a, b, d, l.boxSizing() && "border-box" === n.css(a, "boxSizing", !1, e), e) : 0) } } }), l.opacity || (n.cssHooks.opacity = { get: function(a, b) { return Ob.test((b && a.currentStyle ? a.currentStyle.filter : a.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : b ? "1" : "" }, set: function(a, b) { var c = a.style, d = a.currentStyle, e = n.isNumeric(b) ? "alpha(opacity=" + 100 * b + ")" : "", f = d && d.filter || c.filter || ""; c.zoom = 1, (b >= 1 || "" === b) && "" === n.trim(f.replace(Nb, "")) && c.removeAttribute && (c.removeAttribute("filter"), "" === b || d && !d.filter) || (c.filter = Nb.test(f) ? f.replace(Nb, e) : f + " " + e) } }), n.cssHooks.marginRight = Mb(l.reliableMarginRight, function(a, b) { return b ? n.swap(a, { display: "inline-block" }, Kb, [a, "marginRight"]) : void 0 }), n.each({ margin: "", padding: "", border: "Width" }, function(a, b) { n.cssHooks[a + b] = { expand: function(c) { for (var d = 0, e = {}, f = "string" == typeof c ? c.split(" ") : [c]; 4 > d; d++) e[a + U[d] + b] = f[d] || f[d - 2] || f[0]; return e } }, Hb.test(a) || (n.cssHooks[a + b].set = Xb) }), n.fn.extend({ css: function(a, b) { return W(this, function(a, b, c) { var d, e, f = {}, g = 0; if (n.isArray(b)) { for (d = Jb(a), e = b.length; e > g; g++) f[b[g]] = n.css(a, b[g], !1, d); return f } return void 0 !== c ? n.style(a, b, c) : n.css(a, b) }, a, b, arguments.length > 1) }, show: function() { return Wb(this, !0) }, hide: function() { return Wb(this) }, toggle: function(a) { return "boolean" == typeof a ? a ? this.show() : this.hide() : this.each(function() { V(this) ? n(this).show() : n(this).hide() }) } }); function $b(a, b, c, d, e) { return new $b.prototype.init(a, b, c, d, e) } n.Tween = $b, $b.prototype = { constructor: $b, init: function(a, b, c, d, e, f) { this.elem = a, this.prop = c, this.easing = e || "swing", this.options = b, this.start = this.now = this.cur(), this.end = d, this.unit = f || (n.cssNumber[c] ? "" : "px") }, cur: function() { var a = $b.propHooks[this.prop]; return a && a.get ? a.get(this) : $b.propHooks._default.get(this) }, run: function(a) { var b, c = $b.propHooks[this.prop]; return this.pos = b = this.options.duration ? n.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration) : a, this.now = (this.end - this.start) * b + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), c && c.set ? c.set(this) : $b.propHooks._default.set(this), this } }, $b.prototype.init.prototype = $b.prototype, $b.propHooks = { _default: { get: function(a) { var b; return null == a.elem[a.prop] || a.elem.style && null != a.elem.style[a.prop] ? (b = n.css(a.elem, a.prop, ""), b && "auto" !== b ? b : 0) : a.elem[a.prop] }, set: function(a) { n.fx.step[a.prop] ? n.fx.step[a.prop](a) : a.elem.style && (null != a.elem.style[n.cssProps[a.prop]] || n.cssHooks[a.prop]) ? n.style(a.elem, a.prop, a.now + a.unit) : a.elem[a.prop] = a.now } } }, $b.propHooks.scrollTop = $b.propHooks.scrollLeft = { set: function(a) { a.elem.nodeType && a.elem.parentNode && (a.elem[a.prop] = a.now) } }, n.easing = { linear: function(a) { return a }, swing: function(a) { return .5 - Math.cos(a * Math.PI) / 2 } }, n.fx = $b.prototype.init, n.fx.step = {}; var _b, ac, bc = /^(?:toggle|show|hide)$/, cc = new RegExp("^(?:([+-])=|)(" + T + ")([a-z%]*)$", "i"), dc = /queueHooks$/, ec = [jc], fc = { "*": [function(a, b) { var c = this.createTween(a, b), d = c.cur(), e = cc.exec(b), f = e && e[3] || (n.cssNumber[a] ? "" : "px"), g = (n.cssNumber[a] || "px" !== f && +d) && cc.exec(n.css(c.elem, a)), h = 1, i = 20; if (g && g[3] !== f) { f = f || g[3], e = e || [], g = +d || 1; do h = h || ".5", g /= h, n.style(c.elem, a, g + f); while (h !== (h = c.cur() / d) && 1 !== h && --i) } return e && (g = c.start = +g || +d || 0, c.unit = f, c.end = e[1] ? g + (e[1] + 1) * e[2] : +e[2]), c }] }; function gc() { return setTimeout(function() { _b = void 0 }), _b = n.now() } function hc(a, b) { var c, d = { height: a }, e = 0; for (b = b ? 1 : 0; 4 > e; e += 2 - b) c = U[e], d["margin" + c] = d["padding" + c] = a; return b && (d.opacity = d.width = a), d } function ic(a, b, c) { for (var d, e = (fc[b] || []).concat(fc["*"]), f = 0, g = e.length; g > f; f++) if (d = e[f].call(c, b, a)) return d } function jc(a, b, c) { var d, e, f, g, h, i, j, k, m = this, o = {}, p = a.style, q = a.nodeType && V(a), r = n._data(a, "fxshow"); c.queue || (h = n._queueHooks(a, "fx"), null == h.unqueued && (h.unqueued = 0, i = h.empty.fire, h.empty.fire = function() { h.unqueued || i() }), h.unqueued++, m.always(function() { m.always(function() { h.unqueued--, n.queue(a, "fx").length || h.empty.fire() }) })), 1 === a.nodeType && ("height" in b || "width" in b) && (c.overflow = [p.overflow, p.overflowX, p.overflowY], j = n.css(a, "display"), k = Gb(a.nodeName), "none" === j && (j = k), "inline" === j && "none" === n.css(a, "float") && (l.inlineBlockNeedsLayout && "inline" !== k ? p.zoom = 1 : p.display = "inline-block")), c.overflow && (p.overflow = "hidden", l.shrinkWrapBlocks() || m.always(function() { p.overflow = c.overflow[0], p.overflowX = c.overflow[1], p.overflowY = c.overflow[2] })); for (d in b) if (e = b[d], bc.exec(e)) { if (delete b[d], f = f || "toggle" === e, e === (q ? "hide" : "show")) { if ("show" !== e || !r || void 0 === r[d]) continue; q = !0 } o[d] = r && r[d] || n.style(a, d) } if (!n.isEmptyObject(o)) { r ? "hidden" in r && (q = r.hidden) : r = n._data(a, "fxshow", {}), f && (r.hidden = !q), q ? n(a).show() : m.done(function() { n(a).hide() }), m.done(function() { var b; n._removeData(a, "fxshow"); for (b in o) n.style(a, b, o[b]) }); for (d in o) g = ic(q ? r[d] : 0, d, m), d in r || (r[d] = g.start, q && (g.end = g.start, g.start = "width" === d || "height" === d ? 1 : 0)) } } function kc(a, b) { var c, d, e, f, g; for (c in a) if (d = n.camelCase(c), e = b[d], f = a[c], n.isArray(f) && (e = f[1], f = a[c] = f[0]), c !== d && (a[d] = f, delete a[c]), g = n.cssHooks[d], g && "expand" in g) { f = g.expand(f), delete a[d]; for (c in f) c in a || (a[c] = f[c], b[c] = e) } else b[d] = e } function lc(a, b, c) { var d, e, f = 0, g = ec.length, h = n.Deferred().always(function() { delete i.elem }), i = function() { if (e) return !1; for (var b = _b || gc(), c = Math.max(0, j.startTime + j.duration - b), d = c / j.duration || 0, f = 1 - d, g = 0, i = j.tweens.length; i > g; g++) j.tweens[g].run(f); return h.notifyWith(a, [j, f, c]), 1 > f && i ? c : (h.resolveWith(a, [j]), !1) }, j = h.promise({ elem: a, props: n.extend({}, b), opts: n.extend(!0, { specialEasing: {} }, c), originalProperties: b, originalOptions: c, startTime: _b || gc(), duration: c.duration, tweens: [], createTween: function(b, c) { var d = n.Tween(a, j.opts, b, c, j.opts.specialEasing[b] || j.opts.easing); return j.tweens.push(d), d }, stop: function(b) { var c = 0, d = b ? j.tweens.length : 0; if (e) return this; for (e = !0; d > c; c++) j.tweens[c].run(1); return b ? h.resolveWith(a, [j, b]) : h.rejectWith(a, [j, b]), this } }), k = j.props; for (kc(k, j.opts.specialEasing); g > f; f++) if (d = ec[f].call(j, a, k, j.opts)) return d; return n.map(k, ic, j), n.isFunction(j.opts.start) && j.opts.start.call(a, j), n.fx.timer(n.extend(i, { elem: a, anim: j, queue: j.opts.queue })), j.progress(j.opts.progress).done(j.opts.done, j.opts.complete).fail(j.opts.fail).always(j.opts.always) } n.Animation = n.extend(lc, { tweener: function(a, b) { n.isFunction(a) ? (b = a, a = ["*"]) : a = a.split(" "); for (var c, d = 0, e = a.length; e > d; d++) c = a[d], fc[c] = fc[c] || [], fc[c].unshift(b) }, prefilter: function(a, b) { b ? ec.unshift(a) : ec.push(a) } }), n.speed = function(a, b, c) { var d = a && "object" == typeof a ? n.extend({}, a) : { complete: c || !c && b || n.isFunction(a) && a, duration: a, easing: c && b || b && !n.isFunction(b) && b }; return d.duration = n.fx.off ? 0 : "number" == typeof d.duration ? d.duration : d.duration in n.fx.speeds ? n.fx.speeds[d.duration] : n.fx.speeds._default, (null == d.queue || d.queue === !0) && (d.queue = "fx"), d.old = d.complete, d.complete = function() { n.isFunction(d.old) && d.old.call(this), d.queue && n.dequeue(this, d.queue) }, d }, n.fn.extend({ fadeTo: function(a, b, c, d) { return this.filter(V).css("opacity", 0).show().end().animate({ opacity: b }, a, c, d) }, animate: function(a, b, c, d) { var e = n.isEmptyObject(a), f = n.speed(b, c, d), g = function() { var b = lc(this, n.extend({}, a), f); (e || n._data(this, "finish")) && b.stop(!0) }; return g.finish = g, e || f.queue === !1 ? this.each(g) : this.queue(f.queue, g) }, stop: function(a, b, c) { var d = function(a) { var b = a.stop; delete a.stop, b(c) }; return "string" != typeof a && (c = b, b = a, a = void 0), b && a !== !1 && this.queue(a || "fx", []), this.each(function() { var b = !0, e = null != a && a + "queueHooks", f = n.timers, g = n._data(this); if (e) g[e] && g[e].stop && d(g[e]); else for (e in g) g[e] && g[e].stop && dc.test(e) && d(g[e]); for (e = f.length; e--;) f[e].elem !== this || null != a && f[e].queue !== a || (f[e].anim.stop(c), b = !1, f.splice(e, 1)); (b || !c) && n.dequeue(this, a) }) }, finish: function(a) { return a !== !1 && (a = a || "fx"), this.each(function() { var b, c = n._data(this), d = c[a + "queue"], e = c[a + "queueHooks"], f = n.timers, g = d ? d.length : 0; for (c.finish = !0, n.queue(this, a, []), e && e.stop && e.stop.call(this, !0), b = f.length; b--;) f[b].elem === this && f[b].queue === a && (f[b].anim.stop(!0), f.splice(b, 1)); for (b = 0; g > b; b++) d[b] && d[b].finish && d[b].finish.call(this); delete c.finish }) } }), n.each(["toggle", "show", "hide"], function(a, b) { var c = n.fn[b]; n.fn[b] = function(a, d, e) { return null == a || "boolean" == typeof a ? c.apply(this, arguments) : this.animate(hc(b, !0), a, d, e) } }), n.each({ slideDown: hc("show"), slideUp: hc("hide"), slideToggle: hc("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function(a, b) { n.fn[a] = function(a, c, d) { return this.animate(b, a, c, d) } }), n.timers = [], n.fx.tick = function() { var a, b = n.timers, c = 0; for (_b = n.now(); c < b.length; c++) a = b[c], a() || b[c] !== a || b.splice(c--, 1); b.length || n.fx.stop(), _b = void 0 }, n.fx.timer = function(a) { n.timers.push(a), a() ? n.fx.start() : n.timers.pop() }, n.fx.interval = 13, n.fx.start = function() { ac || (ac = setInterval(n.fx.tick, n.fx.interval)) }, n.fx.stop = function() { clearInterval(ac), ac = null }, n.fx.speeds = { slow: 600, fast: 200, _default: 400 }, n.fn.delay = function(a, b) { return a = n.fx ? n.fx.speeds[a] || a : a, b = b || "fx", this.queue(b, function(b, c) { var d = setTimeout(b, a); c.stop = function() { clearTimeout(d) } }) }, function() { var a, b, c, d, e = z.createElement("div"); e.setAttribute("className", "t"), e.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", a = e.getElementsByTagName("a")[0], c = z.createElement("select"), d = c.appendChild(z.createElement("option")), b = e.getElementsByTagName("input")[0], a.style.cssText = "top:1px", l.getSetAttribute = "t" !== e.className, l.style = /top/.test(a.getAttribute("style")), l.hrefNormalized = "/a" === a.getAttribute("href"), l.checkOn = !!b.value, l.optSelected = d.selected, l.enctype = !!z.createElement("form").enctype, c.disabled = !0, l.optDisabled = !d.disabled, b = z.createElement("input"), b.setAttribute("value", ""), l.input = "" === b.getAttribute("value"), b.value = "t", b.setAttribute("type", "radio"), l.radioValue = "t" === b.value, a = b = c = d = e = null }(); var mc = /\r/g; n.fn.extend({ val: function(a) { var b, c, d, e = this[0]; { if (arguments.length) return d = n.isFunction(a), this.each(function(c) { var e; 1 === this.nodeType && (e = d ? a.call(this, c, n(this).val()) : a, null == e ? e = "" : "number" == typeof e ? e += "" : n.isArray(e) && (e = n.map(e, function(a) { return null == a ? "" : a + "" })), b = n.valHooks[this.type] || n.valHooks[this.nodeName.toLowerCase()], b && "set" in b && void 0 !== b.set(this, e, "value") || (this.value = e)) }); if (e) return b = n.valHooks[e.type] || n.valHooks[e.nodeName.toLowerCase()], b && "get" in b && void 0 !== (c = b.get(e, "value")) ? c : (c = e.value, "string" == typeof c ? c.replace(mc, "") : null == c ? "" : c) } } }), n.extend({ valHooks: { option: { get: function(a) { var b = n.find.attr(a, "value"); return null != b ? b : n.text(a) } }, select: { get: function(a) { for (var b, c, d = a.options, e = a.selectedIndex, f = "select-one" === a.type || 0 > e, g = f ? null : [], h = f ? e + 1 : d.length, i = 0 > e ? h : f ? e : 0; h > i; i++) if (c = d[i], !(!c.selected && i !== e || (l.optDisabled ? c.disabled : null !== c.getAttribute("disabled")) || c.parentNode.disabled && n.nodeName(c.parentNode, "optgroup"))) { if (b = n(c).val(), f) return b; g.push(b) } return g }, set: function(a, b) { var c, d, e = a.options, f = n.makeArray(b), g = e.length; while (g--) if (d = e[g], n.inArray(n.valHooks.option.get(d), f) >= 0) try { d.selected = c = !0 } catch (h) { d.scrollHeight } else d.selected = !1; return c || (a.selectedIndex = -1), e } } } }), n.each(["radio", "checkbox"], function() { n.valHooks[this] = { set: function(a, b) { return n.isArray(b) ? a.checked = n.inArray(n(a).val(), b) >= 0 : void 0 } }, l.checkOn || (n.valHooks[this].get = function(a) { return null === a.getAttribute("value") ? "on" : a.value }) }); var nc, oc, pc = n.expr.attrHandle, qc = /^(?:checked|selected)$/i, rc = l.getSetAttribute, sc = l.input; n.fn.extend({ attr: function(a, b) { return W(this, n.attr, a, b, arguments.length > 1) }, removeAttr: function(a) { return this.each(function() { n.removeAttr(this, a) }) } }), n.extend({ attr: function(a, b, c) { var d, e, f = a.nodeType; if (a && 3 !== f && 8 !== f && 2 !== f) return typeof a.getAttribute === L ? n.prop(a, b, c) : (1 === f && n.isXMLDoc(a) || (b = b.toLowerCase(), d = n.attrHooks[b] || (n.expr.match.bool.test(b) ? oc : nc)), void 0 === c ? d && "get" in d && null !== (e = d.get(a, b)) ? e : (e = n.find.attr(a, b), null == e ? void 0 : e) : null !== c ? d && "set" in d && void 0 !== (e = d.set(a, c, b)) ? e : (a.setAttribute(b, c + ""), c) : void n.removeAttr(a, b)) }, removeAttr: function(a, b) { var c, d, e = 0, f = b && b.match(F); if (f && 1 === a.nodeType) while (c = f[e++]) d = n.propFix[c] || c, n.expr.match.bool.test(c) ? sc && rc || !qc.test(c) ? a[d] = !1 : a[n.camelCase("default-" + c)] = a[d] = !1 : n.attr(a, c, ""), a.removeAttribute(rc ? c : d) }, attrHooks: { type: { set: function(a, b) { if (!l.radioValue && "radio" === b && n.nodeName(a, "input")) { var c = a.value; return a.setAttribute("type", b), c && (a.value = c), b } } } } }), oc = { set: function(a, b, c) { return b === !1 ? n.removeAttr(a, c) : sc && rc || !qc.test(c) ? a.setAttribute(!rc && n.propFix[c] || c, c) : a[n.camelCase("default-" + c)] = a[c] = !0, c } }, n.each(n.expr.match.bool.source.match(/\w+/g), function(a, b) { var c = pc[b] || n.find.attr; pc[b] = sc && rc || !qc.test(b) ? function(a, b, d) { var e, f; return d || (f = pc[b], pc[b] = e, e = null != c(a, b, d) ? b.toLowerCase() : null, pc[b] = f), e } : function(a, b, c) { return c ? void 0 : a[n.camelCase("default-" + b)] ? b.toLowerCase() : null } }), sc && rc || (n.attrHooks.value = { set: function(a, b, c) { return n.nodeName(a, "input") ? void(a.defaultValue = b) : nc && nc.set(a, b, c) } }), rc || (nc = { set: function(a, b, c) { var d = a.getAttributeNode(c); return d || a.setAttributeNode(d = a.ownerDocument.createAttribute(c)), d.value = b += "", "value" === c || b === a.getAttribute(c) ? b : void 0 } }, pc.id = pc.name = pc.coords = function(a, b, c) { var d; return c ? void 0 : (d = a.getAttributeNode(b)) && "" !== d.value ? d.value : null }, n.valHooks.button = { get: function(a, b) { var c = a.getAttributeNode(b); return c && c.specified ? c.value : void 0 }, set: nc.set }, n.attrHooks.contenteditable = { set: function(a, b, c) { nc.set(a, "" === b ? !1 : b, c) } }, n.each(["width", "height"], function(a, b) { n.attrHooks[b] = { set: function(a, c) { return "" === c ? (a.setAttribute(b, "auto"), c) : void 0 } } })), l.style || (n.attrHooks.style = { get: function(a) { return a.style.cssText || void 0 }, set: function(a, b) { return a.style.cssText = b + "" } }); var tc = /^(?:input|select|textarea|button|object)$/i, uc = /^(?:a|area)$/i; n.fn.extend({ prop: function(a, b) { return W(this, n.prop, a, b, arguments.length > 1) }, removeProp: function(a) { return a = n.propFix[a] || a, this.each(function() { try { this[a] = void 0, delete this[a] } catch (b) {} }) } }), n.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function(a, b, c) { var d, e, f, g = a.nodeType; if (a && 3 !== g && 8 !== g && 2 !== g) return f = 1 !== g || !n.isXMLDoc(a), f && (b = n.propFix[b] || b, e = n.propHooks[b]), void 0 !== c ? e && "set" in e && void 0 !== (d = e.set(a, c, b)) ? d : a[b] = c : e && "get" in e && null !== (d = e.get(a, b)) ? d : a[b] }, propHooks: { tabIndex: { get: function(a) { var b = n.find.attr(a, "tabindex"); return b ? parseInt(b, 10) : tc.test(a.nodeName) || uc.test(a.nodeName) && a.href ? 0 : -1 } } } }), l.hrefNormalized || n.each(["href", "src"], function(a, b) { n.propHooks[b] = { get: function(a) { return a.getAttribute(b, 4) } } }), l.optSelected || (n.propHooks.selected = { get: function(a) { var b = a.parentNode; return b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex), null } }), n.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function() { n.propFix[this.toLowerCase()] = this }), l.enctype || (n.propFix.enctype = "encoding"); var vc = /[\t\r\n\f]/g; n.fn.extend({ addClass: function(a) { var b, c, d, e, f, g, h = 0, i = this.length, j = "string" == typeof a && a; if (n.isFunction(a)) return this.each(function(b) { n(this).addClass(a.call(this, b, this.className)) }); if (j) for (b = (a || "").match(F) || []; i > h; h++) if (c = this[h], d = 1 === c.nodeType && (c.className ? (" " + c.className + " ").replace(vc, " ") : " ")) { f = 0; while (e = b[f++]) d.indexOf(" " + e + " ") < 0 && (d += e + " "); g = n.trim(d), c.className !== g && (c.className = g) } return this }, removeClass: function(a) { var b, c, d, e, f, g, h = 0, i = this.length, j = 0 === arguments.length || "string" == typeof a && a; if (n.isFunction(a)) return this.each(function(b) { n(this).removeClass(a.call(this, b, this.className)) }); if (j) for (b = (a || "").match(F) || []; i > h; h++) if (c = this[h], d = 1 === c.nodeType && (c.className ? (" " + c.className + " ").replace(vc, " ") : "")) { f = 0; while (e = b[f++]) while (d.indexOf(" " + e + " ") >= 0) d = d.replace(" " + e + " ", " "); g = a ? n.trim(d) : "", c.className !== g && (c.className = g) } return this }, toggleClass: function(a, b) { var c = typeof a; return "boolean" == typeof b && "string" === c ? b ? this.addClass(a) : this.removeClass(a) : this.each(n.isFunction(a) ? function(c) { n(this).toggleClass(a.call(this, c, this.className, b), b) } : function() { if ("string" === c) { var b, d = 0, e = n(this), f = a.match(F) || []; while (b = f[d++]) e.hasClass(b) ? e.removeClass(b) : e.addClass(b) } else(c === L || "boolean" === c) && (this.className && n._data(this, "__className__", this.className), this.className = this.className || a === !1 ? "" : n._data(this, "__className__") || "") }) }, hasClass: function(a) { for (var b = " " + a + " ", c = 0, d = this.length; d > c; c++) if (1 === this[c].nodeType && (" " + this[c].className + " ").replace(vc, " ").indexOf(b) >= 0) return !0; return !1 } }), n.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(a, b) { n.fn[b] = function(a, c) { return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b) } }), n.fn.extend({ hover: function(a, b) { return this.mouseenter(a).mouseleave(b || a) }, bind: function(a, b, c) { return this.on(a, null, b, c) }, unbind: function(a, b) { return this.off(a, null, b) }, delegate: function(a, b, c, d) { return this.on(b, a, c, d) }, undelegate: function(a, b, c) { return 1 === arguments.length ? this.off(a, "**") : this.off(b, a || "**", c) } }); var wc = n.now(), xc = /\?/, yc = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; n.parseJSON = function(b) { if (a.JSON && a.JSON.parse) return a.JSON.parse(b + ""); var c, d = null, e = n.trim(b + ""); return e && !n.trim(e.replace(yc, function(a, b, e, f) { return c && b && (d = 0), 0 === d ? a : (c = e || b, d += !f - !e, "") })) ? Function("return " + e)() : n.error("Invalid JSON: " + b) }, n.parseXML = function(b) { var c, d; if (!b || "string" != typeof b) return null; try { a.DOMParser ? (d = new DOMParser, c = d.parseFromString(b, "text/xml")) : (c = new ActiveXObject("Microsoft.XMLDOM"), c.async = "false", c.loadXML(b)) } catch (e) { c = void 0 } return c && c.documentElement && !c.getElementsByTagName("parsererror").length || n.error("Invalid XML: " + b), c }; var zc, Ac, Bc = /#.*$/, Cc = /([?&])_=[^&]*/, Dc = /^(.*?):[ \t]*([^\r\n]*)\r?$/gm, Ec = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, Fc = /^(?:GET|HEAD)$/, Gc = /^\/\//, Hc = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, Ic = {}, Jc = {}, Kc = "*/".concat("*"); try { Ac = location.href } catch (Lc) { Ac = z.createElement("a"), Ac.href = "", Ac = Ac.href } zc = Hc.exec(Ac.toLowerCase()) || []; function Mc(a) { return function(b, c) { "string" != typeof b && (c = b, b = "*"); var d, e = 0, f = b.toLowerCase().match(F) || []; if (n.isFunction(c)) while (d = f[e++]) "+" === d.charAt(0) ? (d = d.slice(1) || "*", (a[d] = a[d] || []).unshift(c)) : (a[d] = a[d] || []).push(c) } } function Nc(a, b, c, d) { var e = {}, f = a === Jc; function g(h) { var i; return e[h] = !0, n.each(a[h] || [], function(a, h) { var j = h(b, c, d); return "string" != typeof j || f || e[j] ? f ? !(i = j) : void 0 : (b.dataTypes.unshift(j), g(j), !1) }), i } return g(b.dataTypes[0]) || !e["*"] && g("*") } function Oc(a, b) { var c, d, e = n.ajaxSettings.flatOptions || {}; for (d in b) void 0 !== b[d] && ((e[d] ? a : c || (c = {}))[d] = b[d]); return c && n.extend(!0, a, c), a } function Pc(a, b, c) { var d, e, f, g, h = a.contents, i = a.dataTypes; while ("*" === i[0]) i.shift(), void 0 === e && (e = a.mimeType || b.getResponseHeader("Content-Type")); if (e) for (g in h) if (h[g] && h[g].test(e)) { i.unshift(g); break } if (i[0] in c) f = i[0]; else { for (g in c) { if (!i[0] || a.converters[g + " " + i[0]]) { f = g; break } d || (d = g) } f = f || d } return f ? (f !== i[0] && i.unshift(f), c[f]) : void 0 } function Qc(a, b, c, d) { var e, f, g, h, i, j = {}, k = a.dataTypes.slice(); if (k[1]) for (g in a.converters) j[g.toLowerCase()] = a.converters[g]; f = k.shift(); while (f) if (a.responseFields[f] && (c[a.responseFields[f]] = b), !i && d && a.dataFilter && (b = a.dataFilter(b, a.dataType)), i = f, f = k.shift()) if ("*" === f) f = i; else if ("*" !== i && i !== f) { if (g = j[i + " " + f] || j["* " + f], !g) for (e in j) if (h = e.split(" "), h[1] === f && (g = j[i + " " + h[0]] || j["* " + h[0]])) { g === !0 ? g = j[e] : j[e] !== !0 && (f = h[0], k.unshift(h[1])); break } if (g !== !0) if (g && a["throws"]) b = g(b); else try { b = g(b) } catch (l) { return { state: "parsererror", error: g ? l : "No conversion from " + i + " to " + f } } } return { state: "success", data: b } } n.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: Ac, type: "GET", isLocal: Ec.test(zc[1]), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": Kc, 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": n.parseJSON, "text xml": n.parseXML }, flatOptions: { url: !0, context: !0 } }, ajaxSetup: function(a, b) { return b ? Oc(Oc(a, n.ajaxSettings), b) : Oc(n.ajaxSettings, a) }, ajaxPrefilter: Mc(Ic), ajaxTransport: Mc(Jc), ajax: function(a, b) { "object" == typeof a && (b = a, a = void 0), b = b || {}; var c, d, e, f, g, h, i, j, k = n.ajaxSetup({}, b), l = k.context || k, m = k.context && (l.nodeType || l.jquery) ? n(l) : n.event, o = n.Deferred(), p = n.Callbacks("once memory"), q = k.statusCode || {}, r = {}, s = {}, t = 0, u = "canceled", v = { readyState: 0, getResponseHeader: function(a) { var b; if (2 === t) { if (!j) { j = {}; while (b = Dc.exec(f)) j[b[1].toLowerCase()] = b[2] } b = j[a.toLowerCase()] } return null == b ? null : b }, getAllResponseHeaders: function() { return 2 === t ? f : null }, setRequestHeader: function(a, b) { var c = a.toLowerCase(); return t || (a = s[c] = s[c] || a, r[a] = b), this }, overrideMimeType: function(a) { return t || (k.mimeType = a), this }, statusCode: function(a) { var b; if (a) if (2 > t) for (b in a) q[b] = [q[b], a[b]]; else v.always(a[v.status]); return this }, abort: function(a) { var b = a || u; return i && i.abort(b), x(0, b), this } }; if (o.promise(v).complete = p.add, v.success = v.done, v.error = v.fail, k.url = ((a || k.url || Ac) + "").replace(Bc, "").replace(Gc, zc[1] + "//"), k.type = b.method || b.type || k.method || k.type, k.dataTypes = n.trim(k.dataType || "*").toLowerCase().match(F) || [""], null == k.crossDomain && (c = Hc.exec(k.url.toLowerCase()), k.crossDomain = !(!c || c[1] === zc[1] && c[2] === zc[2] && (c[3] || ("http:" === c[1] ? "80" : "443")) === (zc[3] || ("http:" === zc[1] ? "80" : "443")))), k.data && k.processData && "string" != typeof k.data && (k.data = n.param(k.data, k.traditional)), Nc(Ic, k, b, v), 2 === t) return v; h = k.global, h && 0 === n.active++ && n.event.trigger("ajaxStart"), k.type = k.type.toUpperCase(), k.hasContent = !Fc.test(k.type), e = k.url, k.hasContent || (k.data && (e = k.url += (xc.test(e) ? "&" : "?") + k.data, delete k.data), k.cache === !1 && (k.url = Cc.test(e) ? e.replace(Cc, "$1_=" + wc++) : e + (xc.test(e) ? "&" : "?") + "_=" + wc++)), k.ifModified && (n.lastModified[e] && v.setRequestHeader("If-Modified-Since", n.lastModified[e]), n.etag[e] && v.setRequestHeader("If-None-Match", n.etag[e])), (k.data && k.hasContent && k.contentType !== !1 || b.contentType) && v.setRequestHeader("Content-Type", k.contentType), v.setRequestHeader("Accept", k.dataTypes[0] && k.accepts[k.dataTypes[0]] ? k.accepts[k.dataTypes[0]] + ("*" !== k.dataTypes[0] ? ", " + Kc + "; q=0.01" : "") : k.accepts["*"]); for (d in k.headers) v.setRequestHeader(d, k.headers[d]); if (k.beforeSend && (k.beforeSend.call(l, v, k) === !1 || 2 === t)) return v.abort(); u = "abort"; for (d in { success: 1, error: 1, complete: 1 }) v[d](k[d]); if (i = Nc(Jc, k, b, v)) { v.readyState = 1, h && m.trigger("ajaxSend", [v, k]), k.async && k.timeout > 0 && (g = setTimeout(function() { v.abort("timeout") }, k.timeout)); try { t = 1, i.send(r, x) } catch (w) { if (!(2 > t)) throw w; x(-1, w) } } else x(-1, "No Transport"); function x(a, b, c, d) { var j, r, s, u, w, x = b; 2 !== t && (t = 2, g && clearTimeout(g), i = void 0, f = d || "", v.readyState = a > 0 ? 4 : 0, j = a >= 200 && 300 > a || 304 === a, c && (u = Pc(k, v, c)), u = Qc(k, u, v, j), j ? (k.ifModified && (w = v.getResponseHeader("Last-Modified"), w && (n.lastModified[e] = w), w = v.getResponseHeader("etag"), w && (n.etag[e] = w)), 204 === a || "HEAD" === k.type ? x = "nocontent" : 304 === a ? x = "notmodified" : (x = u.state, r = u.data, s = u.error, j = !s)) : (s = x, (a || !x) && (x = "error", 0 > a && (a = 0))), v.status = a, v.statusText = (b || x) + "", j ? o.resolveWith(l, [r, x, v]) : o.rejectWith(l, [v, x, s]), v.statusCode(q), q = void 0, h && m.trigger(j ? "ajaxSuccess" : "ajaxError", [v, k, j ? r : s]), p.fireWith(l, [v, x]), h && (m.trigger("ajaxComplete", [v, k]), --n.active || n.event.trigger("ajaxStop"))) } return v }, getJSON: function(a, b, c) { return n.get(a, b, c, "json") }, getScript: function(a, b) { return n.get(a, void 0, b, "script") } }), n.each(["get", "post"], function(a, b) { n[b] = function(a, c, d, e) { return n.isFunction(c) && (e = e || d, d = c, c = void 0), n.ajax({ url: a, type: b, dataType: e, data: c, success: d }) } }), n.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(a, b) { n.fn[b] = function(a) { return this.on(b, a) } }), n._evalUrl = function(a) { return n.ajax({ url: a, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0 }) }, n.fn.extend({ wrapAll: function(a) { if (n.isFunction(a)) return this.each(function(b) { n(this).wrapAll(a.call(this, b)) }); if (this[0]) { var b = n(a, this[0].ownerDocument).eq(0).clone(!0); this[0].parentNode && b.insertBefore(this[0]), b.map(function() { var a = this; while (a.firstChild && 1 === a.firstChild.nodeType) a = a.firstChild; return a }).append(this) } return this }, wrapInner: function(a) { return this.each(n.isFunction(a) ? function(b) { n(this).wrapInner(a.call(this, b)) } : function() { var b = n(this), c = b.contents(); c.length ? c.wrapAll(a) : b.append(a) }) }, wrap: function(a) { var b = n.isFunction(a); return this.each(function(c) { n(this).wrapAll(b ? a.call(this, c) : a) }) }, unwrap: function() { return this.parent().each(function() { n.nodeName(this, "body") || n(this).replaceWith(this.childNodes) }).end() } }), n.expr.filters.hidden = function(a) { return a.offsetWidth <= 0 && a.offsetHeight <= 0 || !l.reliableHiddenOffsets() && "none" === (a.style && a.style.display || n.css(a, "display")) }, n.expr.filters.visible = function(a) { return !n.expr.filters.hidden(a) }; var Rc = /%20/g, Sc = /\[\]$/, Tc = /\r?\n/g, Uc = /^(?:submit|button|image|reset|file)$/i, Vc = /^(?:input|select|textarea|keygen)/i; function Wc(a, b, c, d) { var e; if (n.isArray(b)) n.each(b, function(b, e) { c || Sc.test(a) ? d(a, e) : Wc(a + "[" + ("object" == typeof e ? b : "") + "]", e, c, d) }); else if (c || "object" !== n.type(b)) d(a, b); else for (e in b) Wc(a + "[" + e + "]", b[e], c, d) } n.param = function(a, b) { var c, d = [], e = function(a, b) { b = n.isFunction(b) ? b() : null == b ? "" : b, d[d.length] = encodeURIComponent(a) + "=" + encodeURIComponent(b) }; if (void 0 === b && (b = n.ajaxSettings && n.ajaxSettings.traditional), n.isArray(a) || a.jquery && !n.isPlainObject(a)) n.each(a, function() { e(this.name, this.value) }); else for (c in a) Wc(c, a[c], b, e); return d.join("&").replace(Rc, "+") }, n.fn.extend({ serialize: function() { return n.param(this.serializeArray()) }, serializeArray: function() { return this.map(function() { var a = n.prop(this, "elements"); return a ? n.makeArray(a) : this }).filter(function() { var a = this.type; return this.name && !n(this).is(":disabled") && Vc.test(this.nodeName) && !Uc.test(a) && (this.checked || !X.test(a)) }).map(function(a, b) { var c = n(this).val(); return null == c ? null : n.isArray(c) ? n.map(c, function(a) { return { name: b.name, value: a.replace(Tc, "\r\n") } }) : { name: b.name, value: c.replace(Tc, "\r\n") } }).get() }, serializeJson : function(){ var arr = this.serializeArray(), data = {}, temp; if(arr && arr.length){ for(var i = 0, j = arr.length; i < j; i++){ if(data[arr[i].name]){ temp = jQuery.isArray( data[arr[i].name] ) ? data[arr[i].name] : [data[arr[i].name]]; temp.push(arr[i].value); data[arr[i].name] = temp; } else { data[arr[i].name] = arr[i].value; } } } return data; } }), n.ajaxSettings.xhr = void 0 !== a.ActiveXObject ? function() { return !this.isLocal && /^(get|post|head|put|delete|options)$/i.test(this.type) && $c() || _c() } : $c; var Xc = 0, Yc = {}, Zc = n.ajaxSettings.xhr(); a.ActiveXObject && n(a).on("unload", function() { for (var a in Yc) Yc[a](void 0, !0) }), l.cors = !!Zc && "withCredentials" in Zc, Zc = l.ajax = !!Zc, Zc && n.ajaxTransport(function(a) { if (!a.crossDomain || l.cors) { var b; return { send: function(c, d) { var e, f = a.xhr(), g = ++Xc; if (f.open(a.type, a.url, a.async, a.username, a.password), a.xhrFields) for (e in a.xhrFields) f[e] = a.xhrFields[e]; a.mimeType && f.overrideMimeType && f.overrideMimeType(a.mimeType), a.crossDomain || c["X-Requested-With"] || (c["X-Requested-With"] = "XMLHttpRequest"); for (e in c) void 0 !== c[e] && f.setRequestHeader(e, c[e] + ""); f.send(a.hasContent && a.data || null), b = function(c, e) { var h, i, j; if (b && (e || 4 === f.readyState)) if (delete Yc[g], b = void 0, f.onreadystatechange = n.noop, e) 4 !== f.readyState && f.abort(); else { j = {}, h = f.status, "string" == typeof f.responseText && (j.text = f.responseText); try { i = f.statusText } catch (k) { i = "" } h || !a.isLocal || a.crossDomain ? 1223 === h && (h = 204) : h = j.text ? 200 : 404 } j && d(h, i, j, f.getAllResponseHeaders()) }, a.async ? 4 === f.readyState ? setTimeout(b) : f.onreadystatechange = Yc[g] = b : b() }, abort: function() { b && b(void 0, !0) } } } }); function $c() { try { return new a.XMLHttpRequest } catch (b) {} } function _c() { try { return new a.ActiveXObject("Microsoft.XMLHTTP") } catch (b) {} } n.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function(a) { return n.globalEval(a), a } } }), n.ajaxPrefilter("script", function(a) { void 0 === a.cache && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1) }), n.ajaxTransport("script", function(a) { if (a.crossDomain) { var b, c = z.head || n("head")[0] || z.documentElement; return { send: function(d, e) { b = z.createElement("script"), b.async = !0, a.scriptCharset && (b.charset = a.scriptCharset), b.src = a.url, b.onload = b.onreadystatechange = function(a, c) { (c || !b.readyState || /loaded|complete/.test(b.readyState)) && (b.onload = b.onreadystatechange = null, b.parentNode && b.parentNode.removeChild(b), b = null, c || e(200, "success")) }, c.insertBefore(b, c.firstChild) }, abort: function() { b && b.onload(void 0, !0) } } } }); var ad = [], bd = /(=)\?(?=&|$)|\?\?/; n.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var a = ad.pop() || n.expando + "_" + wc++; return this[a] = !0, a } }), n.ajaxPrefilter("json jsonp", function(b, c, d) { var e, f, g, h = b.jsonp !== !1 && (bd.test(b.url) ? "url" : "string" == typeof b.data && !(b.contentType || "").indexOf("application/x-www-form-urlencoded") && bd.test(b.data) && "data"); return h || "jsonp" === b.dataTypes[0] ? (e = b.jsonpCallback = n.isFunction(b.jsonpCallback) ? b.jsonpCallback() : b.jsonpCallback, h ? b[h] = b[h].replace(bd, "$1" + e) : b.jsonp !== !1 && (b.url += (xc.test(b.url) ? "&" : "?") + b.jsonp + "=" + e), b.converters["script json"] = function() { return g || n.error(e + " was not called"), g[0] }, b.dataTypes[0] = "json", f = a[e], a[e] = function() { g = arguments }, d.always(function() { a[e] = f, b[e] && (b.jsonpCallback = c.jsonpCallback, ad.push(e)), g && n.isFunction(f) && f(g[0]), g = f = void 0 }), "script") : void 0 }), n.parseHTML = function(a, b, c) { if (!a || "string" != typeof a) return null; "boolean" == typeof b && (c = b, b = !1), b = b || z; var d = v.exec(a), e = !c && []; return d ? [b.createElement(d[1])] : (d = n.buildFragment([a], b, e), e && e.length && n(e).remove(), n.merge([], d.childNodes)) }; var cd = n.fn.load; n.fn.load = function(a, b, c) { if ("string" != typeof a && cd) return cd.apply(this, arguments); var d, e, f, g = this, h = a.indexOf(" "); return h >= 0 && (d = a.slice(h, a.length), a = a.slice(0, h)), n.isFunction(b) ? (c = b, b = void 0) : b && "object" == typeof b && (f = "POST"), g.length > 0 && n.ajax({ url: a, type: f, dataType: "html", data: b }).done(function(a) { e = arguments, g.html(d ? n("<div>").append(n.parseHTML(a)).find(d) : a) }).complete(c && function(a, b) { g.each(c, e || [a.responseText, b, a]) }), this }, n.expr.filters.animated = function(a) { return n.grep(n.timers, function(b) { return a === b.elem }).length }; var dd = a.document.documentElement; function ed(a) { return n.isWindow(a) ? a : 9 === a.nodeType ? a.defaultView || a.parentWindow : !1 } n.offset = { setOffset: function(a, b, c) { var d, e, f, g, h, i, j, k = n.css(a, "position"), l = n(a), m = {}; "static" === k && (a.style.position = "relative"), h = l.offset(), f = n.css(a, "top"), i = n.css(a, "left"), j = ("absolute" === k || "fixed" === k) && n.inArray("auto", [f, i]) > -1, j ? (d = l.position(), g = d.top, e = d.left) : (g = parseFloat(f) || 0, e = parseFloat(i) || 0), n.isFunction(b) && (b = b.call(a, c, h)), null != b.top && (m.top = b.top - h.top + g), null != b.left && (m.left = b.left - h.left + e), "using" in b ? b.using.call(a, m) : l.css(m) } }, n.fn.extend({ offset: function(a) { if (arguments.length) return void 0 === a ? this : this.each(function(b) { n.offset.setOffset(this, a, b) }); var b, c, d = { top: 0, left: 0 }, e = this[0], f = e && e.ownerDocument; if (f) return b = f.documentElement, n.contains(b, e) ? (typeof e.getBoundingClientRect !== L && (d = e.getBoundingClientRect()), c = ed(f), { top: d.top + (c.pageYOffset || b.scrollTop) - (b.clientTop || 0), left: d.left + (c.pageXOffset || b.scrollLeft) - (b.clientLeft || 0) }) : d }, position: function() { if (this[0]) { var a, b, c = { top: 0, left: 0 }, d = this[0]; return "fixed" === n.css(d, "position") ? b = d.getBoundingClientRect() : (a = this.offsetParent(), b = this.offset(), n.nodeName(a[0], "html") || (c = a.offset()), c.top += n.css(a[0], "borderTopWidth", !0), c.left += n.css(a[0], "borderLeftWidth", !0)), { top: b.top - c.top - n.css(d, "marginTop", !0), left: b.left - c.left - n.css(d, "marginLeft", !0) } } }, offsetParent: function() { return this.map(function() { var a = this.offsetParent || dd; while (a && !n.nodeName(a, "html") && "static" === n.css(a, "position")) a = a.offsetParent; return a || dd }) } }), n.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(a, b) { var c = /Y/.test(b); n.fn[a] = function(d) { return W(this, function(a, d, e) { var f = ed(a); return void 0 === e ? f ? b in f ? f[b] : f.document.documentElement[d] : a[d] : void(f ? f.scrollTo(c ? n(f).scrollLeft() : e, c ? e : n(f).scrollTop()) : a[d] = e) }, a, d, arguments.length, null) } }), n.each(["top", "left"], function(a, b) { n.cssHooks[b] = Mb(l.pixelPosition, function(a, c) { return c ? (c = Kb(a, b), Ib.test(c) ? n(a).position()[b] + "px" : c) : void 0 }) }), n.each({ Height: "height", Width: "width" }, function(a, b) { n.each({ padding: "inner" + a, content: b, "": "outer" + a }, function(c, d) { n.fn[d] = function(d, e) { var f = arguments.length && (c || "boolean" != typeof d), g = c || (d === !0 || e === !0 ? "margin" : "border"); return W(this, function(b, c, d) { var e; return n.isWindow(b) ? b.document.documentElement["client" + a] : 9 === b.nodeType ? (e = b.documentElement, Math.max(b.body["scroll" + a], e["scroll" + a], b.body["offset" + a], e["offset" + a], e["client" + a])) : void 0 === d ? n.css(b, c, g) : n.style(b, c, d, g) }, b, f ? d : void 0, f, null) } }) }), n.fn.size = function() { return this.length }, n.fn.andSelf = n.fn.addBack, "function" == typeof define && define.amd && define("jquery", [], function() { return n }); window.$ = window.jQuery = n; fd = a.jQuery, gd = a.$; return n.noConflict = function(b) { return a.$ === n && (a.$ = gd), b && a.jQuery === n && (a.jQuery = fd), n }, typeof b === L && (a.jQuery = a.$ = n), n }); });
'use strict'; var ArraySpeciesCreate = require('es-abstract/2019/ArraySpeciesCreate'); var FlattenIntoArray = require('es-abstract/2019/FlattenIntoArray'); var Get = require('es-abstract/2019/Get'); var IsCallable = require('es-abstract/2019/IsCallable'); var ToLength = require('es-abstract/2019/ToLength'); var ToObject = require('es-abstract/2019/ToObject'); module.exports = function flatMap(mapperFunction) { var O = ToObject(this); var sourceLen = ToLength(Get(O, 'length')); if (!IsCallable(mapperFunction)) { throw new TypeError('mapperFunction must be a function'); } var T; if (arguments.length > 1) { T = arguments[1]; } var A = ArraySpeciesCreate(O, 0); FlattenIntoArray(A, O, sourceLen, 0, 1, mapperFunction, T); return A; };
"use strict"; var __imns = function(){ return window; } describe("isBoolean Test Suite", function(){ var adr = __imns(); var obj = {}, arr = []; it("isBoolean is a function", function(){ expect(typeof adr.isBoolean === 'function').toBe(true); }); it("isBoolean: {Boolean} = true", function(){ expect(adr.isBoolean(true)).toBe(true); }); it("isBoolean: {Boolean} = false", function(){ expect(adr.isBoolean(true)).toBe(true); }); it("isBoolean: {String} = false", function(){ expect(adr.isBoolean('true')).toBe(false); }); it("isBoolean: {Number} = false", function(){ expect(adr.isBoolean(0)).toBe(false); }); it("isBoolean: {Number} = false", function(){ expect(adr.isBoolean(1)).toBe(false); }); it("isBoolean: true expression = true", function(){ expect(adr.isBoolean((1 == 1))).toBe(true); }); it("isBoolean: false expression = true", function(){ expect(adr.isBoolean((1 == 2))).toBe(true); }); it("isBoolean: {undefined} = false", function(){ expect(adr.isBoolean(undefined)).toBe(false); }); });
import React, { Component } from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import { Route, Switch, withRouter } from 'react-router-dom'; // APIs import { getNetwork, createComment, createContact, createEndpoint, createIdentifier, createMachineTag, createTag, deleteComment, deleteContact, deleteEndpoint, deleteIdentifier, deleteMachineTag, deleteTag, updateContact, addConstituentDataset, deleteConstituentDataset, } from '../../api/network'; import { canCreate, canUpdate, canDelete, } from '../../api/permissions'; // Wrappers import { AuthRoute } from '../auth'; import Exception404 from '../exception/404'; import PageWrapper from '../hoc/PageWrapper'; import withContext from '../hoc/withContext'; // Configuration import MenuConfig from './menu.config'; // Components import NetworkDetails from './Details'; import { CreationFeedback, ItemHeader, ItemMenu } from '../common'; import { CommentList, ContactList, EndpointList, IdentifierList, MachineTagList, TagList } from '../common/subtypes'; import ConstituentDatasets from './subtypes/ConstituentDatasets'; import Actions from './network.actions'; // Helpers import { getSubMenu } from '../util/helpers'; class Network extends Component { constructor(props) { super(props); this.state = { loading: true, network: null, uuids: [], counts: {}, status: 200, isNew: false, constituentKey: Date.now() }; } componentDidMount() { this.checkRouterState(); // A special flag to indicate if a component was mount/unmount this._isMount = true; if (this.props.match.params.key) { this.getData(); } else { this.setState({ data: null, loading: false }); } } componentWillUnmount() { // A special flag to indicate if a component was mount/unmount this._isMount = false; } getData() { this.setState({ loading: true }); getNetwork(this.props.match.params.key).then(({ data }) => { // If user lives the page, request will return result anyway and tries to set in to a state // which will cause an error if (this._isMount) { // Taken an array of UIDs to check user permissions const uuids = [this.props.match.params.key]; this.setState({ network: data, uuids, loading: false, counts: { contacts: data.contacts.length, endpoints: data.endpoints.length, identifiers: data.identifiers.length, tags: data.tags.length, machineTags: data.machineTags.length, comments: data.comments.length, constituents: data.numConstituents } }); } }).catch(err => { // Important for us due to the case of requests cancellation on unmount // Because in that case the request will be marked as cancelled=failed // and catch statement will try to update a state of unmounted component // which will throw an exception if (this._isMount) { this.setState({ status: err.response.status, loading: false }); if (![404, 500, 523].includes(err.response.status)) { this.props.addError({ status: err.response.status, statusText: err.response.data }); } } }); } refresh = key => { if (key) { this.props.history.push(key, { isNew: true }); } else { this.getData(); } }; updateCounts = (key, value) => { this.setState(state => { return { counts: { ...state.counts, [key]: value } }; }); }; update(error) { // If component was unmounted interrupting changes if (!this._isMount) { return; } if (error) { this.props.addError({ status: error.response.status, statusText: error.response.data }); return; } this.getData(); } checkRouterState() { const { history } = this.props; // If we set router state previously, we'll update component's state and reset router's state if (history.location && history.location.state && history.location.state.isNew) { this.setState({ isNew: true }); const state = { ...history.location.state }; delete state.isNew; history.replace({ ...history.location, state }); } } getTitle = () => { const { intl } = this.props; const { network, loading } = this.state; if (network) { return network.title; } else if (!loading) { return intl.formatMessage({ id: 'newNetwork', defaultMessage: 'New network' }); } return ''; }; addDataset(networkKey, dataset) { addConstituentDataset(networkKey, dataset).then(() => { this.updateConstituents(1); this.props.addSuccess({ status: 200, statusText: this.props.intl.formatMessage({ id: 'beenAdded.constituentDataset', defaultMessage: 'Constituent dataset has been added' }) }); }).catch(error => { this.props.addError({ status: error.response.status, statusText: error.response.data }); }); } deleteDataset(networkKey, datasetKey) { deleteConstituentDataset(networkKey, datasetKey).then(() => { this.updateConstituents(-1); this.props.addSuccess({ status: 200, statusText: this.props.intl.formatMessage({ id: 'beenDeleted.constituentDataset', defaultMessage: 'Constituent dataset has been deleted' }) }); }).catch(error => { this.props.addError({ status: error.response.status, statusText: error.response.data }); }) } updateConstituents = direction => { this.setState(state => { return { constituentKey: Date.now(), // If we generate a new key for the child component, React will rerender it counts: { ...state.counts, constituents: state.counts.constituents + direction } }; }); }; render() { const { match, intl } = this.props; const key = match.params.key; const { network, uuids, loading, counts, status, isNew, constituentKey } = this.state; // Parameters for ItemHeader with BreadCrumbs and page title const listName = intl.formatMessage({ id: 'networks', defaultMessage: 'Networks' }); const submenu = getSubMenu(this.props); const pageTitle = network || loading ? intl.formatMessage({ id: 'title.network', defaultMessage: 'Network | GBIF Registry' }) : intl.formatMessage({ id: 'title.newNetwork', defaultMessage: 'New network | GBIF Registry' }); const title = this.getTitle(); return ( <React.Fragment> <ItemHeader listType={[listName]} title={title} submenu={submenu} pageTitle={pageTitle} status={status} loading={loading} usePaperWidth > {network && ( <Actions network={network} onChange={error => this.update(error)}/> )} </ItemHeader> {isNew && !loading && ( <CreationFeedback title={<FormattedMessage id="beenCreated.network.title" defaultMessage="Network has been created successfully!" />} /> )} <PageWrapper status={status} loading={loading}> <Route path="/:type?/:key?/:section?" render={() => ( <ItemMenu counts={counts} config={MenuConfig} isNew={network === null}> <Switch> <Route exact path={`${match.path}`} render={() => <NetworkDetails network={network} refresh={key => this.refresh(key)} /> }/> <Route path={`${match.path}/contact`} render={() => <ContactList contacts={network.contacts} createContact={data => createContact(key, data)} updateContact={data => updateContact(key, data)} deleteContact={itemKey => deleteContact(key, itemKey)} canCreate={() => canCreate('network', key, 'contact')} canUpdate={data => canUpdate('network', key, 'contact', data.key)} canDelete={itemKey => canDelete('network', key, 'contact', itemKey)} updateCounts={this.updateCounts} /> }/> <Route path={`${match.path}/endpoint`} render={() => <EndpointList endpoints={network.endpoints} createEndpoint={data => createEndpoint(key, data)} deleteEndpoint={itemKey => deleteEndpoint(key, itemKey)} canCreate={() => canCreate('network', key, 'endpoint')} canDelete={itemKey => canDelete('network', key, 'endpoint', itemKey)} updateCounts={this.updateCounts} /> }/> <Route path={`${match.path}/identifier`} render={() => <IdentifierList identifiers={network.identifiers} createIdentifier={data => createIdentifier(key, data)} deleteIdentifier={itemKey => deleteIdentifier(key, itemKey)} canCreate={() => canCreate('network', key, 'identifier')} canDelete={itemKey => canDelete('network', key, 'identifier', itemKey)} updateCounts={this.updateCounts} /> }/> <Route path={`${match.path}/tag`} render={() => <TagList tags={network.tags} createTag={data => createTag(key, data)} deleteTag={itemKey => deleteTag(key, itemKey)} canCreate={() => canCreate('network', key, 'tag')} canDelete={itemKey => canDelete('network', key, 'tag', itemKey)} updateCounts={this.updateCounts} /> }/> <Route path={`${match.path}/machineTag`} render={() => <MachineTagList machineTags={network.machineTags} createMachineTag={data => createMachineTag(key, data)} deleteMachineTag={itemKey => deleteMachineTag(key, itemKey)} canCreate={() => canCreate('network', key, 'machineTag')} canDelete={itemKey => canDelete('network', key, 'machineTag', itemKey)} updateCounts={this.updateCounts} /> }/> <AuthRoute path={`${match.path}/comment`} component={() => <CommentList comments={network.comments} uuids={[]} createComment={data => createComment(key, data)} deleteComment={itemKey => deleteComment(key, itemKey)} canCreate={() => canCreate('network', key, 'comment')} canDelete={itemKey => canDelete('network', key, 'comment', itemKey)} updateCounts={this.updateCounts} /> } roles={'REGISTRY_ADMIN'} /> <Route path={`${match.path}/constituents`} render={() => <ConstituentDatasets key={constituentKey} network={network} uuids={uuids} addDataset={(networkKey, dataset) => this.addDataset(networkKey, dataset)} deleteDataset={(networkKey, datasetKey) => this.deleteDataset(networkKey, datasetKey)} /> }/> <Route component={Exception404}/> </Switch> </ItemMenu> )}/> </PageWrapper> </React.Fragment> ); } } const mapContextToProps = ({ addError, addSuccess }) => ({ addError, addSuccess }); export default withContext(mapContextToProps)(withRouter(injectIntl(Network)));
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[6],{2514:function(e,n,t){"use strict";var o=function(){var e=this,n=e.$createElement,t=e._self._c||n;return t("div",[t("section",{staticClass:"page-header"},[t("div",{staticClass:"donate"},[t("a",{attrs:{href:e.donateUrl,target:"_blank",title:"Donate"}},[t("i",{staticClass:"fas fa-heart",staticStyle:{color:"red"}})])]),t("div",{staticClass:"text-h1 project-name"},[e._v(e._s(e.title))]),t("div",{staticClass:"text-h2 project-tagline"},[e._v(e._s(e.tagline))]),t("q-btn",{staticClass:"btn",attrs:{type:"a",href:e.locationUrl,target:"_blank",label:"View on GitHub","no-caps":"",flat:""}}),t("q-btn",{staticClass:"btn",attrs:{to:"/docs",label:"Docs","no-caps":"",flat:""}}),t("q-btn",{staticClass:"btn",attrs:{to:"/examples",label:"Examples","no-caps":"",flat:""}}),e.hasInteractiveDemo?t("q-btn",{staticClass:"btn",attrs:{to:"/demo",label:"Interactive Demo","no-caps":"",flat:""}}):e._e(),t("q-btn",{staticClass:"btn",attrs:{type:"a",href:e.donateUrl,target:"_blank",label:"Donate","no-caps":"",flat:""}}),t("div",{staticClass:"row justify-evenly items-center q-ma-sm"},[t("div",{staticClass:"quasar"},[e._v(e._s(e.quasarDesc))]),t("div",{staticClass:"byline"},[e._v(e._s(e.byline)+" "),t("a",{attrs:{href:e.bylineTwitter,target:"_blank",title:"Twitter"}},[t("i",{staticClass:"fab fa-twitter"})])])])],1),t("main",{staticClass:"flex flex-start justify-center inset-shadow"},[t("div",{staticClass:"q-pa-md col-12-sm col-8-md col-6-lg inset-shadow",staticStyle:{width:"100%",height:"3px"}}),t("div",{staticClass:"q-pa-md col-12-sm col-8-md col-6-lg shadow-1",staticStyle:{"max-width":"800px",width:"100%"}},[e._t("default")],2)])])},a=[],i={name:"Hero",data:function(){return{title:"QMarkdown",tagline:"Inline markdown for your Quasar App",byline:"Created and maintained by Jeff Galbraith",bylineTwitter:"https://twitter.com/jgalbraith64",quasarDesc:"A Quasar Framework Component and App Extension",locationUrl:"https://github.com/quasarframework/quasar-ui-qmarkdown",donateUrl:"https://github.com/sponsors/hawkeye64",hasInteractiveDemo:!0}}},r=i,s=t("2877"),l=t("9c40"),d=t("eebe"),c=t.n(d),h=Object(s["a"])(r,o,a,!1,null,null,null);n["a"]=h.exports;c()(h,"components",{QBtn:l["a"]})},"8b24":function(e,n,t){"use strict";t.r(n);var o=function(){var e=this,n=e.$createElement,t=e._self._c||n;return t("hero",[t("q-markdown",{attrs:{src:e.markdown,toc:""},on:{data:e.onToc}}),t("json-api-viewer",{attrs:{title:"QMarkdown API",json:e.json}}),t("q-markdown",[e._v("\n# Donate\nIf you appreciate the work that went into this, please consider donating to [Quasar](https://donate.quasar.dev) or [Jeff](https://github.com/sponsors/hawkeye64).\n\n---\n\nThis page created with [QMarkdown](https://quasarframework.github.io/quasar-ui-qmarkdown), another great Quasar App Extension.\n ")]),t("q-page-scroller",{attrs:{position:"bottom-right","scroll-offset":150,offset:[18,18]}},[t("q-btn",{class:{"text-black bg-grey-4":e.$q.dark.isActive,"text-white bg-primary":!e.$q.dark.isActive},attrs:{fab:"",icon:"keyboard_arrow_up"}})],1)],1)},a=[],i=t("2514"),r="QMarkdown\n===\n\nQMarkdown is a Quasar component as well as a [Quasar App Extension](https://v1.quasar.dev/app-extensions/introduction). It provides the ability for your Quasar app to display markdown. If you don't know how to use Markdown or need a refresher, this site is recommended: [Markdown Guide](https://www.markdownguide.org/).\n\n# Features\n\n## Markdown Constructs\n\n- Abbreviations\n- Blockquotes\n- Code and Code Highlighting\n- Containers\n- Definition Lists\n- Emojies\n- Emphasis\n- Footnotes\n- Headings\n- Images\n- Inserts\n- Links (+ Anchor Links)\n- Lists\n- Marks\n- Rules\n- Subscript/Superscript\n- Tables\n- Tasklists\n- Titles\n- Typography\n\n## Loaders\nThe loaders are only available if you installed via the QMarkdown App Extension.\n\n- markdown (.md) loader that can load your markdown as text to be processed by QMarkdown\n- vue+markdown (.vmd) loader that can process markdown, then hand off to Vue to be processed\n\n## Front-Matter\n- The front-matter functonality is only available to vue+markdown (`.vmd`) files.\n\n## Utility Functions\n- `getTagParts` that can process a Vue SFC file and return the `template`, `script` and `style` parts\n\n# Installation Types\n\n## Quasar CLI\n\n**App Extension**\n\n:::\n#### Install\n\nTo add as an App Extension to your Quasar application, run the following (in your Quasar app folder):\n```\nquasar ext add @quasar/qmarkdown\n```\n\n#### Uninstall\n\nTo remove as an App Extension from your Quasar application, run the following (in your Quasar app folder):\n```\nquasar ext remove @quasar/qmarkdown\n```\n\n#### Describe\nWhen installed as an App Extension, you can use `quasar describe QMarkdown`\n:::\n\n**OR**:\n\n:::\nCreate and register a boot file:\n\n```js\nimport Vue from 'vue'\nimport Plugin from '@quasar/quasar-ui-qmarkdown'\nimport '@quasar/quasar-ui-qmarkdown/dist/index.css'\n\nVue.use(Plugin)\n```\n:::\n\n**OR**:\n\n:::\n```html\n<style src=\"@quasar/quasar-ui-qmarkdown/dist/index.css\"></style>\n\n<script>\nimport { QMarkdown } from '@quasar/quasar-ui-qmarkdown'\n\nexport default {\n components: {\n QMarkdown\n }\n}\n<\/script>\n```\n:::\n\n## Vue CLI project\n\n:::\n```js\nimport Vue from 'vue'\nimport Plugin from '@quasar/quasar-ui-qmarkdown'\nimport '@quasar/quasar-ui-qmarkdown/dist/index.css'\n\nVue.use(Plugin)\n```\n:::\n\n**OR**:\n\n:::\n```html\n<style src=\"@quasar/quasar-ui-qmarkdown/dist/index.css\"></style>\n\n<script>\nimport { QMarkdown } from '@quasar/quasar-ui-qmarkdown'\n\nexport default {\n components: {\n QMarkdown\n }\n}\n<\/script>\n```\n:::\n\n## UMD variant\n\nExports `window.QMarkdown`.\n\nAdd the following tag(s) after the Quasar ones:\n\n:::\n```html\n<head>\n \x3c!-- AFTER the Quasar stylesheet tags: --\x3e\n <link href=\"https://cdn.jsdelivr.net/npm/@quasar/quasar-ui-qmarkdown/dist/index.min.css\" rel=\"stylesheet\" type=\"text/css\">\n</head>\n<body>\n \x3c!-- at end of body, AFTER Quasar script(s): --\x3e\n <script src=\"https://cdn.jsdelivr.net/npm/@quasar/quasar-ui-qmarkdown/dist/index.umd.min.js\"><\/script>\n</body>\n```\nIf you need the RTL variant of the CSS, then go for the following (instead of the above stylesheet link):\n```html\n<link href=\"https://cdn.jsdelivr.net/npm/@quasar/quasar-ui-qmarkdown/dist/index.rtl.min.css\" rel=\"stylesheet\" type=\"text/css\">\n```\n:::\n\n## Testing on Codepen\n[UMD Example on Codepen](https://codepen.io/Hawkeye64/pen/ExxzdMp?editors=1010)\n\n\n# Docs\nCan be found [here](https://quasarframework.github.io/quasar-ui-qmarkdown).\n\n# Examples\nCan be found [here](https://quasarframework.github.io/quasar-ui-qmarkdown/examples).\n\n# Interactive Demo\nCan be found [here](https://quasarframework.github.io/quasar-ui-qmarkdown/demo).\n\n# Demo (source) Project\nCan be found [here](https://github.com/quasarframework/quasar-ui-qmarkdown/tree/master/demo).\n\n---\n\n# Working with markdown\n::: tip\nWhen working with markdown, you must always left-justify the content to avoid it being converted to blockquotes or other issues.\n:::\n\nThere are two way to pass your markdown content to QMarkdown: Vue slot or property.\n\nQMarkdown App Extension also comes with a Webpack loader that allows you to import your markdown directly into your code.\n\nYou have the ability to get the TOC (Table of Contents), if one is generated, and display that as well.\n\n## Using the `src` property\nIt's as simple as:\n```html\n<q-markdown src=\":::\\nThis is a **test** of markdown\\n:::\"></q-markdown>\n```\n**Output**:\n\n:::\nThis is a **test** of markdown\n:::\n\n\n## Using a Vue slot\nYou can simply use a Vue slot to display markdown.\n\nIn your HTML:\n```html\n<q-markdown>\n:::\nPut your markdown here\n\nClassic markup: :wink: :joy: :cry: :angel: :heart: :beers: :laughing: :yum:\n\nShortcuts (emoticons): :-) :-( 8-) ;)\n:::\n</q-markdown>\n```\n**Output**:\n\n:::\nPut your markdown here\n\nClassic markup: :wink: :joy: :cry: :angel: :heart: :beers: :laughing: :yum:\n\nShortcuts (emoticons): :-) :-( 8-) ;)\n:::\n\nA couple of caveats to remember.\n\nAlways keep your markdown left justified. It does not have to line up with your HTML. This way, the markdown processor won't process it as a blockquote.\n\nIf you start getting weird linting errors, consider a markdown file and importing it.\n\n## Importing Markdown\nQMarkdown App Extesnion comes with a Webpack loader for importing markdown files directly into your code.\n\nIn your JavaScript:\n```js\nimport markdown from '../markdown/calendar.md'\n\nexport default {\n data () {\n return {\n markdown: markdown\n }\n },\n...\n```\n\nAnd, in your HTML:\n```html\n<q-markdown :src=\"markdown\" />\n```\n\nOr, alternatively, you can import it in your vue-router `routes.js` file:\n\n```js\nconst routes = [\n {\n path: '/',\n component: () => import('layouts/MyLayout.vue'),\n children: [\n { path: '', component: () => import('pages/Index.vue') },\n { path: 'contact', component: () => import('pages/contact.vmd') }\n ]\n }\n]\n```\n\n# Setting up Table of Contents\nYou enable a TOC by setting `:toc=\"true\"`. The data in the TOC is based on HTML Headings (H1-H6). You can change the number of headings that you are interested in by using the `toc-start` and `toc-end` properties.\n\nTo get the data for the TOC, you must use the `@data` event.\n\nHTML\n```html\n<q-markdown :src=\"markdown\" toc @data=\"onToc\" />\n```\n\nJavaScript:\n```js\nmethods: {\n onToc (toc) {\n this.toc = toc\n }\n}\n```\n\nThe TOC data looks like this:\n```\n[\n {id: 'h2-Heading', label: 'h2 Heading', level: 2, children: []},\n {id: 'h3-Heading', label: 'h3 Heading', level: 3, children: []}\n]\n```\n\nIf you desire a hierarchical tree of data instead, do the following:\n\nHTML\n```html\n<q-markdown ref=\"markdown\" :src=\"markdown\" toc @data=\"onToc\" />\n```\n\nJavaScript:\n```js\nmethods: {\n onToc (toc) {\n this.toc = this.$refs.markdown.makeTree(toc)\n }\n}\n```\n\nThe TOC data will be transformed to the following:\n```\n[\n {id: 'h2-Heading', title: 'h2 Heading', level: 2, children: [\n {id: 'h3-Heading', title: 'h3 Heading', level: 3, children: []}\n ]}\n\n]\n```\n\n# Importing Vue+Markdown (.vmd)\n\nYou are able to mix Vue (SFC: single-file component) and Markdown together. This must be in a file with an extension of `.vmd` (vue+markdown). The markdown can only reside in the `<template>` section of the Vue SFC file.\n\nThe minimal viable `.vmd` file must contain a `<template>` section. All other sections are optional.\n\nExample:\n\n```html\n<template>\n <div class=\"q-pa-md q-gutter-sm q-markdown\">\n\nQMarkdown\n===\n\nQMarkdown is a [Quasar App Extension](https://v1.quasar.dev/app-extensions/introduction). It provides the ability for your web app to display markdown.\n\n# Features\n... // the rest of the markdown\n</template>\n```\n\nAs you may have noticed, your HTML code should add the `q-markdown` class to the wrapper html in order to get all proper syntax highlighting.\n\nNow, as far as getting it to be displayed on your page, do the following in your `<script>` section:\n\n```js\nimport markdownVue from '../markdown/markdown.vmd'\n\nexport default {\n\n components: {\n markdownVue\n },\n\n```\n\nand in your HTML `<template>` section:\n\n```html\n<template>\n <markdown-vue />\n</template>\n```\n\n## TOC with Vue+Markdown\n\nIf you would like to generate a TOC (Table of Contents) derived from the header components (h1, h2, h3, etc), you will need to add some code to your `.vmd` file so it can be accepted. Just add the following to your `data ()` instance in the `.vmd`:\n\n```\n data () {\n return {\n // eslint-disable-next-line\n tocData: []\n }\n },\n```\n\nThe Vue+Markdown (`.vmd`) loader will replace the `tocData: []`, if found, and add the TOC data.\n\n::: warning\nNotice the commented line `eslint-disable-next-line`? The data added is not formatted and eslint will complain during compilation time. If you use something other than eslint, you may need to add an appropriate **ignore** statement for your linter.\n:::\n\nFinally, if your TOC data is used elsewhere, like the right-drawer in these docs, you need a way of getting it there and if you are using a Vuex store, this is relative easy:\n\n```\n mounted () {\n this.toc = this.tocData\n },\n\n computed: {\n toc:\n {\n get () {\n return this.$store.state.common.toc\n },\n set (toc) {\n this.$store.commit('common/toc', toc)\n }\n }\n }\n```\n\n## Vue+Markdown Issues\nSo far, a couple of issues have been found.\n1. When using `-` over multiple rows for an unorder list, the markdown processor sometimes is not putting in the end `</ul>` tag which causes an issue with Vue transpiling. You can make this an ordered list with `1.` notation.\n2. When using text interpolation, better known as moustache or handle bars, the Vue Loader sees these in the markdown and tries to do substitution which will cause Vue Loader to complain that the variable does not exist. You can fix this, by taking the text from the interpolation and use the `v-text=\"my text\"` instead (like a `span` tag).\n\n## Vue+Markdown Comments\nVue+Markdown is experimental. There are a few other authors doing it, like **Vue Press** and **Sable**, as well as the **Quasar Documentation**. However, none of them are using a `.vmd` extension. This was used to distinguish `vue+markdown` from regular markdown. As such, your favorite editor may not have syntax highlighting that works with `.vmd` files. Hopefully, in the future, this will be resolved.\n\n## Front-Matter with Vue+Markdown\nFront-Matter is a way of extracting meta data from the beginning of a file and converting it to object format. The format for Front-Matter is in YAML format.\n\n::: tip\nAll Front-Matter meta data defined in your .vmd file **must** be at the top of the file.\n:::\n\nAn example of Front-Matter YAML:\n\n```yaml\n---\ntitle: QMarkdown Docs\ndesc: This is the documentation for QMarkdown\n---\n```\n\nThis will be converted to:\n\n```js\n{\n title: \"QMarkdown Docs\",\n desc: \"This is the documentation for QMarkdown\"\n}\n```\n\nThis is injected into your Vue data by having the following:\n\n```js\n data () {\n return {\n // eslint-disable-next-line\n frontMatter: {}\n }\n },\n```\n\nThe Vue+Markdown (`.vmd`) loader will replace the `frontMatter: {}`, if found, and add the Front-Matter data.\n\n::: warning\nNotice the commented line `eslint-disable-next-line`? The data added is not formatted and eslint will complain during compilation time. If you use something other than eslint, you may need to add an appropriate **ignore** statement for your linter.\n:::\n\nFinally, you can use the Front-Matter data like this:\n\n```js\n mounted () {\n document.title = this.frontMatter.title\n },\n```\n\n## Importing markdown in a VMD (Vue+Markdown)\nDid you know you can also import markdown in a `.vmd` component?\n\nHere is an example of how to do just that:\n\n```html\n---\ntitle: Contact us\ndesc: Our contact details\n---\n\n<template>\n<div>\n <qm-toc ref=\"qm-toc\" :toc-tree=\"tocTree\"></qm-toc>\n <q-markdown\n :src=\"markdown\"\n toc\n :toc-start=\"2\"\n :toc-end=\"3\"\n @data=\"onToc\"\n ref=\"markdown\"\n class=\"q-pa-md\"\n />\n</div>\n</template>\n\n<script>\nimport mdMixin from 'src/md/md-mixin'\nimport markdown from './contact.md'\n\nexport default {\n mixins: [mdMixin],\n\n data () {\n return {\n // eslint-disable-next-line\n frontMatter: {},\n // eslint-disable-next-line\n tocData: [],\n\n markdown\n }\n }\n}\n<\/script>\n```\n\nNotice the mixin used?\n\nHere is the code for that to generate your table of contents:\n```html\n<template>\n \x3c!-- We display the TOC only if it is not empty (v-if) and the screen is wide\n enough (class: gt-xs). We apply a medium margin: 'q-ma-md' --\x3e\n <q-card\n v-if=\"tocTree.length\"\n class=\"gt-xs float-right q-ma-md\"\n flat\n bordered\n >\n \x3c!-- We use the 'horizontal' to remove paddings --\x3e\n <q-card-section horizontal>\n \x3c!-- We use 'q-expansion-item' to enable toggling (hide/show) the TOC --\x3e\n <q-expansion-item\n default-opened\n icon=\"toc\"\n label=\"Table of contents\"\n >\n <q-separator />\n <q-list>\n \x3c!-- loop through items of tocTree --\x3e\n <template v-for=\"item in tocTree\">\n \x3c!-- if the item does not have children we use 'q-item' --\x3e\n <q-item\n v-if=\"!item.children.length\"\n :key=\"item.id\"\n :to=\"`#${item.id}`\"\n >\n <q-item-section>{{ item.label }}</q-item-section>\n </q-item>\n \x3c!-- if the item has children we use 'q-expansion-item' to enable\n toggling (hiding/showing) them --\x3e\n <q-expansion-item\n v-else\n :key=\"item.id\"\n default-opened\n :label=\"item.label\"\n :to=\"`#${item.id}`\"\n >\n \x3c!-- children are displayed in a q-list below their parent --\x3e\n <q-list>\n \x3c!-- each child is indented a little (inset-level).\n Dense mode uses less space --\x3e\n <q-item\n v-for=\"childItem in item.children\"\n :key=\"childItem.id\"\n dense\n :inset-level=\"0.2\"\n :to=\"`#${childItem.id}`\"\n >\n <q-item-section>{{ childItem.label }}</q-item-section>\n </q-item>\n </q-list>\n </q-expansion-item>\n </template>\n </q-list>\n </q-expansion-item>\n </q-card-section>\n </q-card>\n</template>\n\n<script>\nexport default {\n props: {\n // 'tocTree' will be provided by the component using QmToc (vmd components)\n tocTree: {\n type: Array,\n default () { return [] }\n }\n }\n}\n<\/script>\n\n<style lang=\"sass\">\n// When navigating (scrolling) to an anchor and to avoid that the anchor gets\n// hidden by the fixed page header we offset the scrolling by the header height.\n.q-markdown [class^=\"q-markdown--heading-h\"]\n scroll-margin-top: $toolbar-min-height\n</style>\n```\n\n# Overriding Links\nQMarkdown requires the `Material Design` font for external links. If you wish to override this to avoid the font dependency or provide a different icon, you can override this sass:\n\n```sass\n.q-markdown--link-external\n &:after\n content: '\\e895'\n font-family: Material Icons\n```\nTo change colors of your links you can do the following:\n\n```sass\n.q-markdown--link\n color: blue\n &:hover\n color: green\n```\n\nAnd to change it for dark mode:\n\n```sass\n.body--dark\n .q-markdown--link\n color: $green-10\n &:hover\n color: yellow\n```\n\n# Anchor Links\nAn **Anchor Link** is simply a link that points to an element on a page with a corresponding **id**.\n\nTo show an achor link on this page, to the **Installation Types** (above), then you must use the slugified verion that matches the id, which in this case is **Installation-Types** (notice the hypen).\n\nYou do it in Markdown like this:\n```\n[Jump to Installation Types](#installation-types)\n```\n\nNotice, that for the current page only, you use the hashtag to start. This produces the following (be aware you will jump to **Installation Types** if you click it):\n\n[Jump to Installation Types](#installation-types)\n\nAnother type of anchor link automatically generated by QMarkdown is on Headings. To turn it off, use the `no-heading-anchor-links` property. This is also controlled by the `toc-start` and `toc-end` properties to determine which levels of heading will be turned into anchor links.\n\n# Extracting Vue SFC parts\nAdditionally, QMarkdown comes with a utility function to extract SFC files into their tag parts (where tag is one of `template`, `script` and `style`). To import, do the following:\n\n```js\nimport { getTagParts } from '@quasar/quasar-ui-qmarkdown'\n```\n\nAnd then, you can use it like this:\n\n```\n mounted () {\n // eslint-disable-next-line import/no-webpack-loader-syntax\n const results = getTagParts(require('!!raw-loader!../components/Hero.vue').default)\n\n console.log('template', results.template)\n console.log('script', results.script)\n console.log('css', results.css)\n },\n```\n\nThis makes use of the `raw-loader` Webpack loader. The exclamations (or bang characters) are needed to tell Webpack to override the default loader.\n\n::: tip\n`raw-loader` is already loaded via QMarkdown App Extension and you do not need to install it. If you do not install via the App extension, just include `raw-loader` in your `devDependencies`.\n:::\n\nNow, you will have access to the tag parts of the Vue file.\n\n# Extending\n\n## Extending Markdown-it!\nYou can use the `extend` property to extend the Markdown-it! markdown processor. The extend function takes a single argument of the md (markdown) instance.\n\nNow, you can extend QMarkdown with either your own code or Markdown-it! [plugins](https://www.npmjs.com/search?q=keywords:markdown-it-plugin). Please read the Markdown-It [documentation](https://github.com/markdown-it/markdown-it#readme) on how to do this.\n\nSyntax:\n\n```html\n<q-markdown :extend=\"extendMarkdown\" />\n```\n\n```js\nmethods: {\n // to extend links\n extendMarkdown (md) {\n md.renderer.rules.link_open = (tokens, idx, options, env, self) => {\n const token = tokens[idx]\n\n const hrefIndex = token.attrIndex('href')\n if (token.attrs[hrefIndex][1][0] === '/') {\n token.attrSet('class', 'q-markdown--link q-markdown--link-local')\n } else {\n token.attrSet('class', 'q-markdown--link q-markdown--link-external')\n token.attrSet('target', '_blank')\n }\n\n return self.renderToken(tokens, idx, options)\n }\n }\n}\n```\n\n## Extend the Code Highlighting\nQMarkdown uses **Prism** for code highlighting. You can use the `extendPrism` property with a function.\n\nSyntax:\n\n```html\n<q-markdown :extendPrism=\"extendPrism\" />\n```\n\n```js\nmethods: {\n // to extend Prism\n extendPrism (Prism) {\n // this uses the 'autoloader' plugin\n // https://prismjs.com/plugins/autoloader/\n Prism.plugins.autoloader.languages_path = 'path/to/grammars/'\n }\n}\n```\n\nHowever, we have seen issues with this. If all you want to do is add more languages, you can do it easily. `Prism` sets itself up as a global window object. All official language load themselves into `Prism`.\n\nLet's say you want to load the `java` language for `Prism`:\n```js\nimport 'prismjs/components/prism-java'\n```\nYep, that's all there is to it. Simple.\n\n# Copy to Clipboard\n\nAs of v1.3.0, QMarkdown has the ability to allow your viewers to **Copy to Clipboard**. It all begins with using the `show-copy` property; this turns it all on. When text is copied to the clipboard, a Quasar dialog will be displayed telling end-user it was copied to clipboard. \n\n::: warning\nFor the notification to work, add the `Dialog` plugin to your quasar.conf.js\n:::\n\n::: tip\nIf you are showing code blocks, you should turn off line numbers with the `no-line-numbers` property. Leaving line numbers in does not work as you would expect as you'll get a column of numbers and then your content.\n:::\n\nOther properties you can use to modify things:\n\n| Property | Description |\n| -------- | ----------- |\n| show-copy | Add behavior that allows end-users to copy content to the clipboard |\n| copy-icon | Name of icon from icon font or svg icon to use as the copy icon |\n| no-copy-tooltip | Turn off the tooltip associated with the copy icon. |\n| copy-tooltip-text | Replacement text for the tooltip. Default: **Copy to Clipboard** |\n| copy-response-text | Replacement text for the response. Default: **Copied to Clipboard** |\n",s=t("fd03"),l={name:"PageIndex",components:{Hero:i["a"]},data:function(){return{markdown:r,json:s}},computed:{toc:{get:function(){return this.$store.state.common.toc},set:function(e){this.$store.commit("common/toc",e)}}},methods:{onToc:function(e){e.push({id:"QMarkdown-API",label:"QMarkdown API",level:1,children:Array(0)}),e.push({id:"Donate",label:"Donate",level:1,children:Array(0)}),this.toc=e}}},d=l,c=t("2877"),h=t("5096"),p=t("9c40"),m=t("eebe"),u=t.n(m),y=Object(c["a"])(d,o,a,!1,null,null,null);n["default"]=y.exports;u()(y,"components",{QPageScroller:h["a"],QBtn:p["a"]})},fd03:function(e){e.exports=JSON.parse('{"type":"component","meta":{"docsUrl":"https://quasarframework.github.io/quasar-ui-qmarkdown/docs"},"props":{"src":{"type":"String","category":"model","desc":"[optional] Pass markdown in as a property","examples":["src=\\"Classic markup: :wink: :joy: :cry: :angel: :heart: :beers: :laughing: :yum:\\""]},"no-abbreviation":{"type":"Boolean","category":"content","desc":"Disable abbreviation conversion"},"no-blockquote":{"type":"Boolean","category":"content","desc":"Disable blockquote conversion"},"no-breaks":{"type":"Boolean","category":"content","desc":"Disable conversion of \'\\\\n\' into <br>"},"no-container":{"type":"Boolean","category":"content","desc":"Disable container conversion"},"no-deflist":{"type":"Boolean","category":"content","desc":"Disable definition list conversion"},"no-emoji":{"type":"Boolean","category":"content","desc":"Disable emojie conversion"},"no-footnote":{"type":"Boolean","category":"content","desc":"Disable footnote conversion"},"no-highlight":{"type":"Boolean","category":"content","desc":"Disable code highlighter"},"no-html":{"type":"Boolean","category":"content","desc":"Disable HTML tags in source"},"no-image":{"type":"Boolean","category":"content","desc":"Disable image conversion"},"no-insert":{"type":"Boolean","category":"content","desc":"Disable insert conversion"},"no-line-numbers":{"type":"Boolean","category":"content","desc":"Disable line numbers on code blocks"},"no-link":{"type":"Boolean","category":"content","desc":"Disable conversion of links"},"no-linkify":{"type":"Boolean","category":"content","desc":"Disable auto-convert URL-like text to links"},"no-heading-anchor-links":{"addedIn":"v1.4.0","type":"Boolean","category":"content","desc":"Your headings will automatically be turned into anchor links, unless you use this property (default is H1-H3)"},"no-mark":{"type":"Boolean","category":"content","desc":"Disable mark conversion"},"no-subscript":{"type":"Boolean","category":"content","desc":"Disable subscript conversion"},"no-superscript":{"type":"Boolean","category":"content","desc":"Disable superscript conversion"},"no-tasklist":{"type":"Boolean","category":"content","desc":"Disable tasklist conversion"},"no-typographer":{"type":"Boolean","category":"content","desc":"Disable language-neutral replacement + quotes beautification"},"line-number-alt":{"type":"String","category":"content","desc":"Provide an alternative character to be used instead of line numbers - must be 1 char in length","examples":["line-number-alt=\\"$\\"","line-number-alt=\\">\\""]},"toc":{"type":"Boolean","category":"behavior","desc":"Set to true if you want a TOC automatically generated"},"toc-start":{"type":"Number","category":"behavior","desc":"The starting Header number for generating a TOC","values":[1,2,3,4,5]},"toc-end":{"type":"Number","category":"behavior","desc":"The ending Header number for generating a TOC. Must be greater than tocStart","values":[2,3,4,5,6]},"task-lists-enable":{"type":"Boolean","category":"content","desc":"Set to true to enable (not read-only) Task Lists"},"task-lists-label":{"type":"Boolean","category":"style","desc":"Set to true to wrap the rendered list items in a <label> element for UX purposes"},"task-lists-label-after":{"type":"Boolean","category":"style","desc":"To add the label after the checkbox (requires `task-lists-label` to be set to `true`)"},"extend":{"type":"Function","category":"extend","desc":"Used to extend the markdown processor. You can use any \'markdown-it\' plugin or write your own","params":{"md":{"type":"Object","desc":"The `markdown-it` instance"}},"examples":[":extend=\\"extendMarkdownFn\\"",":extend=\\"(md) => extendMarkdownFn(md)\\""],"returns":null},"extend-prism":{"type":"Function","category":"extend","addedIn":"v1.0.0","desc":"Used to extend the [Prism](https://prismjs.com/extending.html) code highlighter","params":{"Prism":{"type":"Object","desc":"The `Prism` instance"}},"examples":[":extendPrism=\\"extendPrismFn\\"",":extendPrism=\\"(Prism) => extendPrismFn(Prism)\\""],"returns":null},"content-class":{"type":["Array","String","Object"],"category":"style","desc":"Class definitions to be attributed to the markdown container","examples":["my-special-class",":content-class=\\"{ \'my-special-class\': <condition> }\\""]},"content-style":{"type":["Array","String","Object"],"category":"style","desc":"Style definitions to be attributed to the markdown container","examples":["background-color: #ff0000",":content-style=\\"{ backgroundColor: \'#ff0000\' }\\""]},"no-noopener":{"addedIn":"v1.2.0","type":"Boolean","category":"behavior","desc":"All external links will have the `rel=\\"noopener\\" applied if this is not set"},"no-noreferrer":{"addedIn":"v1.2.0","type":"Boolean","category":"behavior","desc":"All external links will have the `rel=\\"noreferrer\\" applied if this is not set"},"show-copy":{"addedIn":"v1.3.0","type":"Boolean","category":"behavior","desc":"Use this property to turn on \\"Copy to Clipboard\\" functionality"},"copy-icon":{"addedIn":"v1.3.0","type":"String","category":"behavior","desc":"Change the default icon used for Copy to Clipboard","examples":["copy-icon=\\"copy\\"",":copy-icon=\\"matCopy\\""]},"no-copy-tooltip":{"addedIn":"v1.3.0","type":"Boolean","category":"behavior","desc":"Turns off the tooltip associated with the **Copy to Clipboard** icon"},"copy-tooltip-text":{"addedIn":"v1.3.0","type":"String","category":"behavior","desc":"Change the tooltip text associated with the **Copy to Clipboard** icon","default":"Copy to clipboard","examples":["copy-tooltip-text=\\"Click here for content to be copied to the clipboard\\"",":copy-tooltip-text=\\"$t(\'copy-tooltip-text\')\\""]},"copy-response-text":{"addedIn":"v1.3.0","type":"String","category":"behavior","desc":"Change the response text associated with the **Copy to Clipboard** icon (note: you **must** have the `dialog` plugin added to your quasar.conf.js)","default":"Copied to clipboard","examples":["copy-response-text=\\"The content was copied to the clipboard\\"",":copy-response-text=\\"$t(\'copy-response-text\')\\""]}},"slots":{"default":{"desc":"This is the default slot to be used for markdown"}},"events":{"toc":{"desc":"If `toc` property is `true` then if a TOC is generated it is emitted via this event","params":{"tocData":{"type":"Array","tsType":"TocDefinitionArray","desc":"Array of one or more TOC data objects","definition":{"id":{"type":"String","desc":"The id for the TOC header"},"label":{"type":"String","desc":"The TOC header label"},"level":{"type":"Number","desc":"The TOC header type (1=h1, 2=h2, etc)"},"children":{"type":"Array","tsType":"TocDefinitionArray","desc":"This is normally empty, unless you pass this toc array to the `makeTree` method"}}}}}},"methods":{"makeTree":{"type":"Function","desc":"Pass into this function the results from the `@toc` event to have the data array transformed into a hierarchical tree","params":{"data":{"type":"Array","tsType":"TocDefinitionArray","desc":"The results from the `@toc` event"}},"returns":{"type":"Array","tsType":"TocDefinitionArray","desc":"A modified version of the passed in data in a hierachical format","definition":{"id":{"type":"String","desc":"The slugified heading used for the html key","examples":["the-heading"]},"label":{"type":"String","desc":"The original label","examples":["The Heading"]},"level":{"type":"Number","desc":"The heading level: h1 == 1, h2 == 2m, etc.","examples":["1","2"]},"children":{"type":"Array","tsType":"TocDefinitionArray","desc":"If this object is level 1, then any level 2 objects will be in the `children` key and so on"}}}}}}')}}]);
// DOCUMENT LOAD $(() => { console.log("detail.js is loaded") handleStickyNav(); }) // NAV - STICKY handleStickyNav = () => { var stickyNavTop = $('#nav').offset().top; var stickyNav = function(){ var scrollTop = $(window).scrollTop(); if (scrollTop > stickyNavTop) { $('#nav').addClass('sticky'); } else { $('#nav').removeClass('sticky'); } }; stickyNav(); $(window).scroll(function() { stickyNav(); }); }
config = { "interfaces": { "google.monitoring.v3.ServiceMonitoringService": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": [], }, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 600000, } }, "methods": { "CreateService": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "GetService": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "ListServices": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "UpdateService": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "DeleteService": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "CreateServiceLevelObjective": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "GetServiceLevelObjective": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "ListServiceLevelObjectives": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "UpdateServiceLevelObjective": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "DeleteServiceLevelObjective": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, }, } } }
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { 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 extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import Vue from 'vue'; import { EJComponentDecorator } from '@syncfusion/ej2-vue-base'; var PanelsDirective = /** @class */ (function (_super) { __extends(PanelsDirective, _super); function PanelsDirective() { return _super !== null && _super.apply(this, arguments) || this; } PanelsDirective.prototype.render = function () { return; }; PanelsDirective = __decorate([ EJComponentDecorator({}) ], PanelsDirective); return PanelsDirective; }(Vue)); export { PanelsDirective }; export var PanelsPlugin = { name: 'e-panels', install: function (Vue) { Vue.component(PanelsPlugin.name, PanelsDirective); } }; /** * 'e-panels' directive represent a presets of VueJS dashboardlayout component * It must be contained in a dashboardlayout component(`ejs-dashboardlayout`). * ```html * <ejs-dashboardlayout> * <e-panels> * <e-panel></e-panel> * <e-panel></e-panel> * </e-panels> * </ejs-dashboardlayout> * ``` */ var PanelDirective = /** @class */ (function (_super) { __extends(PanelDirective, _super); function PanelDirective() { return _super !== null && _super.apply(this, arguments) || this; } PanelDirective.prototype.render = function () { return; }; PanelDirective = __decorate([ EJComponentDecorator({}) ], PanelDirective); return PanelDirective; }(Vue)); export { PanelDirective }; export var PanelPlugin = { name: 'e-panel', install: function (Vue) { Vue.component(PanelPlugin.name, PanelDirective); } };
App.IconButton = React.createClass({ handleClick(){ let {target} = this.props; $('#' + target).openModal(); }, componentDidMount(){ }, componentDidUpdate(){ }, runModal(){ }, render(){ let {style, customClass, target} = this.props; return ( <i ref='iconButton' style={style} className={`${customClass} iconButton`} data-target={target} onClick={this.handleClick} aria-hidden="true" ></i> ); } }) ;
/** * angular-strap * @version v2.3.12 - 2021-06-04 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes <[email protected]> (https://github.com/mgcrea) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict';angular.module('mgcrea.ngStrap.modal').run(['$templateCache',function(t){t.put('modal/modal.tpl.html','<div class="modal" tabindex="0" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header" ng-show="title"><button type="button" role="button" class="close" aria-label="Close" ng-click="$hide()"><span aria-hidden="true">&times;</span></button><h1 class="modal-title" ng-bind="title"></h1></div><div class="modal-body" ng-bind="content"></div><div class="modal-footer"><button type="button" class="btn btn-default" ng-click="$hide()" aria-label="Close">Close</button></div></div></div></div>')}]);
import HTTPStatus from 'http-status' import Category from './category.model' export async function createCategory(req, res) { try { const category = await Category.createCategory(req.body, req.user._id); return res.status(HTTPStatus.CREATED).json(category); } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } } export async function getCategoryList(req, res) { try { const categories = await Category.find({}) return res.status(HTTPStatus.OK).json(categories) } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } } export async function getCategoryById(req, res) { try { const category = await Category.findById(req.params.id) return res.status(HTTPStatus.OK).json(category) } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } } export async function getCategoryByTag(req, res) { console.log(req.query); let query = req.query try { const categories = await Category.find(query) return res.status(HTTPStatus.OK).json(categories) } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } } export async function updateCategoryById(req, res) { try { // make this so that only the super admin will be able to update categories const category = await Category.findByIdAndUpdate(req.params.id, req.body) return res.status(HTTPStatus.OK).json(category) } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } } export async function deleteCategoryById(req, res) { try { const category = await Category.findByIdAndDelete(req.params.id) return res.status(HTTPStatus.OK).json(category) } catch (error) { return res.status(HTTPStatus.BAD_REQUEST).json(error) } }
// index.js react-bottstrap-test // import React from 'react' import { render } from 'react-dom' import App from './src/App.js' render( <App />, document.getElementById("app") );
const mockAxiosGet = jest.fn(); jest.mock('axios', () => { return { get: mockAxiosGet }; }); jest.mock('../config', () => { return { baseUrl: 'https://test' }; }); global.console = { error: jest.fn(), }; const mockBuildQuery = jest.fn(); jest.mock('../src/build-query', () => { return { buildQuery: mockBuildQuery, }; }); const Client = require('../src/client'); describe('Get Park', () => { const stubbedData = { data: { name: 'Phantasialand' } }; beforeEach(() => { mockAxiosGet.mockImplementation(() => { return stubbedData; }); }); describe('when a successful request is made with an empty config', () => { const expectedUrl = 'https://test/parks/foo'; let response; beforeEach(async () => { mockBuildQuery.mockReturnValueOnce(''); response = await Client.getPark('foo'); }); it('calls axios once', () => { expect(mockAxiosGet.mock.calls.length).toBe(1); }); it('calls axios with the expected url and returns the expected data', () => { expect(mockAxiosGet.mock.calls[0][0]).toEqual(expectedUrl); expect(response).toEqual(stubbedData.data); }); }); describe('when a successful request is made with a config', () => { const expectedUrl = 'https://test/parks/foo?expected'; beforeEach(async () => { mockBuildQuery.mockReturnValueOnce('?expected'); await Client.getPark('foo', { stubbed: 'config' }); }); it('calls axios with the build query appended to the url', () => { expect(mockAxiosGet.mock.calls[0][0]).toEqual(expectedUrl); }); }); describe('when an unsuccessful request is made', () => { const stubbedError = new Error('some error'); let response; beforeEach(async () => { jest.spyOn(global.console, 'error'); mockAxiosGet.mockImplementation(() => { throw new Error('some error'); }); response = await Client.getPark('foo', { stubbed: 'config' }); }); it('console logs the error and returns null', () => { expect(console.error.mock.calls[0][0]).toEqual(stubbedError); expect(response).toEqual(null); }); }); });
if (window['wptForgetSettings']) var wptStorage = {}; else var wptStorage = window.localStorage || {}; function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } function ValidateInput(form) { if( (form.url.value == "" || form.url.value == "Enter a Website URL") && form.script.value == "" && (form['bulkurls'] == undefined || form.bulkurls.value == "") && (form['bulkfile'] == undefined || form.bulkfile.value == "") ) { alert( "Please enter an URL to test." ); form.url.focus(); return false } if( form.url.value == "Enter a Website URL" ) form.url.value = ""; if (form['runs']) { var runs = form.runs.value; if( runs < 1 || runs > maxRuns ) { alert( "Please select a number of runs between 1 and " + maxRuns + "." ); form.runs.focus(); return false } } var date = new Date(); date.setTime(date.getTime()+(730*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); var options = 0; if (form['private']) { if( form.private.checked ) options = 1; } if( form['viewFirst'] && form.viewFirst.checked ) options = options | 2; document.cookie = 'testOptions=' + options + expires + '; path=/'; if (form['runs']) { document.cookie = 'runs=' + runs + expires + '; path=/'; } // save out the selected location and connection information try { document.cookie = 'cfg=' + $('#connection').val() + expires + '; path=/'; document.cookie = 'u=' + $('#bwUp').val() + expires + '; path=/'; document.cookie = 'd=' + $('#bwDown').val() + expires + '; path=/'; document.cookie = 'l=' + $('#latency').val() + expires + '; path=/'; document.cookie = 'p=' + $('#plr').val() + expires + '; path=/'; } catch(error) { } SaveSettings(); return true; } /* Do any populating of the input form based on the loaded location information */ (function($) { // enable tooltips $("#DOMElement").tooltip({ position: "top center", offset: [-5, 0] }); // Capture tab characters in the script input field $("#enter-script").keydown(function(e) { var $this, end, start; if (e.keyCode === 9) { start = this.selectionStart; end = this.selectionEnd; $this = $(this); $this.val($this.val().substring(0, start) + "\t" + $this.val().substring(end)); this.selectionStart = this.selectionEnd = start + 1; return false; } }); // handle when the selection changes for the location $("#location").change(function(){ LocationChanged(); }); $("#location2").change(function(){ $("#location").val($("#location2").val()); LocationChanged(); }); $("#browser").change(function(){ BrowserChanged(); }); $("#connection").change(function(){ ConnectionChanged(); }); RestoreSettings(); })(jQuery); function RestoreSettings() { if (!window['wptForgetSettings']) { if (wptStorage['testVideo'] != undefined) $('#videoCheck').prop('checked', wptStorage['testVideo']); if (wptStorage['testTimeline'] != undefined) $('#timeline').prop('checked', wptStorage['testTimeline']); if (wptStorage['testLoc'] != undefined) $('#location').val(wptStorage['testLoc']); LocationChanged(); } } function SaveSettings() { if (!window['wptForgetSettings']) { wptStorage['testVideo'] = $('#videoCheck').is(':checked'); wptStorage['testTimeline'] = $('#timeline').is(':checked'); } } /* Populate the different browser options for a given location */ function LocationChanged() { $("#current-location").text($('#location option:selected').text()); var loc = $('#location').val(); $('#location2').val(loc); wptStorage['testLoc'] = loc; var marker = locations[loc]['marker']; try{ marker.setIcon('/images/map_green.png'); }catch(err){} try{ selectedMarker.setIcon('/images/map_red.png'); }catch(err){} selectedMarker = marker; var browsers = []; var defaultConfig = locations[loc]['default']; if( defaultConfig == undefined ) defaultConfig = locations[loc]['1']; var defaultBrowser = locations[defaultConfig]['browser']; // build the list of browsers for this location for( var key in locations[loc] ) { // only care about the integer indexes if( !isNaN(key) ) { var config = locations[loc][key]; var browser = locations[config]['browser']; if( browser != undefined ) { // see if we already know about this browser var browserKey = browser.replace(" ",""); browsers[browserKey] = browser; } } } // fill in the browser list, selecting the default one browserHtml = ''; for( var key in browsers ) { var browser = browsers[key]; var selected = ''; if( browser == defaultBrowser ) selected = ' selected'; var display=browser; if (display == 'Safari') display = 'Safari (Windows)'; browserHtml += '<option value="' + htmlEntities(key) + '"' + selected + '>' + htmlEntities(display) + '</option>'; } $('#browser').html(browserHtml); if (wptStorage['testBrowser'] != undefined) $('#browser').val(wptStorage['testBrowser']); BrowserChanged(); UpdateSponsor(); } /* Populate the various connection types that are available */ function BrowserChanged() { var loc = $('#location').val(); var selectedBrowser = $('#browser').val(); var defaultConfig = locations[loc]['default']; var selectedConfig; wptStorage['testBrowser'] = selectedBrowser; var connections = []; // build the list of connections for this location/browser for( var key in locations[loc] ) { // only care about the integer indexes if( !isNaN(key) ) { var config = locations[loc][key]; var browser = locations[config]['browser'].replace(" ","");; if( browser == selectedBrowser ) { if( locations[config]['connectivity'] != undefined ) { connections[config] = {'label': locations[config]['connectivity']}; if( config == defaultConfig ) selectedConfig = config; } else if( locations[config]['connections'] != undefined ) { for( var conn in locations[config]['connections'] ) { var conn_id = locations[config]['connections'][conn]['id']; var conn_group = locations[config]['connections'][conn]['group']; var conn_label = locations[config]['connections'][conn]['label']; if( selectedConfig == undefined ) selectedConfig = config + '.' + conn_id; connections[config + '.' + conn_id] = {'group': conn_group, 'label': conn_group + ' - ' + conn_label}; } } else { for( var conn in connectivity ) { if (connectivity[conn]['hidden'] == undefined || !connectivity[conn]['hidden']) { if( selectedConfig == undefined ) selectedConfig = config + '.' + conn; connections[config + '.' + conn] = {'label': connectivity[conn]['label']}; } } connections[config + '.custom'] = {'label': 'Custom'}; if( selectedConfig == undefined ) selectedConfig = config + '.custom'; } } } } // if the default configuration couldn't be selected, pick the first one if( selectedConfig == undefined ) { for( var config in connections ) { selectedConfig = config; break; } } // build the actual list connectionHtml = ''; var lastGroup = undefined; for( var config in connections ) { var selected = ''; if( config == selectedConfig ) selected = ' selected'; if (connections[config]['group'] != undefined && connections[config]['group'] != lastGroup) { if (lastGroup != undefined) connectionHtml += "</optgroup>"; if (connections[config]['group'].length) { lastGroup = connections[config]['group']; connectionHtml += '<optgroup label="' + htmlEntities(connections[config]['group']) + '">'; } else lastGroup = undefined; } connectionHtml += '<option value="' + htmlEntities(config) + '"' + selected + '>' + htmlEntities(connections[config]['label']) + '</option>'; } $('#connection').html(connectionHtml); if (wptStorage['testConnection'] != undefined) { var connection = wptStorage['testConnection']; $('#connection option:contains(' + connection + ')').each(function(){ if ($(this).text() == connection) { $(this).attr('selected', 'selected'); } }); } ConnectionChanged(); } /* Populate the specifics of the connection information */ function ConnectionChanged() { var conn = $('#connection').val(); wptStorage['testConnection'] = $('#connection option:selected').text(); if( conn != undefined && conn.length ) { var parts = conn.split('.'); var config = parts[0]; var connection = parts[1]; var setSpeed = true; var backlog = locations[config]['backlog']; var up = locations[config]['up'] / 1000; var down = locations[config]['down'] / 1000; var latency = locations[config]['latency']; var plr = 0; if( connection != undefined && connection.length ) { if( connectivity[connection] != undefined ) { up = connectivity[connection]['bwOut'] / 1000; down = connectivity[connection]['bwIn'] / 1000; latency = connectivity[connection]['latency']; if( connectivity[connection]['plr'] != undefined ) plr = connectivity[connection]['plr']; } else { setSpeed = false; } } if( setSpeed ) { $('#bwDown').val(down); $('#bwUp').val(up); $('#latency').val(latency); $('#plr').val(plr); } // enable/disable the fields as necessary if( connection == 'custom' ) $('#bwTable').show(); else $('#bwTable').hide(); $('#backlog').text(backlog); if( backlog < 5 ) $('#pending_tests').removeClass('backlogWarn , backlogHigh').addClass('hidden'); else if( backlog < 20 ) $('#pending_tests').removeClass('backlogHigh , hidden').addClass("backlogWarn"); else $('#pending_tests').removeClass('backlogWarn , hidden').addClass("backlogHigh"); UpdateSettingsSummary(); } } /* Update the location sponsor */ function UpdateSponsor() { var loc = $('#location').val(); var spon = new Array(); // build the list of sponsors for this location for( var key in locations[loc] ) { // only care about the integer indexes if( !isNaN(key) ) { var config = locations[loc][key]; var sponsor = locations[config]['sponsor']; if( sponsor != undefined && sponsor.length && sponsors[sponsor] != undefined ) { // avoid duplicates var found = false; for( var index in spon ) if( spon[index] == sponsor ) found = true; if( !found ) spon.push(sponsor); } } } if( spon.length ) { var html = '<p class="centered"><small>Provided by</small></p>'; var count = 0; // randomize the list if( spon.length > 1 ) spon.sort(function() {return 0.5 - Math.random()}); for( var index in spon ) { var sponsor = spon[index]; var s = sponsors[sponsor]; if( s != undefined ) { var sponsorTxt = ''; var sponsorHref = ''; var sponsorDiv = ''; if( s["logo"] != undefined && s["logo"].length ) { sponsorDiv = '<div class="sponsor_logo" style="background-image: url(' + s["logo"] + '); background-position: 0px ' + s["offset"] + 'px; margin-left: auto; margin-right: auto;"></div>'; } if( s["alt"] != undefined && s["alt"].length ) sponsorTxt = ' title="' + s["alt"] + '"'; if( s["href"] != undefined && s["href"].length ) sponsorHref = s["href"]; if(sponsorDiv.length) { if( count ) html += '<p class="centered nomargin"><small>and</small></p>'; html += '<div class="centered nomargin">'; if( sponsorHref.length ) { html += '<a class="sponsor_link" href="' + sponsorHref + '"' + sponsorTxt + '>'; } html += sponsorDiv; if( sponsorHref.length ) html += '</a>'; html += '</div>'; count++; } } } $('#sponsor').html(html); $('#sponsor').show(); } else $('#sponsor').hide(); } /* Update the summary text with the current test settings */ function UpdateSettingsSummary() { var summary = ''; var runs = $('#number_of_tests').val(); summary += runs; if( runs == 1 ) summary += " run"; else summary += " runs"; if( $('#viewFirst').attr('checked') ) summary += ", First View only"; var conn = $('#connection option:selected').text(); if( conn != undefined ) summary += ", " + conn.replace(/\((.)*\)/,'') + " connection"; if( $('#keep_test_private').attr('checked') ) summary += ", private"; else summary += ", results are public"; $('#settings_summary').text(summary); } /* Show the multiple location selection dialog */ function OpenMultipleLocations() { document.getElementById('multiple-location-dialog').style.display = 'block'; } /* Close the multiple location selection dialog. */ function CloseMultipleLocations() { document.getElementById('multiple-location-dialog').style.display = 'none'; } /* Pop up the location selection dialog */ var map; var selectedMarker; function SelectLocation() { $("#location-dialog").modal({opacity:80}); $('#location2').val($('#location').val()); var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://maps.google.com/maps/api/js?v=3.1&sensor=false&callback=InitializeMap"; document.body.appendChild(script); return false; } function InitializeMap() { var myLatlng = new google.maps.LatLng(15,17); var myOptions = { zoom: 2, center: myLatlng, mapTypeControl: false, navigationControl: true, navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map"), myOptions); var currentLoc = $('#location').val(); for( var loc in locations ) { if( locations[loc]['lat'] != undefined && locations[loc]['lng'] != undefined ) { var pos = new google.maps.LatLng(locations[loc]['lat'], locations[loc]['lng']); var marker = new google.maps.Marker({ position: pos, title:locations[loc]['label'], icon:'/images/map_red.png', map: map }); if( loc == currentLoc ) { marker.setIcon('/images/map_green.png'); selectedMarker = marker; } locations[loc]['marker'] = marker; AttachClickEvent(marker, loc); } } } function AttachClickEvent(marker, loc) { google.maps.event.addListener(marker, 'click', function() { $('#location').val(loc); LocationChanged(); }); }
"""Contains classes for accuracy analysis. """ from ilbs.arrproc import keyExtract class XPOSRecognitionAnalyzer: """Analyze the accuracy of recognition tokens' morphology. Properties: CHECKED (int increment): Number of analyzed tokens. CORRECT_XPOS (int increment): Number of correct recognized XPOS. CORRECT_UPOS (int increment): Number of correct recognized UPOS. IMPROVE_XPOS (int increment): XPOS recognition might be improved with changing applierFunc. IMPROVE_UPOS (int increment): UPOS recognition might be improved with changing applierFunc. reader (*): On of readers specified in gc.py. It should contain nextLine() method and DATALINE constant. limit (int): Limit on tokens to analyze. recognizer (MorphologyRecognizer): A class specified in morphology.py It should contain recognize() method. applier (function): Applier function for your recognizer. """ CHECKED = 0 CORRECT_XPOS = 0 CORRECT_UPOS = 0 IMPROVE_XPOS = 0 IMPROVE_UPOS = 0 def __init__( self, reader, recognizer, limit=0, offset=0 ): """Prepare an analyser. Args: reader (*): On of readers specified in libs/ud. It should contain nextLine() method and DATALINE constant. limit (int): Limit on tokens to analyze. Set to 0 to make it infinite. offset (int): Number of tokens from the beginning of the file to be skipped. recognizer (MorphologyRecognizer): A class specified in morphology.py. It should contain recognize() method. """ self.reader = reader self.limit = limit if limit != 0 else float("inf") self.offset = offset if offset else 0 self.recognizer = recognizer def init(self): """Init a generator function next() does the next check and returns token with info. Yields: dict: { token: str, result: list of dict: Rules as they're stored in DB, applierResult: dict: Rule from applierFunc } """ try: # Skip offset if self.offset != 0: i = 0 while i < self.offset: line = self.reader.nextLine() if line["type"] == self.reader.DATALINE: i += 1 # All non-DATALINE lines will be skipped while True: if self.limit <= self.CHECKED: raise StopIteration line = self.reader.nextLine() if line["type"] != self.reader.DATALINE: continue token = self.reader.extractProperty( line, prop=self.reader.FORMNAME ) upos = self.reader.extractProperty( line, prop=self.reader.UPOSNAME ) xpos = self.reader.extractProperty( line, prop=self.reader.XPOSNAME ) result = self.recognizer.recognize( token, withApplier=False ) applierResult = self.recognizer.recognize(token) self.CHECKED += 1 checks = { "IMPROVE_UPOS": False, "IMPROVE_XPOS": False, "CORRECT_UPOS": False, "CORRECT_XPOS": False } if result: if upos in keyExtract(result, "upos"): checks["IMPROVE_UPOS"] = True self.IMPROVE_UPOS += 1 if applierResult and upos == applierResult["upos"]: checks["CORRECT_UPOS"] = True self.CORRECT_UPOS += 1 if xpos in keyExtract(result, "xpos"): checks["IMPROVE_XPOS"] = True self.IMPROVE_XPOS += 1 if applierResult and xpos == applierResult["xpos"]: checks["CORRECT_XPOS"] = True self.CORRECT_XPOS += 1 yield { "checks": checks, "token": token, "result": result, "applierResult": applierResult, "gc": line } except EOFError: raise StopIteration
import React from "react"; import Employees from "./pages/Employees.js"; function App () { return <Employees /> } export default App;
# Copyright 2019 DeepMind Technologies Limited. 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. # ============================================================================== """A Double DQN (tuned) agent training on Atari. From the paper "Deep Reinforcement Learning with Double Q-learning" http://arxiv.org/abs/1509.06461. This is DQN with: * Double Q-learning. * Shared bias in final layer of the network. * Tuned parameters: * Smaller final training exploration epsilon. * Smaller evaluation exploration epsilon. * Larger target network update period. """ # pylint: disable=g-bad-import-order import collections import itertools import sys import typing from absl import app from absl import flags from absl import logging import dm_env import haiku as hk import jax from jax.config import config import numpy as np import optax from dqn_zoo import atari_data from dqn_zoo import gym_atari from dqn_zoo import networks from dqn_zoo import parts from dqn_zoo import processors from dqn_zoo import replay as replay_lib from dqn_zoo.double_q import agent # Relevant flag values are expressed in terms of environment frames. FLAGS = flags.FLAGS flags.DEFINE_string('environment_name', 'pong', '') flags.DEFINE_integer('environment_height', 84, '') flags.DEFINE_integer('environment_width', 84, '') flags.DEFINE_bool('use_gym', False, '') flags.DEFINE_integer('replay_capacity', int(1e6), '') flags.DEFINE_bool('compress_state', True, '') flags.DEFINE_float('min_replay_capacity_fraction', 0.05, '') flags.DEFINE_integer('batch_size', 32, '') flags.DEFINE_integer('max_frames_per_episode', 108000, '') # 30 mins. flags.DEFINE_integer('num_action_repeats', 4, '') flags.DEFINE_integer('num_stacked_frames', 4, '') flags.DEFINE_float('exploration_epsilon_begin_value', 1., '') flags.DEFINE_float('exploration_epsilon_end_value', 0.01, '') flags.DEFINE_float('exploration_epsilon_decay_frame_fraction', 0.02, '') flags.DEFINE_float('eval_exploration_epsilon', 0.01, '') flags.DEFINE_integer('target_network_update_period', int(1.2e5), '') flags.DEFINE_float('grad_error_bound', 1. / 32, '') flags.DEFINE_float('learning_rate', 0.00025, '') flags.DEFINE_float('optimizer_epsilon', 0.01 / 32**2, '') flags.DEFINE_float('additional_discount', 0.99, '') flags.DEFINE_float('max_abs_reward', 1., '') flags.DEFINE_integer('seed', 1, '') # GPU may introduce nondeterminism. flags.DEFINE_integer('num_iterations', 200, '') flags.DEFINE_integer('num_train_frames', int(1e6), '') # Per iteration. flags.DEFINE_integer('num_eval_frames', int(5e5), '') # Per iteration. flags.DEFINE_integer('learn_period', 16, '') flags.DEFINE_string('results_csv_path', '/tmp/results.csv', '') def main(argv): """Trains Double DQN agent on Atari.""" del argv logging.info('Double DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform) random_state = np.random.RandomState(FLAGS.seed) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=np.int64)) if FLAGS.results_csv_path: writer = parts.CsvWriter(FLAGS.results_csv_path) else: writer = parts.NullWriter() def environment_builder(): """Creates Atari environment.""" env = gym_atari.GymAtari( FLAGS.environment_name, seed=random_state.randint(1, 2**32)) return gym_atari.RandomNoopsEnvironmentWrapper( env, min_noop_steps=1, max_noop_steps=30, seed=random_state.randint(1, 2**32), ) env = environment_builder() logging.info('Environment: %s', FLAGS.environment_name) logging.info('Action spec: %s', env.action_spec()) logging.info('Observation spec: %s', env.observation_spec()) num_actions = env.action_spec().num_values network_fn = networks.double_dqn_atari_network(num_actions) network = hk.transform(network_fn) def preprocessor_builder(): return processors.atari( additional_discount=FLAGS.additional_discount, max_abs_reward=FLAGS.max_abs_reward, resize_shape=(FLAGS.environment_height, FLAGS.environment_width), num_action_repeats=FLAGS.num_action_repeats, num_pooled_frames=2, zero_discount_on_life_loss=True, num_stacked_frames=FLAGS.num_stacked_frames, grayscaling=True, ) # Create sample network input from sample preprocessor output. sample_processed_timestep = preprocessor_builder()(env.reset()) sample_processed_timestep = typing.cast(dm_env.TimeStep, sample_processed_timestep) sample_network_input = sample_processed_timestep.observation assert sample_network_input.shape == (FLAGS.environment_height, FLAGS.environment_width, FLAGS.num_stacked_frames) exploration_epsilon_schedule = parts.LinearSchedule( begin_t=int(FLAGS.min_replay_capacity_fraction * FLAGS.replay_capacity * FLAGS.num_action_repeats), decay_steps=int(FLAGS.exploration_epsilon_decay_frame_fraction * FLAGS.num_iterations * FLAGS.num_train_frames), begin_value=FLAGS.exploration_epsilon_begin_value, end_value=FLAGS.exploration_epsilon_end_value) if FLAGS.compress_state: def encoder(transition): return transition._replace( s_tm1=replay_lib.compress_array(transition.s_tm1), s_t=replay_lib.compress_array(transition.s_t)) def decoder(transition): return transition._replace( s_tm1=replay_lib.uncompress_array(transition.s_tm1), s_t=replay_lib.uncompress_array(transition.s_t)) else: encoder = None decoder = None replay_structure = replay_lib.Transition( s_tm1=None, a_tm1=None, r_t=None, discount_t=None, s_t=None, ) replay = replay_lib.TransitionReplay(FLAGS.replay_capacity, replay_structure, random_state, encoder, decoder) optimizer = optax.rmsprop( learning_rate=FLAGS.learning_rate, decay=0.95, eps=FLAGS.optimizer_epsilon, centered=True, ) train_rng_key, eval_rng_key = jax.random.split(rng_key) train_agent = agent.DoubleDqn( preprocessor=preprocessor_builder(), sample_network_input=sample_network_input, network=network, optimizer=optimizer, transition_accumulator=replay_lib.TransitionAccumulator(), replay=replay, batch_size=FLAGS.batch_size, exploration_epsilon=exploration_epsilon_schedule, min_replay_capacity_fraction=FLAGS.min_replay_capacity_fraction, learn_period=FLAGS.learn_period, target_network_update_period=FLAGS.target_network_update_period, grad_error_bound=FLAGS.grad_error_bound, rng_key=train_rng_key, ) eval_agent = parts.EpsilonGreedyActor( preprocessor=preprocessor_builder(), network=network, exploration_epsilon=FLAGS.eval_exploration_epsilon, rng_key=eval_rng_key, ) # Set up checkpointing. checkpoint = parts.NullCheckpoint() state = checkpoint.state state.iteration = 0 state.train_agent = train_agent state.eval_agent = eval_agent state.random_state = random_state state.writer = writer if checkpoint.can_be_restored(): checkpoint.restore() while state.iteration <= FLAGS.num_iterations: # New environment for each iteration to allow for determinism if preempted. env = environment_builder() logging.info('Training iteration %d.', state.iteration) train_seq = parts.run_loop(train_agent, env, FLAGS.max_frames_per_episode) num_train_frames = 0 if state.iteration == 0 else FLAGS.num_train_frames train_seq_truncated = itertools.islice(train_seq, num_train_frames) train_stats = parts.generate_statistics(train_seq_truncated) logging.info('Evaluation iteration %d.', state.iteration) eval_agent.network_params = train_agent.online_params eval_seq = parts.run_loop(eval_agent, env, FLAGS.max_frames_per_episode) eval_seq_truncated = itertools.islice(eval_seq, FLAGS.num_eval_frames) eval_stats = parts.generate_statistics(eval_seq_truncated) # Logging and checkpointing. human_normalized_score = atari_data.get_human_normalized_score( FLAGS.environment_name, eval_stats['episode_return']) capped_human_normalized_score = np.amin([1., human_normalized_score]) log_output = [ ('iteration', state.iteration, '%3d'), ('frame', state.iteration * FLAGS.num_train_frames, '%5d'), ('eval_episode_return', eval_stats['episode_return'], '% 2.2f'), ('train_episode_return', train_stats['episode_return'], '% 2.2f'), ('eval_num_episodes', eval_stats['num_episodes'], '%3d'), ('train_num_episodes', train_stats['num_episodes'], '%3d'), ('eval_frame_rate', eval_stats['step_rate'], '%4.0f'), ('train_frame_rate', train_stats['step_rate'], '%4.0f'), ('train_exploration_epsilon', train_agent.exploration_epsilon, '%.3f'), ('normalized_return', human_normalized_score, '%.3f'), ('capped_normalized_return', capped_human_normalized_score, '%.3f'), ('human_gap', 1. - capped_human_normalized_score, '%.3f'), ] log_output_str = ', '.join(('%s: ' + f) % (n, v) for n, v, f in log_output) logging.info(log_output_str) writer.write(collections.OrderedDict((n, v) for n, v, _ in log_output)) state.iteration += 1 checkpoint.save() writer.close() if __name__ == '__main__': config.update('jax_platform_name', 'gpu') # Default to GPU. config.update('jax_numpy_rank_promotion', 'raise') config.config_with_absl() app.run(main)
var x = 0; var source = "let x: string = 'string'"; function fib(x) { if (x <= 1) return 1; return fib(x - 1) + x; } var result = fib(90); console.log(result);
# echo-server.py import socket HOST = "127.0.0.1" # Standard loopback interface address (localhost) PORT = 7777 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) if data == b'end': break elif data == b'': data = b' ' conn.sendall(data) print('received:', data)
import axios from 'axios'; import { authConstants } from '../constants/authConstants'; export const login = (data) => async (dispatch) => { dispatch({ type: authConstants.START_LOADING }); try { const result = await axios.post('/auth/access-token', data); const token = result.data.accesstoken; axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; localStorage.setItem('token', token); dispatch({ type: authConstants.LOGIN_SUCCESS, payload: { data: result.data.accesstoken } }); } catch (err) { console.log(err); dispatch({ type: authConstants.LOGIN_FAILED }); } finally { dispatch({ type: authConstants.STOP_LOADING }); } };
L.Coordinates = L.Control.extend({ options: { position: 'bottomright' }, onAdd: function(map) { this._container = L.DomUtil.create('div', 'leaflet-bar'); this._container.style.background = '#ffffff'; map.on('mousemove', this._onMouseMove, this); return this._container; }, _onMouseMove: function(e) { this._container.innerHTML = '<span style="padding: 5px">' + e.latlng.lng.toFixed(3) + ', ' + e.latlng.lat.toFixed(3) + '</span>'; } });
var searchData= [ ['id_0',['id',['../structqos__class.html#a50d6aa2bf63622320919cf7b4a294939',1,'qos_class']]], ['iface_5fin_1',['iface_in',['../structqos__class.html#ab47b524511e925a416f40f401fb736f0',1,'qos_class']]], ['iface_5fout_2',['iface_out',['../structqos__class.html#aac0ca8abb088579b646d489f553b8fb2',1,'qos_class']]], ['initqosclass_3',['initQosClass',['../classification_8c.html#a152a8b24830cb6d60e74a264ce9787d6',1,'classification.c']]], ['ip_5fdst_5faddr_4',['ip_dst_addr',['../structqos__class.html#a7cfcefa454c116feaaf206c3b2d203f3',1,'qos_class']]], ['ip_5fdst_5fmask_5',['ip_dst_mask',['../structqos__class.html#ab43e840caae053ca3cca1ddd7bd3876b',1,'qos_class']]], ['ip_5fsrc_5faddr_6',['ip_src_addr',['../structqos__class.html#a7130e1ade1f7f226ad259c47edeec494',1,'qos_class']]], ['ip_5fsrc_5fmask_7',['ip_src_mask',['../structqos__class.html#af97d1e6badbde720b084841497bcf104',1,'qos_class']]], ['iptables_5fipv4_8',['IPTABLES_IPV4',['../classification_8c.html#a9e6af64356c2d601cdb49b676d4fe1dba781b1fdbefbe39fc6edf90430244c503',1,'classification.c']]], ['iptables_5fipv6_9',['IPTABLES_IPV6',['../classification_8c.html#a9e6af64356c2d601cdb49b676d4fe1dbab4889de7d1672b8b83e5460efbca2db0',1,'classification.c']]] ];
/* @flow */ import React from "react"; import { View, StyleSheet } from "react-native"; import { useTheme } from "@react-navigation/native"; import LText from "./LText"; import Touchable from "./Touchable"; type ChoiceButtonProps = { disabled?: boolean, onSelect: Function, label: React$Node, description?: React$Node, Icon: any, extra?: React$Node, event: string, eventProperties: *, navigationParams?: any[], enableActions?: string, }; const ChoiceButton = ({ event, eventProperties, disabled, label, description, Icon, extra, onSelect, navigationParams, enableActions, }: ChoiceButtonProps) => { const { colors } = useTheme(); return ( <Touchable event={event} eventProperties={eventProperties} style={styles.button} disabled={disabled} onPress={() => onSelect({ navigationParams, enableActions })} > <View style={[ styles.buttonIcon, { backgroundColor: colors.lightLive }, disabled ? { backgroundColor: colors.lightFog } : {}, ]} > <Icon color={disabled ? colors.grey : colors.live} size={18} /> </View> <View style={styles.buttonLabelContainer}> <LText style={[styles.buttonLabel]} color={disabled ? "grey" : "darkBlue"} semiBold > {label} </LText> {description && ( <LText style={[styles.buttonDesc]} color="grey"> {description} </LText> )} </View> {extra && <View style={styles.extraButton}>{extra}</View>} </Touchable> ); }; export default ChoiceButton; const styles = StyleSheet.create({ button: { width: "100%", height: "auto", marginVertical: 8, flexDirection: "row", justifyContent: "flex-start", alignItems: "center", borderRadius: 4, paddingVertical: 8, paddingHorizontal: 8, }, buttonIcon: { width: 50, height: 50, borderRadius: 50, justifyContent: "center", alignItems: "center", }, buttonLabelContainer: { flex: 1, flexGrow: 1, justifyContent: "center", alignItems: "flex-start", marginHorizontal: 10, }, buttonLabel: { fontSize: 18, lineHeight: 22, }, buttonDesc: { fontSize: 13, lineHeight: 16, }, extraButton: { flexShrink: 1, flexDirection: "row", alignContent: "center", justifyContent: "flex-end", }, });
const BackboneElement = require('./BackboneElement'); class EncounterHospitalization extends BackboneElement { constructor(opt) { super(opt); this.__resourceType = 'EncounterHospitalization'; Object.assign(this, opt); } // This is a EncounterHospitalization resource static get __resourceType() { return 'EncounterHospitalization'; } // Pre-admission identifier. get preAdmissionIdentifier() { return this.__preAdmissionIdentifier; } set preAdmissionIdentifier(new_value) { const Identifier = require('./Identifier'); this.__preAdmissionIdentifier = new Identifier(new_value); } // The location from which the patient came before admission. get origin() { return this.__origin; } set origin(new_value) { const Reference = require('./Reference'); this.__origin = new Reference(new_value); } // From where patient was admitted (physician referral, transfer). get admitSource() { return this.__admitSource; } set admitSource(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__admitSource = new CodeableConcept(new_value); } // The admitting diagnosis field is used to record the diagnosis codes as reported by admitting practitioner. This could be different or in addition to the conditions reported as reason-condition(s) for the encounter. get admittingDiagnosis() { return this.__admittingDiagnosis; } set admittingDiagnosis(new_value) { const Reference = require('./Reference'); this.__admittingDiagnosis = Array.isArray(new_value) ? new_value.map(val => new Reference(val)) : [new Reference(new_value)]; } // Whether this hospitalization is a readmission and why if known. get reAdmission() { return this.__reAdmission; } set reAdmission(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__reAdmission = new CodeableConcept(new_value); } // Diet preferences reported by the patient. get dietPreference() { return this.__dietPreference; } set dietPreference(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__dietPreference = Array.isArray(new_value) ? new_value.map(val => new CodeableConcept(val)) : [new CodeableConcept(new_value)]; } // Special courtesies (VIP, board member). get specialCourtesy() { return this.__specialCourtesy; } set specialCourtesy(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__specialCourtesy = Array.isArray(new_value) ? new_value.map(val => new CodeableConcept(val)) : [new CodeableConcept(new_value)]; } // Wheelchair, translator, stretcher, etc. get specialArrangement() { return this.__specialArrangement; } set specialArrangement(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__specialArrangement = Array.isArray(new_value) ? new_value.map(val => new CodeableConcept(val)) : [new CodeableConcept(new_value)]; } // Location to which the patient is discharged. get destination() { return this.__destination; } set destination(new_value) { const Reference = require('./Reference'); this.__destination = new Reference(new_value); } // Category or kind of location after discharge. get dischargeDisposition() { return this.__dischargeDisposition; } set dischargeDisposition(new_value) { const CodeableConcept = require('./CodeableConcept'); this.__dischargeDisposition = new CodeableConcept(new_value); } // The final diagnosis given a patient before release from the hospital after all testing, surgery, and workup are complete. get dischargeDiagnosis() { return this.__dischargeDiagnosis; } set dischargeDiagnosis(new_value) { const Reference = require('./Reference'); this.__dischargeDiagnosis = Array.isArray(new_value) ? new_value.map(val => new Reference(val)) : [new Reference(new_value)]; } toJSON() { return Object.assign(super.toJSON(), { preAdmissionIdentifier: this.__preAdmissionIdentifier && this.__preAdmissionIdentifier.toJSON(), origin: this.__origin && this.__origin.toJSON(), admitSource: this.__admitSource && this.__admitSource.toJSON(), admittingDiagnosis: this.__admittingDiagnosis && this.__admittingDiagnosis.map(v => v.toJSON()), reAdmission: this.__reAdmission && this.__reAdmission.toJSON(), dietPreference: this.__dietPreference && this.__dietPreference.map(v => v.toJSON()), specialCourtesy: this.__specialCourtesy && this.__specialCourtesy.map(v => v.toJSON()), specialArrangement: this.__specialArrangement && this.__specialArrangement.map(v => v.toJSON()), destination: this.__destination && this.__destination.toJSON(), dischargeDisposition: this.__dischargeDisposition && this.__dischargeDisposition.toJSON(), dischargeDiagnosis: this.__dischargeDiagnosis && this.__dischargeDiagnosis.map(v => v.toJSON()), }); } } module.exports = EncounterHospitalization;
module.exports = function (router) { // CHANGE ME TO THE VERSION YOURE WORKING ON var version = '0-1-4' var base_url = 'raa-v2/' + version + '/sprint/new-flow'; var locations = require('../../../../data/locations.json') var training = require('../../../../data/training.json') var vacancies = require('../../../../data/vacancies.json') var employers = require('../../../../data/employers.json') var providers = ['Eurosource Solutions Limited','SBC TRAINING','learndirect Apprenticeships','Lifetime Training','Lifetime Training','University College Birmingham','Coventry University' ] var dates = ['1 Mar 2019','23 Apr 2019','30 Apr 2019','9 May 2019','16 May 2019','24 Jun 2019','11 Jul 2019','12 Jul 2019','28 Aug 2019','13 Nov 2019'] // GLOBAL GET ROUTER. // Code here will be called on every page within this version function getEmployersList($amount){ var newEmployersList = [] var rand for(var i=0;i<$amount;i++){ var rand = employers[Math.floor(Math.random() * employers.length)]; newEmployersList.push(rand) } return newEmployersList } router.get('/' + base_url + '*', function (req, res,next) { // set session info by use of the url paremeters if(req.query.alt){req.session.alt=req.query.alt} if(req.query.force_notifcation_setup){req.session.force_notifcation_setup=req.query.force_notifcation_setup} if(req.query.vacancies){req.session.vacancies=req.query.vacancies} if(req.query.has_notifications){req.session.has_notifications=req.query.has_notifications} if(req.query.returnDashaboard){req.session.returnDashaboard=req.query.returnDashaboard} if(req.query.returnDashaboard){req.session.returnDashaboard=req.query.returnDashaboard} if(req.query.numberOfEntities){req.session.NumberOfEntities = req.query.numberOfEntities} if(req.query.user){req.session.user = req.query.user} if(req.query.employerAmount){req.session.employerAmount=req.query.employerAmount} // Set defaults if any session data is not set req.session.alt = req.session.alt|| "no" req.session.force_notifcation_setup = req.session.force_notifcation_setup || "yes" req.session.has_notifications = req.session.has_notifications || "no"; req.session.vacancies = req.session.vacancies || "multiple"; req.session.orgName = req.session.orgName || "ABC opticians" req.session.hasTradingName = (req.query.hasTradingName)? req.query.hasTradingName : "no"; req.session.NumberOfEntities = req.session.NumberOfEntities || 4; req.session.user = req.session.user || "provider"; req.session.employerAmount = req.session.employerAmount || 8; return next() }) // ------------------------------- // #config // ------------------------------- router.post('/' + base_url + '/config', function (req, res) { var page = 'dashboard-'+req.body.journey; console.log(req.body) req.session.NumberOfEntities = req.body.NumberOfEntities || 88; req.session.orgName = req.body.orgName; res.redirect(301, '/' + base_url + '/'+page) }) // ------------------------------- // #Dashboards // ------------------------------- router.get('/' + base_url + '/dashboard', function (req, res) { res.render(base_url + '/dashboard', { "data" : req.session, } ) }) router.get('/' + base_url + '/vacancies', function (req, res) { var empoloyer_title = [] for(var i in req.session.employers){ empoloyer_title.push(req.session.employers[i].businessName) } res.render(base_url + '/vacancies', { "data" : req.session, "locations" : locations, "query" : req.query, "providers" : providers, "vacancies" : vacancies, "employers" : empoloyer_title, "dates" : dates, } ) }) // ------------------------------- // #create // ------------------------------- // Added from Disability branch router.get('/' + base_url + '/create/tasks', function (req, res) { res.render(base_url + '/create/tasks', { "data" : req.session, "query" : req.query, } ) }) router.get('/' + base_url + '/create/employers-select', function (req, res) { if(req.query.employerAmount){ req.session.employerAmount = req.query.employerAmount } req.session.employers = getEmployersList(req.session.employerAmount); res.render(base_url + '/create/employers-select', { "data" : req.session, "employers" : employers, "query" : req.query, } ) }) router.post('/' + base_url + '/create/employers-select', function (req, res) { req.session.currentEmployer = req.body.selected_organisation_id req.session.orgName = req.session.currentEmployer if(req.query.route=='clone'){ res.redirect(301, '/' + base_url + '/create-vacancy-options/create-vacancy') }else{ res.redirect(301, '/' + base_url + '/create/title') } }) // #title router.get('/' + base_url + '/create/title', function (req, res) { res.render(base_url + '/create/title', { "data" : req.session, "query" : req.query, } ) }); router.post('/' + base_url + '/create/title', function (req, res) { req.session.title = req.body.title || "Engineering Apprenticeship" if(req.body.continueButton){ res.redirect(301, '/' + base_url + '/create/positions') }else{ res.redirect(301, '/' + base_url + '/create/vacancy-preview') } }); // #positions router.post('/' + base_url + '/create/positions', function (req, res) { req.session.numberOfPositions = req.body.numberOfPositions || 1; res.redirect(301, '/' + base_url + '/create/training-level') }); router.get('/' + base_url + '/create/training-level', function (req, res) { res.render(base_url + '/create/training-level', { "data" : req.session, "training" : training, "query" : req.query.query, } ) }); router.post('/' + base_url + '/create/training-level', function (req, res) { req.session.training_standard = req.body.searchClients || "Aerospace engineer, Level: 6 (Standard) "; if(req.session.user=="employer"){ res.redirect(301, '/' + base_url + '/create/select-training-provider') }else{ res.redirect(301, '/' + base_url + '/create/linked-organisation') } }) router.get('/' + base_url + '/create/training', function (req, res) { req.session.training_standard = req.query.searchClients || "Aerospace engineer, Level: 6 (Standard) "; res.render(base_url + '/create/training', { "data" : req.session, "query" : req.query, } ) }) router.post('/' + base_url + '/create/create-vacancy', function (req, res) { if(req.body.create_option == "new"){ res.redirect(301, '/' + base_url + '/create/title') }else{ res.redirect(301, '/' + base_url + '/create/clone-vacancy') } }) // #clone-vacancy router.get('/' + base_url + '/create/clone-vacancy', function (req, res) { res.render(base_url + '/create/clone-vacancy', { "data" : req.session, "query" : req.query.query } ) }) // Added from Disability branch router.post('/' + base_url + '/create/title', function (req, res) { req.session.title = req.body.title || "Engineering Apprenticeship" req.session.is_disability_confident = (req.body.disability_confident_level) ? "yes" : "no"; res.redirect(301, '/' + base_url + '/create/short-description') }) router.post('/' + base_url + '/create/disability-vacancy-check', function (req, res) { req.session.is_disability_confident = req.body.disability_confident_level req.session.disability_confident_level= req.body.disability_confident_level res.redirect(301, '/' + base_url + '/create/dates') }) router.post('/' + base_url + '/create/dates', function (req, res) { if(req.body.continueButton){ res.redirect(301, '/' + base_url + '/create/duration') }else{ res.redirect(301, '/' + base_url + '/create/vacancy-preview') } }) // #employer router.get('/' + base_url + '/create/linked-organisation', function (req, res) { req.session.NumberOfEntities=5 if(req.session.NumberOfEntities < 2){ return res.redirect(301, '/' + base_url + '/create/display-name?') } res.render(base_url + '/create/linked-organisation', { "data" : req.session, "locations" : locations, "query" : req.query, } ) }) router.post('/' + base_url + '/create/linked-organisation', function (req, res) { req.session.orgName = req.body.selected_organisation_id || "ABC Opticians" if(req.body.continueButton){ res.redirect(301, '/' + base_url + '/create/display-name') } else{ res.redirect(301, '/' + base_url + '/create/display-name?edit=yes') } }) router.post('/' + base_url + '/create/display-name', function (req, res) { req.session.tradingName = req.query.tradingName || "Acme Lens"; req.session.hasTradingName=(req.query.tradingName)? 'yes' : 'no'; if(req.body.continueButton){ res.redirect(301, '/' + base_url + '/create/location') }else{ res.redirect(301, '/' + base_url + '/create/vacancy-preview') } }) router.post('/' + base_url + '/create/disability', function (req, res) { if(req.body.disability_confident_signed=='yes'){ res.redirect(301, '/' + base_url + '/create/disability-vacancy-check') }else{ res.redirect(301, '/' + base_url + '/create/dates') } }) router.post('/' + base_url + '/create/short-description', function (req, res) { req.session.shortDescription = req.body.shortDescription || "As a Software Developer Apprentice, you will be undertaking a recognised apprenticeship qualification, including Microsoft certifications, at the same time as working as part of the company’s Software Development team." if(req.body.continueButton){ res.redirect(301, '/' + base_url + '/create/long-description') }else{ res.redirect(301, '/' + base_url + '/create/vacancy-preview') } }) //search-results-preview router.get('/' + base_url + '/create/search-results-preview', function (req, res) { req.session.orgname = req.session.orgname || "ABC Opticians" res.render(base_url + '/create/search-results-preview', { "data" : req.session, } ) }) // ------------------------------- // #vacancy-preview // ------------------------------- router.get('/' + base_url + '/create/vacancy-preview', function (req, res) { res.render(base_url + '/create/vacancy-preview', { "data" : req.session, } ) }) router.post('/' + base_url + '/create/vacancy-preview', function (req, res) { res.redirect(301, '/' + base_url + '/create/confirmation') }) router.get('/' + base_url + '/create/confirmation', function (req, res) { res.render(base_url + '/create/confirmation', { "data" : req.session, } ) }) // *SKILLS* router.get('/' + base_url + '/create/skills', function (req, res) { res.render(base_url + '/create/skills', { "data" : req.session, } ) }) router.post('/' + base_url + '/create/skills', function (req, res) { req.session.Skills = req.body.Skills console.log(req.body) res.redirect(301, '/' + base_url + '/create/vacancy-preview') }) // *QUALIFICATIONS* router.get('/' + base_url + '/create/qualifications', function (req, res) { res.render(base_url + '/create/qualifications', { "data" : req.session, } ) }) router.post('/' + base_url + 'vacancy-preview/qualifications', function (req, res) { res.redirect(301, '/' + base_url + '/create/vacancy-preview') }) // *CONSIDERATIONS* router.post('/' + base_url + '/create/considerations', function (req, res) { req.session.ThingsToConsider = req.body.ThingsToConsider; res.redirect(301, '/' + base_url + '/create/vacancy-preview') }) // *CONTACT DETAILS* router.post('/' + base_url + '/create/employer-contact-details', function (req, res) { req.session.EmployerContactName = req.body.EmployerContactName; req.session.EmployerContactEmail = req.body.EmployerContactEmail; req.session.EmployerContactPhone = req.body.EmployerContactPhone; res.redirect(301, '/' + base_url + '/create/vacancy-preview') }) // DELETE router.post('/' + base_url + '/create/delete', function (req, res) { if(req.body.ConfirmDeletion == "yes"){ res.redirect(301, '/' + base_url + '/'+req.session.returnDashaboard) }else{ res.redirect(301, '/' + base_url + '/create/vacancy-preview') } }) //#vacancy-description router.get('/' + base_url + '/create/vacancy-description', function (req, res) { res.render(base_url + '/create/vacancy-description', { "data" : req.session, } ) }) router.post('/' + base_url + '/create/vacancy-description', function (req, res) { req.session.VacancyDescription = req.body.VacancyDescription req.session.TrainingDescription = req.body.TrainingDescription req.session.OutcomeDescription = req.body.OutcomeDescription res.redirect(301, '/' + base_url + '/create/vacancy-preview') }) //#confirmation router.post('/' + base_url + '/create/confirmation', function (req, res) { if(req.session.force_notifcation_setup == "yes" && req.session.has_notifications == "no"){ res.redirect(301, '/' + base_url + '/notifications/receive-notifications'); }else{ res.redirect(301, '/' + base_url + '/dashboard-'+req.session.vacancies) } }) // ------------------------------- // #NOTIFCATIONS // ------------------------------- router.post('/' + base_url + '/notifications/receive-notifications', function (req, res) { if(req.body.receive_notification == "yes"){ req.session.receive_notification = 'yes' req.session.has_notifications = 'no' res.redirect(301, '/' + base_url + '/notifications/notification-preferences-new'); }else{ res.redirect(301, '/' + base_url + '/dashboard-'+req.session.vacancies) } }) router.get('/' + base_url + '/notifications/notification-preferences', function (req, res) { var page=base_url + "/notifications/notification-preferences" if(req.session.has_notifications == "no"){ page= base_url + '/notifications/notification-preferences-new' } res.render(page , { "data" : req.session, "new" : req.query.new, } ) }) router.post('/' + base_url + '/notifications/notification-preferences', function (req, res) { if(req.body.receive_notification != "_unchecked"){ req.session.force_notifcation_setup = "no" req.session.has_notifications = "yes" res.redirect(301, '/' + base_url + '/notifications/notificaiton-confirmation?new=no') }else{ req.session.has_notifications = "no" res.redirect(301, '/' + base_url + '/notifications/notificaiton-confirmation-unsubscribe') } }) router.post('/' + base_url + '/notifications/notification-preferences-new', function (req, res) { if(req.body.receive_notification){ req.session.force_notifcation_setup = "no" req.session.has_notifications = "yes" } res.redirect(301, '/' + base_url + '/notifications/notificaiton-confirmation?new=yes') }) router.get('/' + base_url + '/notifications/notificaiton-confirmation', function (req, res) { res.render(base_url + '/notifications/notificaiton-confirmation', { "data" : req.session, "new" : req.query.new, } ) }) router.post('/' + base_url + '/notifications/notificaiton-confirmation', function (req, res) { res.redirect(301, '/' + base_url + '/dashboard-'+req.session.vacancies) }) router.post('/' + base_url + '/notifications/notificaiton-confirmation-unsubscribe', function (req, res) { res.redirect(301, '/' + base_url + '/dashboard-'+req.session.vacancies) }) router.get('/' + base_url + '/reports/dashboard', function (req, res) { res.render(base_url + '/reports/dashboard', { "data" : req.session, "query" : req.query, } ) }) router.post('/' + base_url + '/account/clone-dates', function (req, res) { if(req.body.change_date == "yes"){ res.redirect(301, '/' + base_url + '/account/clone-location') }else{ res.redirect(301, '/' + base_url + '/account/clone-change-dates') } }) router.get('/' + base_url + '/reports/download', function(req, res){ var filePath = 'public/files/download.csv'; var fileName = 'download.csv'; var path = require('path'); res.download(path.resolve(filePath), 'download.csv'); }); router.get('/' + base_url + '/create/*', function (req, res) { var url = require('url') var path= (url.parse(req.url).pathname) var page = path.substr(req.originalUrl.lastIndexOf('/') + 1) console.log("get page: "+page) res.render(base_url + '/create/'+page, { "data" : req.session, "query" : req.query, "training" : training, "locations" : locations, } ) }); router.get('/' + base_url + '/account/*', function (req, res) { var url = require('url') var path= (url.parse(req.url).pathname) var page = path.substr(req.originalUrl.lastIndexOf('/') + 1) console.log("get page: "+page) res.render(base_url + '/account/'+page, { "data" : req.session, "query" : req.query, "training" : training, "locations" : locations, } ) }); }
# Copyright (c) 2020 PaddlePaddle Authors. 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. from ..fluid import core __all__ = [] def Singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton class OpUpdateInfoHelper(object): def __init__(self, info): self._info = info def verify_key_value(self, name=''): result = False key_funcs = { core.OpAttrInfo: 'name', core.OpInputOutputInfo: 'name', } if name == '': result = True elif type(self._info) in key_funcs: if getattr(self._info, key_funcs[type(self._info)])() == name: result = True return result @Singleton class OpLastCheckpointChecker(object): def __init__(self): self.raw_version_map = core.get_op_version_map() self.checkpoints_map = {} self._construct_map() def _construct_map(self): for op_name in self.raw_version_map: last_checkpoint = self.raw_version_map[op_name].checkpoints()[-1] infos = last_checkpoint.version_desc().infos() self.checkpoints_map[op_name] = infos def filter_updates(self, op_name, type=core.OpUpdateType.kInvalid, key=''): updates = [] if op_name in self.checkpoints_map: for update in self.checkpoints_map[op_name]: if (update.type() == type) or (type == core.OpUpdateType.kInvalid): if OpUpdateInfoHelper(update.info()).verify_key_value(key): updates.append(update.info()) return updates
print("""13 aozccqxeesvgg bapzdcrxfetvh bcaqzecsxgeuv pbdarzfctxhev yqbeaszgcuxie dyrbfatzhcvxj deysbgauzicwx rdfytbhavzjcx wsdgyubiawzkc fwtdhyvbjaxzl fgwudiywbkayz tfhwvdjyxblaz uufiwwdkyybma """)
var searchData= [ ['xml_5frpc_5fclient',['XML_RPC_Client',['../class_x_m_l___r_p_c___client.html',1,'']]], ['xml_5frpc_5fmessage',['XML_RPC_Message',['../class_x_m_l___r_p_c___message.html',1,'']]], ['xml_5frpc_5fresponse',['XML_RPC_Response',['../class_x_m_l___r_p_c___response.html',1,'']]], ['xml_5frpc_5fvalues',['XML_RPC_Values',['../class_x_m_l___r_p_c___values.html',1,'']]], ['xmlrpc_5fdecoder',['xmlrpc_decoder',['../class_x_m_l___r_p_c___response.html#a44f453c58a4aad3ccb76dd9926f9fa64',1,'XML_RPC_Response']]] ];
export default [ { path: "/", text: "home", }, { path: "/tours", text: "tours", }, { path: "/blog", text: "blog", }, { path: "/contact", text: "contact", } ];
const chalk = require('chalk') const iconv = require('iconv-lite') const ora = require('ora') const padStart = String.prototype.padStart const log = console.log const format = (label, msg) => { if (!msg) { return '' } return msg.split('\n').map((line, i) => { return i === 0 ? `${label} ${line}` : padStart.call(line, chalk.reset(label).length) }).join('\n') } const chalkTag = msg => chalk.bgBlackBright.white.dim(` ${msg} `) const Log = { error(message, tag) { log(format(chalk.bgRed.black(' ERROR ') + (tag ? chalkTag(tag) : ''), message)) }, success (message, tag) { log(format(chalk.bgGreen.black(' SUCCESS ') + (tag ? chalkTag(tag) : ''), message)) }, green(message) { log(chalk.green(message)) }, blue(message) { log(chalk.blue(message)) } } const Helper = { getArr(str, separator = ',') { return str.split(separator) } } const Common = { getLuckNumber () { return ~~(Math.random() * 10) }, getTitle(str, color = 'green') { const baseLength = 30 const lastSpace = baseLength - str.length const left = ~~(lastSpace / 2) const right = lastSpace - left const title = chalk[color].bold.underline(str) const leftString = Array.from({length: left}).fill('=').join('') const rightString = Array.from({length: right}).fill('=').join('') return leftString + ' ' + title + ' ' + rightString } } const Time = { get today () { const date = new Date() const dateArr = [ date.getFullYear(), date.getMonth() + 1, date.getDate() ] return dateArr.join('-') } } // Tool模块 const Tool = { transformToLink (str) { // 让一个类链接变成一个链接 const prefix = 'http://' if (Tool.checkIsLinkLike(str) && !~str.indexOf(prefix)) { return prefix + str } return str }, checkIsLinkLike (str) { // 检测一个字符串是不是一个类链接 // http://xxx 、xxx.com字样 、http://xxx.net const reg = /^(https?:\/\/)?\w+\.[a-z0-9_.]+/g return reg.test(str) }, getUriEncodeGBk (str, encode = 'gbk') { const buf = iconv.encode(str, encode) return Array.prototype.map.call(buf, (char) => { const hex = char.toString(16) return '%' + hex }).join('') }, spinnerFactory (text = '电影天堂数据正在拼命加载中...') { return ora({ spinner: 'dots', text: chalk.yellow(text) }) } } module.exports = { error: Log.error, success: Log.success, Log, Helper, Time, Common, Tool }
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: ['@babel/polyfill', './src/index.tsx', './src/index.css'], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, '../../dist/client'), publicPath: '/' }, devtool: 'source-map', resolve: { extensions: ['.ts', '.tsx', '.js'] }, module: { rules: [ { test: /\.(ts|tsx)$/, loader: 'ts-loader', exclude: /(node_modules|bower_components)/ }, { test: /\.scss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader?sourceMap', options: { sourceMap: true } } ] }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /.jpe?g$|.gif$|.png$|.svg$|.woff$|.woff2$|.ttf$|.eot$/, use: [ { loader: 'url-loader', options: { limit: 10000 } } ] } ] }, plugins: [ // new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.LoaderOptionsPlugin({ debug: true }), new HtmlWebpackPlugin({ template: './public/index.html', inject: 'body', filename: 'index.html' }), new webpack.ProvidePlugin({ React: 'React', react: 'React', 'window.react': 'React', 'window.React': 'React', }), ], devServer: { port: 8000, proxy: { '/api/*': { target: 'http://localhost:3000', }, }, historyApiFallback: true }, 'externals': { } };
var z = {}; var _z = z, x = babelHelpers.objectWithoutProperties(_z, []); var _z2 = z, x = _z2.x, y = babelHelpers.objectWithoutProperties(_z2, ["x"]); var _z3 = z, x = _z3[x], y = babelHelpers.objectWithoutProperties(_z3, [x]); (function (_ref) { var x = _ref.x, y = babelHelpers.objectWithoutProperties(_ref, ["x"]); }); var _o = o; x = _o.x; y = _o.y; z = babelHelpers.objectWithoutProperties(_o, ["x", "y"]); _o;
"""Sample for getting nexar token with login.""" import argparse import pyperclip from nexar_token import get_token_with_login if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("client_id", help="The client ID.", type=str) parser.add_argument("client_secret", help="The client secret.", type=str) parser.add_argument("scope", help="The scope.", nargs="+", type=str) args = parser.parse_args() token = get_token_with_login(args.client_id, args.client_secret, args.scope)["access_token"] pyperclip.copy(token) print("\nYour token has been copied to the clipboard")
["^ ","~:resource-id",["~:shadow.build.classpath/resource","goog/dom/vendor.js"],"~:js","goog.provide(\"goog.dom.vendor\");\ngoog.require(\"goog.string\");\ngoog.require(\"goog.userAgent\");\n/**\n * @return {?string}\n */\ngoog.dom.vendor.getVendorJsPrefix = function() {\n if (goog.userAgent.WEBKIT) {\n return \"Webkit\";\n } else {\n if (goog.userAgent.GECKO) {\n return \"Moz\";\n } else {\n if (goog.userAgent.IE) {\n return \"ms\";\n } else {\n if (goog.userAgent.OPERA) {\n return \"O\";\n }\n }\n }\n }\n return null;\n};\n/**\n * @return {?string}\n */\ngoog.dom.vendor.getVendorPrefix = function() {\n if (goog.userAgent.WEBKIT) {\n return \"-webkit\";\n } else {\n if (goog.userAgent.GECKO) {\n return \"-moz\";\n } else {\n if (goog.userAgent.IE) {\n return \"-ms\";\n } else {\n if (goog.userAgent.OPERA) {\n return \"-o\";\n }\n }\n }\n }\n return null;\n};\n/**\n * @param {string} propertyName\n * @param {!Object=} opt_object\n * @return {?string}\n */\ngoog.dom.vendor.getPrefixedPropertyName = function(propertyName, opt_object) {\n if (opt_object && propertyName in opt_object) {\n return propertyName;\n }\n var prefix = goog.dom.vendor.getVendorJsPrefix();\n if (prefix) {\n prefix = prefix.toLowerCase();\n var prefixedPropertyName = prefix + goog.string.toTitleCase(propertyName);\n return opt_object === undefined || prefixedPropertyName in opt_object ? prefixedPropertyName : null;\n }\n return null;\n};\n/**\n * @param {string} eventType\n * @return {string}\n */\ngoog.dom.vendor.getPrefixedEventType = function(eventType) {\n var prefix = goog.dom.vendor.getVendorJsPrefix() || \"\";\n return (prefix + eventType).toLowerCase();\n};\n","~:source","// Copyright 2012 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview Vendor prefix getters.\n */\n\ngoog.provide('goog.dom.vendor');\n\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\n\n\n/**\n * Returns the JS vendor prefix used in CSS properties. Different vendors\n * use different methods of changing the case of the property names.\n *\n * @return {?string} The JS vendor prefix or null if there is none.\n */\ngoog.dom.vendor.getVendorJsPrefix = function() {\n if (goog.userAgent.WEBKIT) {\n return 'Webkit';\n } else if (goog.userAgent.GECKO) {\n return 'Moz';\n } else if (goog.userAgent.IE) {\n return 'ms';\n } else if (goog.userAgent.OPERA) {\n return 'O';\n }\n\n return null;\n};\n\n\n/**\n * Returns the vendor prefix used in CSS properties.\n *\n * @return {?string} The vendor prefix or null if there is none.\n */\ngoog.dom.vendor.getVendorPrefix = function() {\n if (goog.userAgent.WEBKIT) {\n return '-webkit';\n } else if (goog.userAgent.GECKO) {\n return '-moz';\n } else if (goog.userAgent.IE) {\n return '-ms';\n } else if (goog.userAgent.OPERA) {\n return '-o';\n }\n\n return null;\n};\n\n\n/**\n * @param {string} propertyName A property name.\n * @param {!Object=} opt_object If provided, we verify if the property exists in\n * the object.\n * @return {?string} A vendor prefixed property name, or null if it does not\n * exist.\n */\ngoog.dom.vendor.getPrefixedPropertyName = function(propertyName, opt_object) {\n // We first check for a non-prefixed property, if available.\n if (opt_object && propertyName in opt_object) {\n return propertyName;\n }\n var prefix = goog.dom.vendor.getVendorJsPrefix();\n if (prefix) {\n prefix = prefix.toLowerCase();\n var prefixedPropertyName = prefix + goog.string.toTitleCase(propertyName);\n return (opt_object === undefined || prefixedPropertyName in opt_object) ?\n prefixedPropertyName :\n null;\n }\n return null;\n};\n\n\n/**\n * @param {string} eventType An event type.\n * @return {string} A lower-cased vendor prefixed event type.\n */\ngoog.dom.vendor.getPrefixedEventType = function(eventType) {\n var prefix = goog.dom.vendor.getVendorJsPrefix() || '';\n return (prefix + eventType).toLowerCase();\n};\n","~:compiled-at",1587990774984,"~:source-map-json","{\n\"version\":3,\n\"file\":\"goog.dom.vendor.js\",\n\"lineCount\":71,\n\"mappings\":\"AAkBAA,IAAAC,QAAA,CAAa,iBAAb,CAAA;AAEAD,IAAAE,QAAA,CAAa,aAAb,CAAA;AACAF,IAAAE,QAAA,CAAa,gBAAb,CAAA;AASA;;;AAAAF,IAAAG,IAAAC,OAAAC,kBAAA,GAAoCC,QAAQ,EAAG;AAC7C,MAAIN,IAAAO,UAAAC,OAAJ;AACE,WAAO,QAAP;AADF;AAEO,QAAIR,IAAAO,UAAAE,MAAJ;AACL,aAAO,KAAP;AADK;AAEA,UAAIT,IAAAO,UAAAG,GAAJ;AACL,eAAO,IAAP;AADK;AAEA,YAAIV,IAAAO,UAAAI,MAAJ;AACL,iBAAO,GAAP;AADK;AAFA;AAFA;AAFP;AAUA,SAAO,IAAP;AAX6C,CAA/C;AAoBA;;;AAAAX,IAAAG,IAAAC,OAAAQ,gBAAA,GAAkCC,QAAQ,EAAG;AAC3C,MAAIb,IAAAO,UAAAC,OAAJ;AACE,WAAO,SAAP;AADF;AAEO,QAAIR,IAAAO,UAAAE,MAAJ;AACL,aAAO,MAAP;AADK;AAEA,UAAIT,IAAAO,UAAAG,GAAJ;AACL,eAAO,KAAP;AADK;AAEA,YAAIV,IAAAO,UAAAI,MAAJ;AACL,iBAAO,IAAP;AADK;AAFA;AAFA;AAFP;AAUA,SAAO,IAAP;AAX2C,CAA7C;AAsBA;;;;;AAAAX,IAAAG,IAAAC,OAAAU,wBAAA,GAA0CC,QAAQ,CAACC,YAAD,EAAeC,UAAf,CAA2B;AAE3E,MAAIA,UAAJ,IAAkBD,YAAlB,IAAkCC,UAAlC;AACE,WAAOD,YAAP;AADF;AAGA,MAAIE,SAASlB,IAAAG,IAAAC,OAAAC,kBAAA,EAAb;AACA,MAAIa,MAAJ,CAAY;AACVA,UAAA,GAASA,MAAAC,YAAA,EAAT;AACA,QAAIC,uBAAuBF,MAAvBE,GAAgCpB,IAAAqB,OAAAC,YAAA,CAAwBN,YAAxB,CAApC;AACA,WAAQC,UAAD,KAAgBM,SAAhB,IAA6BH,oBAA7B,IAAqDH,UAArD,GACHG,oBADG,GAEH,IAFJ;AAHU;AAOZ,SAAO,IAAP;AAb2E,CAA7E;AAqBA;;;;AAAApB,IAAAG,IAAAC,OAAAoB,qBAAA,GAAuCC,QAAQ,CAACC,SAAD,CAAY;AACzD,MAAIR,SAASlB,IAAAG,IAAAC,OAAAC,kBAAA,EAATa,IAAgD,EAApD;AACA,SAAOC,CAACD,MAADC,GAAUO,SAAVP,aAAA,EAAP;AAFyD,CAA3D;;\",\n\"sources\":[\"goog/dom/vendor.js\"],\n\"sourcesContent\":[\"// Copyright 2012 The Closure Library Authors. All Rights Reserved.\\n//\\n// Licensed under the Apache License, Version 2.0 (the \\\"License\\\");\\n// you may not use this file except in compliance with the License.\\n// You may obtain a copy of the License at\\n//\\n// http://www.apache.org/licenses/LICENSE-2.0\\n//\\n// Unless required by applicable law or agreed to in writing, software\\n// distributed under the License is distributed on an \\\"AS-IS\\\" BASIS,\\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n// See the License for the specific language governing permissions and\\n// limitations under the License.\\n\\n/**\\n * @fileoverview Vendor prefix getters.\\n */\\n\\ngoog.provide('goog.dom.vendor');\\n\\ngoog.require('goog.string');\\ngoog.require('goog.userAgent');\\n\\n\\n/**\\n * Returns the JS vendor prefix used in CSS properties. Different vendors\\n * use different methods of changing the case of the property names.\\n *\\n * @return {?string} The JS vendor prefix or null if there is none.\\n */\\ngoog.dom.vendor.getVendorJsPrefix = function() {\\n if (goog.userAgent.WEBKIT) {\\n return 'Webkit';\\n } else if (goog.userAgent.GECKO) {\\n return 'Moz';\\n } else if (goog.userAgent.IE) {\\n return 'ms';\\n } else if (goog.userAgent.OPERA) {\\n return 'O';\\n }\\n\\n return null;\\n};\\n\\n\\n/**\\n * Returns the vendor prefix used in CSS properties.\\n *\\n * @return {?string} The vendor prefix or null if there is none.\\n */\\ngoog.dom.vendor.getVendorPrefix = function() {\\n if (goog.userAgent.WEBKIT) {\\n return '-webkit';\\n } else if (goog.userAgent.GECKO) {\\n return '-moz';\\n } else if (goog.userAgent.IE) {\\n return '-ms';\\n } else if (goog.userAgent.OPERA) {\\n return '-o';\\n }\\n\\n return null;\\n};\\n\\n\\n/**\\n * @param {string} propertyName A property name.\\n * @param {!Object=} opt_object If provided, we verify if the property exists in\\n * the object.\\n * @return {?string} A vendor prefixed property name, or null if it does not\\n * exist.\\n */\\ngoog.dom.vendor.getPrefixedPropertyName = function(propertyName, opt_object) {\\n // We first check for a non-prefixed property, if available.\\n if (opt_object && propertyName in opt_object) {\\n return propertyName;\\n }\\n var prefix = goog.dom.vendor.getVendorJsPrefix();\\n if (prefix) {\\n prefix = prefix.toLowerCase();\\n var prefixedPropertyName = prefix + goog.string.toTitleCase(propertyName);\\n return (opt_object === undefined || prefixedPropertyName in opt_object) ?\\n prefixedPropertyName :\\n null;\\n }\\n return null;\\n};\\n\\n\\n/**\\n * @param {string} eventType An event type.\\n * @return {string} A lower-cased vendor prefixed event type.\\n */\\ngoog.dom.vendor.getPrefixedEventType = function(eventType) {\\n var prefix = goog.dom.vendor.getVendorJsPrefix() || '';\\n return (prefix + eventType).toLowerCase();\\n};\\n\"],\n\"names\":[\"goog\",\"provide\",\"require\",\"dom\",\"vendor\",\"getVendorJsPrefix\",\"goog.dom.vendor.getVendorJsPrefix\",\"userAgent\",\"WEBKIT\",\"GECKO\",\"IE\",\"OPERA\",\"getVendorPrefix\",\"goog.dom.vendor.getVendorPrefix\",\"getPrefixedPropertyName\",\"goog.dom.vendor.getPrefixedPropertyName\",\"propertyName\",\"opt_object\",\"prefix\",\"toLowerCase\",\"prefixedPropertyName\",\"string\",\"toTitleCase\",\"undefined\",\"getPrefixedEventType\",\"goog.dom.vendor.getPrefixedEventType\",\"eventType\"]\n}\n"]
const Notifier = require('../lib/Notifier') const notifier = new Notifier({ barkKey: process.env.BARK_KEY, larkWebhook: process.env.LARK_WEBHOOK, workWechat: process.env.QYWX_SEND_CONF, serverChanToken: process.env.SC_SEND_KEY, telegram: { botToken: process.env.TG_BOT_TOKEN, userId: process.env.TG_USER_ID } }) async function main() { console.log('\n## 消息推送 ##') try { const res = await Promise.all( notifier.notify('推送测试', '这是推送测试的消息' + Date.now()) ) console.log('result', res) } catch (e) { console.log('执行失败', e) } } module.exports = main
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ fake_head = ListNode(None) fake_head.next = head front = fake_head for _ in range(1, m): front = front.next count = n - m end = front.next while count > 0: curr = end.next end.next = curr.next curr.next = front.next front.next = curr count -= 1 return fake_head.next
import React from "react"; import { shallow } from "enzyme"; import Message from "../Message"; let wrapped; // beforeEach(() => { // wrapped = shallow(<Message items={items} formValues={formValues} />); // }); afterEach(() => { wrapped.unmount(); }); describe("Message tests", () => { it("should say instructions for search", () => { const items = []; const formValues1 = {}; wrapped = shallow(<Message items={items} formValues={formValues1} />); expect( wrapped.contains( "Please enter query and click SEARCH button above, results appear here." ) ).toBeTruthy(); }); it("should say search results", () => { const items = ["random string"]; const formValues2 = { search: { submitSucceeded: true } }; wrapped = shallow(<Message items={items} formValues={formValues2} />); expect(wrapped.contains("SEARCH results:")).toBeTruthy(); }); it("should say no search results", () => { const items = []; const formValues3 = { search: { submitSucceeded: true } }; wrapped = shallow(<Message items={items} formValues={formValues3} />); expect(wrapped.contains("Your query returned no results.")).toBeTruthy(); }); });
import Vue from 'vue' import Router from 'vue-router' const routerOptions = [ { path: '/', component: 'Home' }, { path: '/about', component: 'About' }, { path: '/login', component: 'Login' }, { path: '/register', component: 'Register' }, { path: '/course/view/:courseid', component: 'Course', name: 'course' }, { path: '/techstack', component: 'TechStack' }, { path: '/dashboard', component: 'Dashboard' }, { path: '/course/add', component: 'CourseAdd' }, { path: '*', component: 'NotFound' } ] const routes = routerOptions.map(route => { return { ...route, component: () => import(`@/components/${route.component}.vue`) } }) Vue.use(Router) export default new Router({ routes, mode: 'history', linkActiveClass: 'mdl-navigation__link--current' })
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class SPConvBlock(nn.Module): """ SuperPointNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding): super(SPConvBlock, self).__init__() self.conv = nn.Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=True) self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.activ(x) return x def sp_conv1x1(in_channels, out_channels): """ 1x1 version of the SuperPointNet specific convolution layer. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ return nn.Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, bias=True) def sp_conv3x3_block(in_channels, out_channels): """ 3x3 version of the SuperPointNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ return SPConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1) class SPHead(nn.Module): """ SuperPointNet head block. Parameters: ---------- in_channels : int Number of input channels. mid_channels : int Number of middle channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, mid_channels, out_channels): super(SPHead, self).__init__() self.conv1 = sp_conv3x3_block( in_channels=in_channels, out_channels=mid_channels) self.conv2 = sp_conv1x1( in_channels=mid_channels, out_channels=out_channels) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x class SPDetector(nn.Module): """ SuperPointNet detector. Parameters: ---------- in_channels : int Number of input channels. mid_channels : int Number of middle channels. conf_thresh : float, default 0.015 Confidence threshold. nms_dist : int, default 4 NMS distance. border_size : int, default 4 Image border size to remove points. reduction : int, default 8 Feature reduction factor. """ def __init__(self, in_channels, mid_channels, conf_thresh=0.015, nms_dist=4, border_size=4, reduction=8): super(SPDetector, self).__init__() self.conf_thresh = conf_thresh self.nms_dist = nms_dist self.border_size = border_size self.reduction = reduction num_classes = reduction * reduction + 1 self.detector = SPHead( in_channels=in_channels, mid_channels=mid_channels, out_channels=num_classes) def nms_fast(self, in_corners, H, W, dist_thresh): """ Run a faster approximate Non-Max-Suppression on numpy corners shaped: 3xN [x_i,y_i,conf_i]^T Algo summary: Create a grid sized HxW. Assign each corner location a 1, rest are zeros. Iterate through all the 1's and convert them either to -1 or 0. Suppress points by setting nearby values to 0. Grid Value Legend: -1 : Kept. 0 : Empty or suppressed. 1 : To be processed (converted to either kept or supressed). NOTE: The NMS first rounds points to integers, so NMS distance might not be exactly dist_thresh. It also assumes points are within image boundaries. Inputs in_corners - 3xN numpy array with corners [x_i, y_i, confidence_i]^T. H - Image height. W - Image width. dist_thresh - Distance to suppress, measured as an infinty norm distance. Returns nmsed_corners - 3xN numpy matrix with surviving corners. nmsed_inds - N length numpy vector with surviving corner indices. """ grid = np.zeros((H, W)).astype(int) # Track NMS data. inds = np.zeros((H, W)).astype(int) # Store indices of points. # Sort by confidence and round to nearest int. inds1 = np.argsort(-in_corners[2, :]) corners = in_corners[:, inds1] rcorners = corners[:2, :].round().astype(int) # Rounded corners. # Check for edge case of 0 or 1 corners. if rcorners.shape[1] == 0: return np.zeros((3, 0)).astype(int), np.zeros(0).astype(int) if rcorners.shape[1] == 1: out = np.vstack((rcorners, in_corners[2])).reshape(3, 1) return out, np.zeros((1)).astype(int) # Initialize the grid. for i, rc in enumerate(rcorners.T): grid[rcorners[1, i], rcorners[0, i]] = 1 inds[rcorners[1, i], rcorners[0, i]] = i # Pad the border of the grid, so that we can NMS points near the border. pad = dist_thresh grid = np.pad(grid, ((pad, pad), (pad, pad)), mode='constant') # Iterate through points, highest to lowest conf, suppress neighborhood. count = 0 for i, rc in enumerate(rcorners.T): # Account for top and left padding. pt = (rc[0] + pad, rc[1] + pad) if grid[pt[1], pt[0]] == 1: # If not yet suppressed. grid[pt[1] - pad:pt[1] + pad + 1, pt[0] - pad:pt[0] + pad + 1] = 0 grid[pt[1], pt[0]] = -1 count += 1 # Get all surviving -1's and return sorted array of remaining corners. keepy, keepx = np.where(grid == -1) keepy, keepx = keepy - pad, keepx - pad inds_keep = inds[keepy, keepx] out = corners[:, inds_keep] values = out[-1, :] inds2 = np.argsort(-values) out = out[:, inds2] out_inds = inds1[inds_keep[inds2]] return out, out_inds def forward(self, x): x_height, x_width = x.size()[-2:] img_height = x_height * self.reduction img_width = x_width * self.reduction semi = self.detector(x) dense = semi.softmax(dim=1) nodust = dense[:, :-1, :, :] heatmap = nodust.permute(0, 2, 3, 1) heatmap = heatmap.reshape((-1, x_height, x_height, self.reduction, self.reduction)) heatmap = heatmap.permute(0, 1, 3, 2, 4) heatmap = heatmap.reshape((-1, x_height * self.reduction, x_width * self.reduction)) heatmap_mask = (heatmap >= self.conf_thresh) pts1 = torch.nonzero(heatmap_mask) pts2 = torch.masked_select(heatmap, heatmap_mask) heatmap = heatmap.data.cpu().numpy().squeeze() xs, ys = np.where(heatmap >= self.conf_thresh) # Confidence threshold. if len(xs) == 0: return np.zeros((3, 0)), None, None pts = np.zeros((3, len(xs))) # Populate point data sized 3xN. pts[0, :] = ys pts[1, :] = xs pts[2, :] = heatmap[xs, ys] pts, _ = self.nms_fast(pts, img_height, img_width, dist_thresh=self.nms_dist) # Apply NMS. inds = np.argsort(pts[2, :]) pts = pts[:, inds[::-1]] # Sort by confidence. # Remove points along border. bord = self.border_size toremoveW = np.logical_or(pts[0, :] < bord, pts[0, :] >= (img_width - bord)) toremoveH = np.logical_or(pts[1, :] < bord, pts[1, :] >= (img_height - bord)) toremove = np.logical_or(toremoveW, toremoveH) pts = pts[:, ~toremove] return pts class SPDescriptor(nn.Module): """ SuperPointNet descriptor generator. Parameters: ---------- in_channels : int Number of input channels. mid_channels : int Number of middle channels. descriptor_length : int, default 256 Descriptor length. reduction : int, default 8 Feature reduction factor. """ def __init__(self, in_channels, mid_channels, descriptor_length=256, reduction=8): super(SPDescriptor, self).__init__() self.desc_length = descriptor_length self.reduction = reduction self.head = SPHead( in_channels=in_channels, mid_channels=mid_channels, out_channels=descriptor_length) def nms_fast(self, in_corners, H, W, dist_thresh): """ Run a faster approximate Non-Max-Suppression on numpy corners shaped: 3xN [x_i,y_i,conf_i]^T Algo summary: Create a grid sized HxW. Assign each corner location a 1, rest are zeros. Iterate through all the 1's and convert them either to -1 or 0. Suppress points by setting nearby values to 0. Grid Value Legend: -1 : Kept. 0 : Empty or suppressed. 1 : To be processed (converted to either kept or supressed). NOTE: The NMS first rounds points to integers, so NMS distance might not be exactly dist_thresh. It also assumes points are within image boundaries. Inputs in_corners - 3xN numpy array with corners [x_i, y_i, confidence_i]^T. H - Image height. W - Image width. dist_thresh - Distance to suppress, measured as an infinty norm distance. Returns nmsed_corners - 3xN numpy matrix with surviving corners. nmsed_inds - N length numpy vector with surviving corner indices. """ grid = np.zeros((H, W)).astype(int) # Track NMS data. inds = np.zeros((H, W)).astype(int) # Store indices of points. # Sort by confidence and round to nearest int. inds1 = np.argsort(-in_corners[2, :]) corners = in_corners[:, inds1] rcorners = corners[:2, :].round().astype(int) # Rounded corners. # Check for edge case of 0 or 1 corners. if rcorners.shape[1] == 0: return np.zeros((3, 0)).astype(int), np.zeros(0).astype(int) if rcorners.shape[1] == 1: out = np.vstack((rcorners, in_corners[2])).reshape(3, 1) return out, np.zeros((1)).astype(int) # Initialize the grid. for i, rc in enumerate(rcorners.T): grid[rcorners[1, i], rcorners[0, i]] = 1 inds[rcorners[1, i], rcorners[0, i]] = i # Pad the border of the grid, so that we can NMS points near the border. pad = dist_thresh grid = np.pad(grid, ((pad, pad), (pad, pad)), mode='constant') # Iterate through points, highest to lowest conf, suppress neighborhood. count = 0 for i, rc in enumerate(rcorners.T): # Account for top and left padding. pt = (rc[0] + pad, rc[1] + pad) if grid[pt[1], pt[0]] == 1: # If not yet suppressed. grid[pt[1] - pad:pt[1] + pad + 1, pt[0] - pad:pt[0] + pad + 1] = 0 grid[pt[1], pt[0]] = -1 count += 1 # Get all surviving -1's and return sorted array of remaining corners. keepy, keepx = np.where(grid == -1) keepy, keepx = keepy - pad, keepx - pad inds_keep = inds[keepy, keepx] out = corners[:, inds_keep] values = out[-1, :] inds2 = np.argsort(-values) out = out[:, inds2] out_inds = inds1[inds_keep[inds2]] return out, out_inds def forward(self, x, pts): x_height, x_width = x.size()[-2:] coarse_desc = self.head(x) coarse_desc = F.normalize(coarse_desc) if pts.shape[1] == 0: descriptors = np.zeros((self.desc_length, 0)) else: # Interpolate into descriptor map using 2D point locations. sampled_pts = torch.from_numpy(pts[:2, :].copy()) sampled_pts[0, :] = (sampled_pts[0, :] / (float(x_height * self.reduction) / 2.)) - 1. sampled_pts[1, :] = (sampled_pts[1, :] / (float(x_width * self.reduction) / 2.)) - 1. sampled_pts = sampled_pts.transpose(0, 1).contiguous() sampled_pts = sampled_pts.view(1, 1, -1, 2) sampled_pts = sampled_pts.float() sampled_pts = sampled_pts.to(x.device) descriptors = F.grid_sample(coarse_desc, sampled_pts) descriptors = descriptors.data.cpu().numpy().reshape(self.desc_length, -1) descriptors /= np.linalg.norm(descriptors, axis=0)[np.newaxis, :] return descriptors class SuperPointNet(nn.Module): """ Pytorch definition of SuperPoint Network. """ def __init__(self): super(SuperPointNet, self).__init__() in_channels = 1 channels_per_layers = [64, 64, 128, 128] layers = [2, 2, 2, 2] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] final_block_channels = 256 self.features = nn.Sequential() for i, channels_per_stage in enumerate(channels): stage = nn.Sequential() for j, out_channels in enumerate(channels_per_stage): if i != 0: stage.add_module("reduce{}".format(i + 1), nn.MaxPool2d( kernel_size=2, stride=2)) stage.add_module("unit{}".format(j + 1), sp_conv3x3_block( in_channels=in_channels, out_channels=out_channels)) in_channels = out_channels self.features.add_module("stage{}".format(i + 1), stage) self.detector = SPDetector( in_channels=in_channels, mid_channels=final_block_channels) self.descriptor = SPDescriptor( in_channels=in_channels, mid_channels=final_block_channels) def forward(self, x): x = self.features(x) feature_points = self.detector(x) descriptors = self.descriptor(x, feature_points) return feature_points, descriptors def oth_superpointnet(pretrained=False, **kwargs): return SuperPointNet(**kwargs) def _calc_width(net): import numpy as np net_params = filter(lambda p: p.requires_grad, net.parameters()) weight_count = 0 for param in net_params: weight_count += np.prod(param.size()) return weight_count def _test(): import torch pretrained = False models = [ oth_superpointnet, ] for model in models: net = model(pretrained=pretrained) # net.train() net.eval() weight_count = _calc_width(net) print("m={}, {}".format(model.__name__, weight_count)) assert (model != oth_superpointnet or weight_count == 1300865) x = torch.randn(1, 1, 224, 224) y = net(x) # y.sum().backward() assert (len(y) == 2) # assert (len(y) == 2) and (y[0].shape[0] == y[1].shape[0] == 1) and (y[0].shape[2] == y[1].shape[2] == 28) and\ # (y[0].shape[3] == y[1].shape[3] == 28) # assert (y[0].shape[1] == 65) and (y[1].shape[1] == 256) if __name__ == "__main__": _test()
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.undefined = mod.exports; } })(this, function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { "name": "--pf-c-alert--m-inline--BorderTopWidth", "value": "1px", "var": "var(--pf-c-alert--m-inline--BorderTopWidth)" }; });
"use strict"; var _addPageDependency = require("../../redux/actions/add-page-dependency"); const _ = require(`lodash`); const invariant = require(`invariant`); const { getDb, colls } = require(`./index`); function makeTypeCollName(type) { return `gatsby:nodeType:${type}`; } /** * Creates a collection that will contain nodes of a certain type. The * name of the collection for type `MyType` will be something like * `gatsby:nodeType:MyType` (see `makeTypeCollName`) */ function createNodeTypeCollection(type) { const collName = makeTypeCollName(type); const nodeTypesColl = getDb().getCollection(colls.nodeTypes.name); invariant(nodeTypesColl, `Collection ${colls.nodeTypes.name} should exist`); nodeTypesColl.insert({ type, collName }); // TODO what if `addCollection` fails? We will have inserted into // nodeTypesColl but no collection will exist. Need to make this // into a transaction const options = { unique: [`id`], indices: [`id`, `internal.counter`], disableMeta: true }; const coll = getDb().addCollection(collName, options); return coll; } /** * Returns the name of the collection that contains nodes of the * specified type, where type is the node's `node.internal.type` */ function getTypeCollName(type) { const nodeTypesColl = getDb().getCollection(colls.nodeTypes.name); invariant(nodeTypesColl, `Collection ${colls.nodeTypes.name} should exist`); const nodeTypeInfo = nodeTypesColl.by(`type`, type); return nodeTypeInfo ? nodeTypeInfo.collName : undefined; } /** * Returns a reference to the collection that contains nodes of the * specified type, where type is the node's `node.internal.type` */ function getNodeTypeCollection(type) { const typeCollName = getTypeCollName(type); let coll; if (typeCollName) { coll = getDb().getCollection(typeCollName); invariant(coll, `Type [${type}] Collection doesn't exist for nodeTypeInfo: [${typeCollName}]`); return coll; } else { return undefined; } } /** * Deletes all empty node type collections, unless `force` is true, in * which case it deletes the collections even if they have nodes in * them */ function deleteNodeTypeCollections(force = false) { const nodeTypesColl = getDb().getCollection(colls.nodeTypes.name); // find() returns all objects in collection const nodeTypes = nodeTypesColl.find(); for (const nodeType of nodeTypes) { const coll = getDb().getCollection(nodeType.collName); if (coll.count() === 0 || force) { getDb().removeCollection(coll.name); nodeTypesColl.remove(nodeType); } } } /** * Deletes all nodes from all the node type collections, including the * id -> type metadata. There will be no nodes related data in loki * after this is called */ function deleteAll() { const db = getDb(); if (db) { deleteNodeTypeCollections(true); db.getCollection(colls.nodeMeta.name).clear(); } } // /////////////////////////////////////////////////////////////////// // Queries // /////////////////////////////////////////////////////////////////// /** * Returns the node with `id` == id, or null if not found */ function getNode(id) { if (!id) { return null; } // First, find out which collection the node is in const nodeMetaColl = getDb().getCollection(colls.nodeMeta.name); invariant(nodeMetaColl, `nodeMeta collection should exist`); const nodeMeta = nodeMetaColl.by(`id`, id); if (nodeMeta) { // Now get the collection and query it by the `id` field, which // has an index on it const { typeCollName } = nodeMeta; const typeColl = getDb().getCollection(typeCollName); invariant(typeColl, `type collection ${typeCollName} referenced by nodeMeta but doesn't exist`); return typeColl.by(`id`, id); } else { return undefined; } } /** * Returns all nodes of a type (where `typeName == * node.internal.type`). This is an O(1) operation since nodes are * already stored in separate collections by type */ function getNodesByType(typeName) { invariant(typeName, `typeName is null`); const collName = getTypeCollName(typeName); const coll = getDb().getCollection(collName); if (!coll) return []; return coll.chain().simplesort(`internal.counter`).data(); } /** * Returns the collection of all nodes. This should be deprecated and * `getNodesByType` should be used instead. Or at least where possible */ function getNodes() { const nodeTypes = getTypes(); return _.flatMap(nodeTypes, nodeType => getNodesByType(nodeType)); } /** * Returns the unique collection of all node types */ function getTypes() { const nodeTypes = getDb().getCollection(colls.nodeTypes.name).data; return nodeTypes.map(nodeType => nodeType.type); } /** * Looks up the node by id, records a dependency between the node and * the path, and then returns the node * * @param {string} id node id to lookup * @param {string} path the page path to record a node dependency * against * @returns {Object} node or undefined if not found */ function getNodeAndSavePathDependency(id, path) { invariant(id, `id is null`); invariant(id, `path is null`); const node = getNode(id); (0, _addPageDependency.createPageDependency)({ path, nodeId: id }); return node; } /** * Determine if node has changed (by comparing its * `internal.contentDigest` * * @param {string} id * @param {string} digest * @returns {boolean} */ function hasNodeChanged(id, digest) { const node = getNode(id); if (!node) { return true; } else { return node.internal.contentDigest !== digest; } } // ///////////////////////////////////////////////////////////////// // Create/Update/Delete // /////////////////////////////////////////////////////////////////// /** * Creates a node in the DB. Will create a collection for the node * type if one hasn't been created yet * * @param {Object} node The node to add. Must have an `id` and * `internal.type` */ function createNode(node, oldNode) { invariant(node.internal, `node has no "internal" field`); invariant(node.internal.type, `node has no "internal.type" field`); invariant(node.id, `node has no "id" field`); const type = node.internal.type; // Loki doesn't provide "upsert", so if the node already exists, we // delete and then create it if (oldNode) { deleteNode(oldNode); } let nodeTypeColl = getNodeTypeCollection(type); if (!nodeTypeColl) { nodeTypeColl = createNodeTypeCollection(type); } const nodeMetaColl = getDb().getCollection(colls.nodeMeta.name); invariant(nodeMetaColl, `Collection ${colls.nodeMeta.name} should exist`); nodeMetaColl.insert({ id: node.id, typeCollName: nodeTypeColl.name }); // TODO what if this insert fails? We will have inserted the id -> // collName mapping, but there won't be any nodes in the type // collection. Need to create a transaction around this return nodeTypeColl.insert(node); } /** * Updates a node in the DB. The contents of `node` will completely * overwrite value in the DB. Note, `node` must be a loki node. i.e it * has `$loki` and `meta` fields. * * @param {Object} node The new node information. This should be all * the node information. Not just changes */ function updateNode(node) { invariant(node.internal, `node has no "internal" field`); invariant(node.internal.type, `node has no "internal.type" field`); invariant(node.id, `node has no "id" field`); const oldNode = getNode(node.id); return createNode(node, oldNode); } /** * Deletes a node from its type collection and removes its id -> * collName mapping. Function is idempotent. If the node has already * been deleted, this is a noop. * * @param {Object} the node to delete. Must have an `id` and * `internal.type` */ function deleteNode(node) { invariant(node.internal, `node has no "internal" field`); invariant(node.internal.type, `node has no "internal.type" field`); invariant(node.id, `node has no "id" field`); const type = node.internal.type; const nodeTypeColl = getNodeTypeCollection(type); if (!nodeTypeColl) { invariant(nodeTypeColl, `${type} collection doesn't exist. When trying to delete`); } const obj = nodeTypeColl.by(`id`, node.id); if (obj) { const nodeMetaColl = getDb().getCollection(colls.nodeMeta.name); invariant(nodeMetaColl, `Collection ${colls.nodeMeta.name} should exist`); nodeMetaColl.findAndRemove({ id: node.id }); // TODO What if this `remove()` fails? We will have removed the id // -> collName mapping, but not the actual node in the // collection. Need to make this into a transaction nodeTypeColl.remove(obj); } // idempotent. Do nothing if node wasn't already in DB } /** * deprecated */ function deleteNodes(nodes) { for (const node of nodes) { deleteNode(node); } } const saveResolvedNodes = async (nodeTypeNames, resolver) => { for (const typeName of nodeTypeNames) { const nodes = getNodesByType(typeName); const resolved = await Promise.all(nodes.map(async node => { node.__gatsby_resolved = await resolver(node); return node; })); const nodeColl = getNodeTypeCollection(typeName); if (nodeColl) { nodeColl.update(resolved); } } }; // Cleared on DELETE_CACHE let fieldUsages = null; const FIELD_INDEX_THRESHOLD = 5; // Every time we run a query, we increment a counter for each of its // fields, so that we can determine which fields are used the // most. Any time a field is seen more than `FIELD_INDEX_THRESHOLD` // times, we create a loki index so that future queries with that // field will execute faster. // times, we create a loki index so that future queries with that // field will execute faster. function ensureFieldIndexes(typeName, lokiArgs, sortArgs) { if (fieldUsages == null) { fieldUsages = {}; const { emitter } = require(`../../redux`); emitter.on(`DELETE_CACHE`, () => { for (const field in fieldUsages) { delete fieldUsages[field]; } }); } const nodeColl = getNodeTypeCollection(typeName); if (!fieldUsages[typeName]) { fieldUsages[typeName] = {}; } _.forEach(lokiArgs, (v, fieldName) => { // Increment the usages of the field _.update(fieldUsages[typeName], fieldName, n => n ? n + 1 : 1); // If we have crossed the threshold, then create the index if (_.get(fieldUsages[typeName], fieldName) >= FIELD_INDEX_THRESHOLD) { // Loki ensures that this is a noop if index already exists. E.g // if it was previously added via a sort field nodeColl.ensureIndex(fieldName); } }); } // /////////////////////////////////////////////////////////////////// // Reducer // /////////////////////////////////////////////////////////////////// function reducer(state = new Map(), action) { switch (action.type) { case `DELETE_CACHE`: deleteAll(); return null; case `CREATE_NODE`: { createNode(action.payload, action.oldNode); return null; } case `ADD_FIELD_TO_NODE`: case `ADD_CHILD_NODE_TO_PARENT_NODE`: updateNode(action.payload); return null; case `DELETE_NODE`: { if (action.payload) { deleteNode(action.payload); } return null; } case `DELETE_NODES`: { deleteNodes(action.fullNodes); return null; } default: return null; } } // /////////////////////////////////////////////////////////////////// // Exports // /////////////////////////////////////////////////////////////////// module.exports = { getNodeTypeCollection, getNodes, getNode, getNodesByType, getTypes, hasNodeChanged, getNodeAndSavePathDependency, createNode, updateNode, deleteNode, deleteNodeTypeCollections, deleteAll, reducer, saveResolvedNodes, ensureFieldIndexes }; //# sourceMappingURL=nodes.js.map
"use strict"; //# sourceMappingURL=outlined-keyboard-icon.d.js.map
import BarnesHutSolver from "./BarnesHutSolver" class ForceAtlas2BasedRepulsionSolver extends BarnesHutSolver { constructor(body, physicsBody, options) { super(body, physicsBody, options); } /** * Calculate the forces based on the distance. * * @param distance * @param dx * @param dy * @param node * @param parentBranch * @private */ _calculateForces(distance, dx, dy, node, parentBranch) { if (distance === 0) { distance = 0.1 * Math.random(); dx = distance; } if (this.overlapAvoidanceFactor < 1 && node.shape.radius) { distance = Math.max(0.1 + (this.overlapAvoidanceFactor * node.shape.radius), distance - node.shape.radius); } let degree = (node.edges.length + 1); // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce let gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance,2); let fx = dx * gravityForce; let fy = dy * gravityForce; this.physicsBody.forces[node.id].x += fx; this.physicsBody.forces[node.id].y += fy; } } export default ForceAtlas2BasedRepulsionSolver;
// manifesto v2.2.21 https://github.com/iiif-commons/manifesto (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.manifesto = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){ (function (global){ var Manifesto; (function (Manifesto) { var StringValue = /** @class */ (function () { function StringValue(value) { this.value = ""; if (value) { this.value = value.toLowerCase(); } } StringValue.prototype.toString = function () { return this.value; }; return StringValue; }()); Manifesto.StringValue = StringValue; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var AnnotationMotivation = /** @class */ (function (_super) { __extends(AnnotationMotivation, _super); function AnnotationMotivation() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. AnnotationMotivation.prototype.bookmarking = function () { return new AnnotationMotivation(AnnotationMotivation.BOOKMARKING.toString()); }; AnnotationMotivation.prototype.classifying = function () { return new AnnotationMotivation(AnnotationMotivation.CLASSIFYING.toString()); }; AnnotationMotivation.prototype.commenting = function () { return new AnnotationMotivation(AnnotationMotivation.COMMENTING.toString()); }; AnnotationMotivation.prototype.describing = function () { return new AnnotationMotivation(AnnotationMotivation.DESCRIBING.toString()); }; AnnotationMotivation.prototype.editing = function () { return new AnnotationMotivation(AnnotationMotivation.EDITING.toString()); }; AnnotationMotivation.prototype.highlighting = function () { return new AnnotationMotivation(AnnotationMotivation.HIGHLIGHTING.toString()); }; AnnotationMotivation.prototype.identifying = function () { return new AnnotationMotivation(AnnotationMotivation.IDENTIFYING.toString()); }; AnnotationMotivation.prototype.linking = function () { return new AnnotationMotivation(AnnotationMotivation.LINKING.toString()); }; AnnotationMotivation.prototype.moderating = function () { return new AnnotationMotivation(AnnotationMotivation.MODERATING.toString()); }; AnnotationMotivation.prototype.painting = function () { return new AnnotationMotivation(AnnotationMotivation.PAINTING.toString()); }; AnnotationMotivation.prototype.questioning = function () { return new AnnotationMotivation(AnnotationMotivation.QUESTIONING.toString()); }; AnnotationMotivation.prototype.replying = function () { return new AnnotationMotivation(AnnotationMotivation.REPLYING.toString()); }; AnnotationMotivation.prototype.tagging = function () { return new AnnotationMotivation(AnnotationMotivation.TAGGING.toString()); }; AnnotationMotivation.prototype.transcribing = function () { return new AnnotationMotivation(AnnotationMotivation.TRANSCRIBING.toString()); }; AnnotationMotivation.BOOKMARKING = new AnnotationMotivation("oa:bookmarking"); AnnotationMotivation.CLASSIFYING = new AnnotationMotivation("oa:classifying"); AnnotationMotivation.COMMENTING = new AnnotationMotivation("oa:commenting"); AnnotationMotivation.DESCRIBING = new AnnotationMotivation("oa:describing"); AnnotationMotivation.EDITING = new AnnotationMotivation("oa:editing"); AnnotationMotivation.HIGHLIGHTING = new AnnotationMotivation("oa:highlighting"); AnnotationMotivation.IDENTIFYING = new AnnotationMotivation("oa:identifying"); AnnotationMotivation.LINKING = new AnnotationMotivation("oa:linking"); AnnotationMotivation.MODERATING = new AnnotationMotivation("oa:moderating"); AnnotationMotivation.PAINTING = new AnnotationMotivation("sc:painting"); AnnotationMotivation.QUESTIONING = new AnnotationMotivation("oa:questioning"); AnnotationMotivation.REPLYING = new AnnotationMotivation("oa:replying"); AnnotationMotivation.TAGGING = new AnnotationMotivation("oa:tagging"); AnnotationMotivation.TRANSCRIBING = new AnnotationMotivation("oad:transcribing"); return AnnotationMotivation; }(Manifesto.StringValue)); Manifesto.AnnotationMotivation = AnnotationMotivation; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Behavior = /** @class */ (function (_super) { __extends(Behavior, _super); function Behavior() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. Behavior.prototype.autoadvance = function () { return new Behavior(Behavior.AUTOADVANCE.toString()); }; Behavior.prototype.nonav = function () { return new Behavior(Behavior.NONAV.toString()); }; Behavior.AUTOADVANCE = new Behavior("auto-advance"); Behavior.NONAV = new Behavior("no-nav"); return Behavior; }(Manifesto.StringValue)); Manifesto.Behavior = Behavior; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var IIIFResourceType = /** @class */ (function (_super) { __extends(IIIFResourceType, _super); function IIIFResourceType() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. IIIFResourceType.prototype.annotation = function () { return new IIIFResourceType(IIIFResourceType.ANNOTATION.toString()); }; IIIFResourceType.prototype.canvas = function () { return new IIIFResourceType(IIIFResourceType.CANVAS.toString()); }; IIIFResourceType.prototype.collection = function () { return new IIIFResourceType(IIIFResourceType.COLLECTION.toString()); }; IIIFResourceType.prototype.manifest = function () { return new IIIFResourceType(IIIFResourceType.MANIFEST.toString()); }; IIIFResourceType.prototype.range = function () { return new IIIFResourceType(IIIFResourceType.RANGE.toString()); }; IIIFResourceType.prototype.sequence = function () { return new IIIFResourceType(IIIFResourceType.SEQUENCE.toString()); }; IIIFResourceType.ANNOTATION = new IIIFResourceType("annotation"); IIIFResourceType.CANVAS = new IIIFResourceType("canvas"); IIIFResourceType.COLLECTION = new IIIFResourceType("collection"); IIIFResourceType.MANIFEST = new IIIFResourceType("manifest"); IIIFResourceType.RANGE = new IIIFResourceType("range"); IIIFResourceType.SEQUENCE = new IIIFResourceType("sequence"); return IIIFResourceType; }(Manifesto.StringValue)); Manifesto.IIIFResourceType = IIIFResourceType; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ManifestType = /** @class */ (function (_super) { __extends(ManifestType, _super); function ManifestType() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. ManifestType.prototype.empty = function () { return new ManifestType(ManifestType.EMPTY.toString()); }; ManifestType.prototype.manuscript = function () { return new ManifestType(ManifestType.MANUSCRIPT.toString()); }; ManifestType.prototype.monograph = function () { return new ManifestType(ManifestType.MONOGRAPH.toString()); }; ManifestType.EMPTY = new ManifestType(""); ManifestType.MANUSCRIPT = new ManifestType("manuscript"); ManifestType.MONOGRAPH = new ManifestType("monograph"); return ManifestType; }(Manifesto.StringValue)); Manifesto.ManifestType = ManifestType; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var RenderingFormat = /** @class */ (function (_super) { __extends(RenderingFormat, _super); function RenderingFormat() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. RenderingFormat.prototype.pdf = function () { return new RenderingFormat(RenderingFormat.PDF.toString()); }; RenderingFormat.prototype.doc = function () { return new RenderingFormat(RenderingFormat.DOC.toString()); }; RenderingFormat.prototype.docx = function () { return new RenderingFormat(RenderingFormat.DOCX.toString()); }; RenderingFormat.PDF = new RenderingFormat("application/pdf"); RenderingFormat.DOC = new RenderingFormat("application/msword"); RenderingFormat.DOCX = new RenderingFormat("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); return RenderingFormat; }(Manifesto.StringValue)); Manifesto.RenderingFormat = RenderingFormat; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var MediaType = /** @class */ (function (_super) { __extends(MediaType, _super); function MediaType() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. MediaType.prototype.jpg = function () { return new MediaType(MediaType.JPG.toString()); }; MediaType.prototype.mp4 = function () { return new MediaType(MediaType.MP4.toString()); }; MediaType.prototype.pdf = function () { return new MediaType(MediaType.PDF.toString()); }; MediaType.prototype.threejs = function () { return new MediaType(MediaType.THREEJS.toString()); }; MediaType.prototype.webm = function () { return new MediaType(MediaType.WEBM.toString()); }; MediaType.JPG = new MediaType("image/jpeg"); MediaType.MP4 = new MediaType("video/mp4"); MediaType.PDF = new MediaType("application/pdf"); MediaType.THREEJS = new MediaType("application/vnd.threejs+json"); MediaType.WEBM = new MediaType("video/webm"); return MediaType; }(Manifesto.StringValue)); Manifesto.MediaType = MediaType; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ResourceType = /** @class */ (function (_super) { __extends(ResourceType, _super); function ResourceType() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. ResourceType.prototype.canvas = function () { return new ResourceType(ResourceType.CANVAS.toString()); }; ResourceType.prototype.choice = function () { return new ResourceType(ResourceType.CHOICE.toString()); }; ResourceType.prototype.document = function () { return new ResourceType(ResourceType.DOCUMENT.toString()); }; ResourceType.prototype.image = function () { return new ResourceType(ResourceType.IMAGE.toString()); }; ResourceType.prototype.movingimage = function () { return new ResourceType(ResourceType.MOVINGIMAGE.toString()); }; ResourceType.prototype.physicalobject = function () { return new ResourceType(ResourceType.PHYSICALOBJECT.toString()); }; ResourceType.prototype.sound = function () { return new ResourceType(ResourceType.SOUND.toString()); }; ResourceType.prototype.text = function () { return new ResourceType(ResourceType.TEXT.toString()); }; ResourceType.CANVAS = new ResourceType("canvas"); ResourceType.CHOICE = new ResourceType("choice"); ResourceType.DOCUMENT = new ResourceType("document"); ResourceType.IMAGE = new ResourceType("image"); ResourceType.MOVINGIMAGE = new ResourceType("movingimage"); ResourceType.PHYSICALOBJECT = new ResourceType("physicalobject"); ResourceType.SOUND = new ResourceType("sound"); ResourceType.TEXT = new ResourceType("textualbody"); return ResourceType; }(Manifesto.StringValue)); Manifesto.ResourceType = ResourceType; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ServiceProfile = /** @class */ (function (_super) { __extends(ServiceProfile, _super); function ServiceProfile() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. ServiceProfile.prototype.auth1Clickthrough = function () { return new ServiceProfile(ServiceProfile.AUTH1CLICKTHROUGH.toString()); }; ServiceProfile.prototype.auth1External = function () { return new ServiceProfile(ServiceProfile.AUTH1EXTERNAL.toString()); }; ServiceProfile.prototype.auth1Kiosk = function () { return new ServiceProfile(ServiceProfile.AUTH1KIOSK.toString()); }; ServiceProfile.prototype.auth1Login = function () { return new ServiceProfile(ServiceProfile.AUTH1LOGIN.toString()); }; ServiceProfile.prototype.auth1Logout = function () { return new ServiceProfile(ServiceProfile.AUTH1LOGOUT.toString()); }; ServiceProfile.prototype.auth1Token = function () { return new ServiceProfile(ServiceProfile.AUTH1TOKEN.toString()); }; ServiceProfile.prototype.autoComplete = function () { return new ServiceProfile(ServiceProfile.AUTOCOMPLETE.toString()); }; ServiceProfile.prototype.iiif1ImageLevel1 = function () { return new ServiceProfile(ServiceProfile.IIIF1IMAGELEVEL1.toString()); }; ServiceProfile.prototype.iiif1ImageLevel2 = function () { return new ServiceProfile(ServiceProfile.IIIF1IMAGELEVEL2.toString()); }; ServiceProfile.prototype.iiif2ImageLevel1 = function () { return new ServiceProfile(ServiceProfile.IIIF2IMAGELEVEL1.toString()); }; ServiceProfile.prototype.iiif2ImageLevel2 = function () { return new ServiceProfile(ServiceProfile.IIIF2IMAGELEVEL2.toString()); }; ServiceProfile.prototype.ixif = function () { return new ServiceProfile(ServiceProfile.IXIF.toString()); }; ServiceProfile.prototype.login = function () { return new ServiceProfile(ServiceProfile.AUTHLOGIN.toString()); }; ServiceProfile.prototype.clickThrough = function () { return new ServiceProfile(ServiceProfile.AUTHCLICKTHROUGH.toString()); }; ServiceProfile.prototype.restricted = function () { return new ServiceProfile(ServiceProfile.AUTHRESTRICTED.toString()); }; ServiceProfile.prototype.logout = function () { return new ServiceProfile(ServiceProfile.AUTHLOGOUT.toString()); }; ServiceProfile.prototype.otherManifestations = function () { return new ServiceProfile(ServiceProfile.OTHERMANIFESTATIONS.toString()); }; ServiceProfile.prototype.search = function () { return new ServiceProfile(ServiceProfile.SEARCH.toString()); }; ServiceProfile.prototype.stanfordIIIFImageCompliance1 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE1.toString()); }; ServiceProfile.prototype.stanfordIIIFImageCompliance2 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE2.toString()); }; ServiceProfile.prototype.stanfordIIIFImageConformance1 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIFIMAGECONFORMANCE1.toString()); }; ServiceProfile.prototype.stanfordIIIFImageConformance2 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIFIMAGECONFORMANCE2.toString()); }; ServiceProfile.prototype.stanfordIIIF1ImageCompliance1 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE1.toString()); }; ServiceProfile.prototype.stanfordIIIF1ImageCompliance2 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE2.toString()); }; ServiceProfile.prototype.stanfordIIIF1ImageConformance1 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE1.toString()); }; ServiceProfile.prototype.stanfordIIIF1ImageConformance2 = function () { return new ServiceProfile(ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE2.toString()); }; ServiceProfile.prototype.token = function () { return new ServiceProfile(ServiceProfile.AUTHTOKEN.toString()); }; ServiceProfile.prototype.trackingExtensions = function () { return new ServiceProfile(ServiceProfile.TRACKINGEXTENSIONS.toString()); }; ServiceProfile.prototype.uiExtensions = function () { return new ServiceProfile(ServiceProfile.UIEXTENSIONS.toString()); }; ServiceProfile.prototype.printExtensions = function () { return new ServiceProfile(ServiceProfile.PRINTEXTENSIONS.toString()); }; ServiceProfile.prototype.shareExtensions = function () { return new ServiceProfile(ServiceProfile.SHAREEXTENSIONS.toString()); }; // image api ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE0 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/compliance.html#level0"); ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE1 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/compliance.html#level1"); ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE2 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/compliance.html#level2"); ServiceProfile.STANFORDIIIFIMAGECONFORMANCE0 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/conformance.html#level0"); ServiceProfile.STANFORDIIIFIMAGECONFORMANCE1 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/conformance.html#level1"); ServiceProfile.STANFORDIIIFIMAGECONFORMANCE2 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/conformance.html#level2"); ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE0 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0"); ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE1 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1"); ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE2 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2"); ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE0 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0"); ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE1 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1"); ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE2 = new ServiceProfile("http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2"); ServiceProfile.IIIF1IMAGELEVEL0 = new ServiceProfile("http://iiif.io/api/image/1/level0.json"); ServiceProfile.IIIF1IMAGELEVEL0PROFILE = new ServiceProfile("http://iiif.io/api/image/1/profiles/level0.json"); ServiceProfile.IIIF1IMAGELEVEL1 = new ServiceProfile("http://iiif.io/api/image/1/level1.json"); ServiceProfile.IIIF1IMAGELEVEL1PROFILE = new ServiceProfile("http://iiif.io/api/image/1/profiles/level1.json"); ServiceProfile.IIIF1IMAGELEVEL2 = new ServiceProfile("http://iiif.io/api/image/1/level2.json"); ServiceProfile.IIIF1IMAGELEVEL2PROFILE = new ServiceProfile("http://iiif.io/api/image/1/profiles/level2.json"); ServiceProfile.IIIF2IMAGELEVEL0 = new ServiceProfile("http://iiif.io/api/image/2/level0.json"); ServiceProfile.IIIF2IMAGELEVEL0PROFILE = new ServiceProfile("http://iiif.io/api/image/2/profiles/level0.json"); ServiceProfile.IIIF2IMAGELEVEL1 = new ServiceProfile("http://iiif.io/api/image/2/level1.json"); ServiceProfile.IIIF2IMAGELEVEL1PROFILE = new ServiceProfile("http://iiif.io/api/image/2/profiles/level1.json"); ServiceProfile.IIIF2IMAGELEVEL2 = new ServiceProfile("http://iiif.io/api/image/2/level2.json"); ServiceProfile.IIIF2IMAGELEVEL2PROFILE = new ServiceProfile("http://iiif.io/api/image/2/profiles/level2.json"); // auth api ServiceProfile.AUTHCLICKTHROUGH = new ServiceProfile("http://iiif.io/api/auth/0/login/clickthrough"); ServiceProfile.AUTHLOGIN = new ServiceProfile("http://iiif.io/api/auth/0/login"); ServiceProfile.AUTHLOGOUT = new ServiceProfile("http://iiif.io/api/auth/0/logout"); ServiceProfile.AUTHRESTRICTED = new ServiceProfile("http://iiif.io/api/auth/0/login/restricted"); ServiceProfile.AUTHTOKEN = new ServiceProfile("http://iiif.io/api/auth/0/token"); ServiceProfile.AUTH1CLICKTHROUGH = new ServiceProfile("http://iiif.io/api/auth/1/clickthrough"); ServiceProfile.AUTH1EXTERNAL = new ServiceProfile("http://iiif.io/api/auth/1/external"); ServiceProfile.AUTH1KIOSK = new ServiceProfile("http://iiif.io/api/auth/1/kiosk"); ServiceProfile.AUTH1LOGIN = new ServiceProfile("http://iiif.io/api/auth/1/login"); ServiceProfile.AUTH1LOGOUT = new ServiceProfile("http://iiif.io/api/auth/1/logout"); ServiceProfile.AUTH1TOKEN = new ServiceProfile("http://iiif.io/api/auth/1/token"); // search api ServiceProfile.AUTOCOMPLETE = new ServiceProfile("http://iiif.io/api/search/0/autocomplete"); ServiceProfile.SEARCH = new ServiceProfile("http://iiif.io/api/search/0/search"); // extensions ServiceProfile.TRACKINGEXTENSIONS = new ServiceProfile("http://universalviewer.io/tracking-extensions-profile"); ServiceProfile.UIEXTENSIONS = new ServiceProfile("http://universalviewer.io/ui-extensions-profile"); ServiceProfile.PRINTEXTENSIONS = new ServiceProfile("http://universalviewer.io/print-extensions-profile"); ServiceProfile.SHAREEXTENSIONS = new ServiceProfile("http://universalviewer.io/share-extensions-profile"); // other ServiceProfile.OTHERMANIFESTATIONS = new ServiceProfile("http://iiif.io/api/otherManifestations.json"); ServiceProfile.IXIF = new ServiceProfile("http://wellcomelibrary.org/ld/ixif/0/alpha.json"); return ServiceProfile; }(Manifesto.StringValue)); Manifesto.ServiceProfile = ServiceProfile; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ViewingDirection = /** @class */ (function (_super) { __extends(ViewingDirection, _super); function ViewingDirection() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. ViewingDirection.prototype.leftToRight = function () { return new ViewingDirection(ViewingDirection.LEFTTORIGHT.toString()); }; ViewingDirection.prototype.rightToLeft = function () { return new ViewingDirection(ViewingDirection.RIGHTTOLEFT.toString()); }; ViewingDirection.prototype.topToBottom = function () { return new ViewingDirection(ViewingDirection.TOPTOBOTTOM.toString()); }; ViewingDirection.prototype.bottomToTop = function () { return new ViewingDirection(ViewingDirection.BOTTOMTOTOP.toString()); }; ViewingDirection.LEFTTORIGHT = new ViewingDirection("left-to-right"); ViewingDirection.RIGHTTOLEFT = new ViewingDirection("right-to-left"); ViewingDirection.TOPTOBOTTOM = new ViewingDirection("top-to-bottom"); ViewingDirection.BOTTOMTOTOP = new ViewingDirection("bottom-to-top"); return ViewingDirection; }(Manifesto.StringValue)); Manifesto.ViewingDirection = ViewingDirection; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ViewingHint = /** @class */ (function (_super) { __extends(ViewingHint, _super); function ViewingHint() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. ViewingHint.prototype.continuous = function () { return new ViewingHint(ViewingHint.CONTINUOUS.toString()); }; ViewingHint.prototype.empty = function () { return new ViewingHint(ViewingHint.EMPTY.toString()); }; ViewingHint.prototype.individuals = function () { return new ViewingHint(ViewingHint.INDIVIDUALS.toString()); }; ViewingHint.prototype.nonPaged = function () { return new ViewingHint(ViewingHint.NONPAGED.toString()); }; ViewingHint.prototype.paged = function () { return new ViewingHint(ViewingHint.PAGED.toString()); }; ViewingHint.prototype.top = function () { return new ViewingHint(ViewingHint.TOP.toString()); }; ViewingHint.CONTINUOUS = new ViewingHint("continuous"); ViewingHint.EMPTY = new ViewingHint(""); ViewingHint.INDIVIDUALS = new ViewingHint("individuals"); ViewingHint.NONPAGED = new ViewingHint("non-paged"); ViewingHint.PAGED = new ViewingHint("paged"); ViewingHint.TOP = new ViewingHint("top"); return ViewingHint; }(Manifesto.StringValue)); Manifesto.ViewingHint = ViewingHint; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var JSONLDResource = /** @class */ (function () { function JSONLDResource(jsonld) { this.__jsonld = jsonld; this.context = this.getProperty('context'); this.id = this.getProperty('id'); } JSONLDResource.prototype.getProperty = function (name) { var prop = null; if (this.__jsonld) { prop = this.__jsonld[name]; if (!prop) { // property may have a prepended '@' prop = this.__jsonld['@' + name]; } } return prop; }; return JSONLDResource; }()); Manifesto.JSONLDResource = JSONLDResource; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var ManifestResource = /** @class */ (function (_super) { __extends(ManifestResource, _super); function ManifestResource(jsonld, options) { var _this = _super.call(this, jsonld) || this; _this.options = options; return _this; } ManifestResource.prototype.getIIIFResourceType = function () { return new Manifesto.IIIFResourceType(Manifesto.Utils.normaliseType(this.getProperty('type'))); }; ManifestResource.prototype.getLabel = function () { return Manifesto.TranslationCollection.parse(this.getProperty('label'), this.options.locale); }; ManifestResource.prototype.getMetadata = function () { var _metadata = this.getProperty('metadata'); var metadata = []; if (!_metadata) return metadata; for (var i = 0; i < _metadata.length; i++) { var item = _metadata[i]; var metadataItem = new Manifesto.MetadataItem(this.options.locale); metadataItem.parse(item); metadata.push(metadataItem); } return metadata; }; ManifestResource.prototype.getRendering = function (format) { var renderings = this.getRenderings(); // normalise format to string if (typeof (format) !== 'string') { format = format.toString(); } for (var i = 0; i < renderings.length; i++) { var rendering = renderings[i]; if (rendering.getFormat().toString() === format) { return rendering; } } return null; }; ManifestResource.prototype.getRenderings = function () { var rendering; // if passing a manifesto-parsed object, use the __jsonld.rendering property, // otherwise look for a rendering property if (this.__jsonld) { rendering = this.__jsonld.rendering; } else { rendering = this.rendering; } var renderings = []; if (!rendering) return renderings; // coerce to array if (!Array.isArray(rendering)) { rendering = [rendering]; } for (var i = 0; i < rendering.length; i++) { var r = rendering[i]; renderings.push(new Manifesto.Rendering(r, this.options)); } return renderings; }; ManifestResource.prototype.getService = function (profile) { return Manifesto.Utils.getService(this, profile); }; ManifestResource.prototype.getServices = function () { return Manifesto.Utils.getServices(this); }; ManifestResource.prototype.getThumbnail = function () { var thumbnail = this.getProperty('thumbnail'); if (Array.isArray(thumbnail)) { thumbnail = thumbnail[0]; } if (thumbnail) { return new Manifesto.Thumbnail(thumbnail, this.options); } return null; }; ManifestResource.prototype.isAnnotation = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.ANNOTATION.toString(); }; ManifestResource.prototype.isCanvas = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.CANVAS.toString(); }; ManifestResource.prototype.isCollection = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.COLLECTION.toString(); }; ManifestResource.prototype.isManifest = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.MANIFEST.toString(); }; ManifestResource.prototype.isRange = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.RANGE.toString(); }; ManifestResource.prototype.isSequence = function () { return this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.SEQUENCE.toString(); }; return ManifestResource; }(Manifesto.JSONLDResource)); Manifesto.ManifestResource = ManifestResource; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Resource = /** @class */ (function (_super) { __extends(Resource, _super); function Resource(jsonld, options) { return _super.call(this, jsonld, options) || this; } Resource.prototype.getFormat = function () { var format = this.getProperty('format'); if (format) { return new Manifesto.MediaType(format.toLowerCase()); } return null; }; Resource.prototype.getResources = function () { var resources = []; if (!this.__jsonld.resources) return resources; for (var i = 0; i < this.__jsonld.resources.length; i++) { var a = this.__jsonld.resources[i]; var annotation = new Manifesto.Annotation(a, this.options); resources.push(annotation); } return resources; }; Resource.prototype.getType = function () { var type = this.getProperty('type'); if (type) { return new Manifesto.ResourceType(Manifesto.Utils.normaliseType(type)); } return null; }; Resource.prototype.getWidth = function () { return this.getProperty('width'); }; Resource.prototype.getHeight = function () { return this.getProperty('height'); }; Resource.prototype.getMaxWidth = function () { return this.getProperty('maxWidth'); }; Resource.prototype.getMaxHeight = function () { var maxHeight = this.getProperty('maxHeight'); // if a maxHeight hasn't been specified, default to maxWidth. // maxWidth in essence becomes maxEdge if (!maxHeight) { return this.getMaxWidth(); } return null; }; return Resource; }(Manifesto.ManifestResource)); Manifesto.Resource = Resource; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Canvas = /** @class */ (function (_super) { __extends(Canvas, _super); function Canvas(jsonld, options) { return _super.call(this, jsonld, options) || this; } // http://iiif.io/api/image/2.1/#canonical-uri-syntax Canvas.prototype.getCanonicalImageUri = function (w) { var id = null; var region = 'full'; var rotation = 0; var quality = 'default'; var width = w; var size; // if an info.json has been loaded if (this.externalResource && this.externalResource.data && this.externalResource.data['@id']) { id = this.externalResource.data['@id']; if (!width) { width = this.externalResource.data.width; } if (this.externalResource.data['@context']) { if (this.externalResource.data['@context'].indexOf('/1.0/context.json') > -1 || this.externalResource.data['@context'].indexOf('/1.1/context.json') > -1 || this.externalResource.data['@context'].indexOf('/1/context.json') > -1) { quality = 'native'; } } } else { // info.json hasn't been loaded yet var images = this.getImages(); if (images && images.length) { var firstImage = images[0]; var resource = firstImage.getResource(); var services = resource.getServices(); if (!width) { width = resource.getWidth(); } if (services.length) { var service = services[0]; id = service.id; quality = Manifesto.Utils.getImageQuality(service.getProfile()); } else if (width === resource.getWidth()) { // if the passed width is the same as the resource width // i.e. not looking for a thumbnail // return the full size image. // used for download options when loading static images. return resource.id; } } // todo: should this be moved to getThumbUri? if (!id) { var thumbnail = this.getProperty('thumbnail'); if (thumbnail) { if (typeof (thumbnail) === 'string') { return thumbnail; } else { if (thumbnail['@id']) { return thumbnail['@id']; } else if (thumbnail.length) { return thumbnail[0].id; } } } } } size = width + ','; // trim off trailing '/' if (id && id.endsWith('/')) { id = id.substr(0, id.length - 1); } var uri = [id, region, size, rotation, quality + '.jpg'].join('/'); return uri; }; Canvas.prototype.getMaxDimensions = function () { var maxDimensions = null; var profile; if (this.externalResource.data && this.externalResource.data.profile) { profile = this.externalResource.data.profile; if (Array.isArray(profile)) { profile = profile.en().where(function (p) { return p["maxWidth" || "maxwidth"]; }).first(); if (profile) { maxDimensions = new Manifesto.Size(profile.maxWidth, profile.maxHeight ? profile.maxHeight : profile.maxWidth); } } } return maxDimensions; }; // Presentation API 3.0 Canvas.prototype.getContent = function () { var content = []; var items = this.__jsonld.items || this.__jsonld.content; if (!items) return content; // should be contained in an AnnotationPage var annotationPage = null; if (items.length) { annotationPage = new Manifesto.AnnotationPage(items[0], this.options); } if (!annotationPage) { return content; } var annotations = annotationPage.getItems(); for (var i = 0; i < annotations.length; i++) { var a = annotations[i]; var annotation = new Manifesto.Annotation(a, this.options); content.push(annotation); } return content; }; Canvas.prototype.getDuration = function () { return this.getProperty('duration'); }; Canvas.prototype.getImages = function () { var images = []; if (!this.__jsonld.images) return images; for (var i = 0; i < this.__jsonld.images.length; i++) { var a = this.__jsonld.images[i]; var annotation = new Manifesto.Annotation(a, this.options); images.push(annotation); } return images; }; Canvas.prototype.getIndex = function () { return this.getProperty('index'); }; Canvas.prototype.getOtherContent = function () { var _this = this; var otherContent = Array.isArray(this.getProperty('otherContent')) ? this.getProperty('otherContent') : [this.getProperty('otherContent')]; var canonicalComparison = function (typeA, typeB) { if (typeof typeA !== 'string' || typeof typeB !== 'string') { return false; } return typeA.toLowerCase() === typeA.toLowerCase(); }; var otherPromises = otherContent .filter(function (otherContent) { return otherContent && canonicalComparison(otherContent['@type'], 'sc:AnnotationList'); }) .map(function (annotationList, i) { return ((new Manifesto.AnnotationList(annotationList['label'] || "Annotation list " + i, annotationList, _this.options))); }) .map(function (annotationList) { return annotationList.load(); }); return Promise.all(otherPromises); }; // Prefer thumbnail service to image service if supplied and if // the thumbnail service can provide a satisfactory size +/- x pixels. // this is used to get thumb URIs *before* the info.json has been requested // and populate thumbnails in a viewer. // the publisher may also provide pre-computed fixed-size thumbs for better performance. //getThumbUri(width: number): string { // // var uri; // var images: IAnnotation[] = this.getImages(); // // if (images && images.length) { // var firstImage = images[0]; // var resource: IResource = firstImage.getResource(); // var services: IService[] = resource.getServices(); // // for (let i = 0; i < services.length; i++) { // var service: IService = services[i]; // var id = service.id; // // if (!_endsWith(id, '/')) { // id += '/'; // } // // uri = id + 'full/' + width + ',/0/' + Utils.getImageQuality(service.getProfile()) + '.jpg'; // } // } // // return uri; //} //getType(): CanvasType { // return new CanvasType(this.getProperty('@type').toLowerCase()); //} Canvas.prototype.getWidth = function () { return this.getProperty('width'); }; Canvas.prototype.getHeight = function () { return this.getProperty('height'); }; return Canvas; }(Manifesto.Resource)); Manifesto.Canvas = Canvas; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var IIIFResource = /** @class */ (function (_super) { __extends(IIIFResource, _super); function IIIFResource(jsonld, options) { var _this = _super.call(this, jsonld, options) || this; _this.index = -1; _this.isLoaded = false; var defaultOptions = { defaultLabel: '-', locale: 'en-GB', resource: _this, pessimisticAccessControl: false }; _this.options = Object.assign(defaultOptions, options); return _this; } IIIFResource.prototype.getAttribution = function () { var attribution = this.getProperty('attribution'); if (attribution) { return Manifesto.TranslationCollection.parse(attribution, this.options.locale); } return []; }; IIIFResource.prototype.getDescription = function () { var description = this.getProperty('description'); if (description) { return Manifesto.TranslationCollection.parse(description, this.options.locale); } return []; }; IIIFResource.prototype.getIIIFResourceType = function () { return new Manifesto.IIIFResourceType(Manifesto.Utils.normaliseType(this.getProperty('type'))); }; IIIFResource.prototype.getLogo = function () { var logo = this.getProperty('logo'); if (!logo) return null; if (typeof (logo) === 'string') return logo; return logo['@id']; }; IIIFResource.prototype.getLicense = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('license'), this.options.locale); }; IIIFResource.prototype.getNavDate = function () { return new Date(this.getProperty('navDate')); }; IIIFResource.prototype.getRelated = function () { return this.getProperty('related'); }; IIIFResource.prototype.getSeeAlso = function () { return this.getProperty('seeAlso'); }; IIIFResource.prototype.getLabel = function () { var label = this.getProperty('label'); if (label) { return Manifesto.TranslationCollection.parse(label, this.options.locale); } return []; }; IIIFResource.prototype.getDefaultLabel = function () { return Manifesto.TranslationCollection.getValue(this.getLabel()); }; IIIFResource.prototype.getDefaultTree = function () { this.defaultTree = new Manifesto.TreeNode('root'); this.defaultTree.data = this; return this.defaultTree; }; IIIFResource.prototype.isCollection = function () { if (this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.COLLECTION.toString()) { return true; } return false; }; IIIFResource.prototype.isManifest = function () { if (this.getIIIFResourceType().toString() === Manifesto.IIIFResourceType.MANIFEST.toString()) { return true; } return false; }; IIIFResource.prototype.load = function () { var that = this; return new Promise(function (resolve, reject) { if (that.isLoaded) { resolve(that); } else { var options_1 = that.options; options_1.navDate = that.getNavDate(); var id = that.__jsonld.id; if (!id) { id = that.__jsonld['@id']; } Manifesto.Utils.loadResource(id).then(function (data) { that.parentLabel = Manifesto.TranslationCollection.getValue(that.getLabel(), options_1.locale); var parsed = Manifesto.Deserialiser.parse(data, options_1); that = Object.assign(that, parsed); that.index = options_1.index; resolve(that); }); } }); }; return IIIFResource; }(Manifesto.ManifestResource)); Manifesto.IIIFResource = IIIFResource; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Manifest = /** @class */ (function (_super) { __extends(Manifest, _super); function Manifest(jsonld, options) { var _this = _super.call(this, jsonld, options) || this; _this.index = 0; _this._allRanges = null; _this.items = []; _this._topRanges = []; if (_this.__jsonld.structures && _this.__jsonld.structures.length) { var topRanges = _this._getTopRanges(); for (var i = 0; i < topRanges.length; i++) { var range = topRanges[i]; _this._parseRanges(range, String(i)); } } return _this; } Manifest.prototype.getBehavior = function () { if (this.getProperty('behavior')) { return new Manifesto.Behavior(this.getProperty('behavior')); } return null; }; Manifest.prototype.getDefaultTree = function () { _super.prototype.getDefaultTree.call(this); this.defaultTree.data.type = Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.MANIFEST.toString()); if (!this.isLoaded) { return this.defaultTree; } var topRanges = this.getTopRanges(); // if there are any ranges in the manifest, default to the first 'top' range or generated placeholder if (topRanges.length) { topRanges[0].getTree(this.defaultTree); } Manifesto.Utils.generateTreeNodeIds(this.defaultTree); return this.defaultTree; }; Manifest.prototype._getTopRanges = function () { var topRanges = []; if (this.__jsonld.structures && this.__jsonld.structures.length) { for (var i = 0; i < this.__jsonld.structures.length; i++) { var json = this.__jsonld.structures[i]; if (json.viewingHint === Manifesto.ViewingHint.TOP.toString()) { topRanges.push(json); } } // if no viewingHint="top" range was found, create a default one if (!topRanges.length) { var range = {}; range.ranges = this.__jsonld.structures; topRanges.push(range); } } return topRanges; }; Manifest.prototype.getTopRanges = function () { return this._topRanges; }; Manifest.prototype._getRangeById = function (id) { if (this.__jsonld.structures && this.__jsonld.structures.length) { for (var i = 0; i < this.__jsonld.structures.length; i++) { var r = this.__jsonld.structures[i]; if (r['@id'] === id || r.id === id) { return r; } } } return null; }; //private _parseRangeCanvas(json: any, range: IRange): void { // todo: currently this isn't needed //var canvas: IJSONLDResource = new JSONLDResource(json); //range.items.push(<IManifestResource>canvas); //} Manifest.prototype._parseRanges = function (r, path, parentRange) { var range; var id = null; if (typeof (r) === 'string') { id = r; r = this._getRangeById(id); } if (!r) { console.warn("Range:", id, "does not exist"); return; } range = new Manifesto.Range(r, this.options); range.parentRange = parentRange; range.path = path; if (!parentRange) { this._topRanges.push(range); } else { parentRange.items.push(range); } var items = r.items || r.members; if (items) { for (var i = 0; i < items.length; i++) { var item = items[i]; // todo: use an ItemType constant? if (item['@type'] && item['@type'].toLowerCase() === 'sc:range' || item['type'] && item['type'].toLowerCase() === 'range') { this._parseRanges(item, path + '/' + i, range); } else if (item['@type'] && item['@type'].toLowerCase() === 'sc:canvas' || item['type'] && item['type'].toLowerCase() === 'canvas') { // store the ids on the __jsonld object to be used by Range.getCanvasIds() if (!range.canvases) { range.canvases = []; } var id_1 = item.id || item['@id']; range.canvases.push(id_1); } } } else if (r.ranges) { for (var i = 0; i < r.ranges.length; i++) { this._parseRanges(r.ranges[i], path + '/' + i, range); } } }; Manifest.prototype.getAllRanges = function () { if (this._allRanges != null) return this._allRanges; this._allRanges = []; var topRanges = this.getTopRanges(); for (var i = 0; i < topRanges.length; i++) { var topRange = topRanges[i]; if (topRange.id) { this._allRanges.push(topRange); // it might be a placeholder root range } var subRanges = topRange.getRanges(); this._allRanges = this._allRanges.concat(subRanges.en().traverseUnique(function (range) { return range.getRanges(); }).toArray()); } return this._allRanges; }; Manifest.prototype.getRangeById = function (id) { var ranges = this.getAllRanges(); for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (range.id === id) { return range; } } return null; }; Manifest.prototype.getRangeByPath = function (path) { var ranges = this.getAllRanges(); for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (range.path === path) { return range; } } return null; }; Manifest.prototype.getSequences = function () { if (this.items.length) { return this.items; } // IxIF mediaSequences overrode sequences, so need to be checked first. // deprecate this when presentation 3 ships var items = this.__jsonld.mediaSequences || this.__jsonld.sequences; if (items) { for (var i = 0; i < items.length; i++) { var s = items[i]; var sequence = new Manifesto.Sequence(s, this.options); this.items.push(sequence); } } else if (this.__jsonld.items) { var sequence = new Manifesto.Sequence(this.__jsonld.items, this.options); this.items.push(sequence); } return this.items; }; Manifest.prototype.getSequenceByIndex = function (sequenceIndex) { return this.getSequences()[sequenceIndex]; }; Manifest.prototype.getTotalSequences = function () { return this.getSequences().length; }; Manifest.prototype.getManifestType = function () { var service = this.getService(Manifesto.ServiceProfile.UIEXTENSIONS); if (service) { return new Manifesto.ManifestType(service.getProperty('manifestType')); } return new Manifesto.ManifestType(''); }; Manifest.prototype.getTrackingLabel = function () { var service = this.getService(Manifesto.ServiceProfile.TRACKINGEXTENSIONS); if (service) { return service.getProperty('trackingLabel'); } return ''; }; Manifest.prototype.isMultiSequence = function () { return this.getTotalSequences() > 1; }; Manifest.prototype.isPagingEnabled = function () { return this.getViewingHint().toString() === Manifesto.ViewingHint.PAGED.toString(); }; Manifest.prototype.getViewingDirection = function () { if (this.getProperty('viewingDirection')) { return new Manifesto.ViewingDirection(this.getProperty('viewingDirection')); } return Manifesto.ViewingDirection.LEFTTORIGHT; }; Manifest.prototype.getViewingHint = function () { if (this.getProperty('viewingHint')) { return new Manifesto.ViewingHint(this.getProperty('viewingHint')); } return Manifesto.ViewingHint.EMPTY; }; return Manifest; }(Manifesto.IIIFResource)); Manifesto.Manifest = Manifest; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Collection = /** @class */ (function (_super) { __extends(Collection, _super); function Collection(jsonld, options) { var _this = _super.call(this, jsonld, options) || this; _this.items = []; _this._collections = null; _this._manifests = null; jsonld.__collection = _this; return _this; } Collection.prototype.getCollections = function () { if (this._collections) { return this._collections; } return this._collections = this.items.en().where(function (m) { return m.isCollection(); }).toArray(); }; Collection.prototype.getManifests = function () { if (this._manifests) { return this._manifests; } return this._manifests = this.items.en().where(function (m) { return m.isManifest(); }).toArray(); }; Collection.prototype.getCollectionByIndex = function (collectionIndex) { var collections = this.getCollections(); if (!collections[collectionIndex]) { throw new Error("Collection index is outside range of array"); } var collection = collections[collectionIndex]; collection.options.index = collectionIndex; // id for collection MUST be dereferenceable return collection.load(); }; Collection.prototype.getManifestByIndex = function (manifestIndex) { var manifests = this.getManifests(); if (!manifests[manifestIndex]) { throw new Error("Manifest index is outside range of array"); } var manifest = manifests[manifestIndex]; manifest.options.index = manifestIndex; return manifest.load(); }; Collection.prototype.getTotalCollections = function () { return this.getCollections().length; }; Collection.prototype.getTotalManifests = function () { return this.getManifests().length; }; Collection.prototype.getTotalItems = function () { return this.items.length; }; Collection.prototype.getViewingDirection = function () { if (this.getProperty('viewingDirection')) { return new Manifesto.ViewingDirection(this.getProperty('viewingDirection')); } return Manifesto.ViewingDirection.LEFTTORIGHT; }; /** * Get a tree of sub collections and manifests, using each child manifest's first 'top' range. */ Collection.prototype.getDefaultTree = function () { _super.prototype.getDefaultTree.call(this); this.defaultTree.data.type = Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.COLLECTION.toString()); this._parseManifests(this); this._parseCollections(this); Manifesto.Utils.generateTreeNodeIds(this.defaultTree); return this.defaultTree; }; Collection.prototype._parseManifests = function (parentCollection) { if (parentCollection.getManifests() && parentCollection.getManifests().length) { for (var i = 0; i < parentCollection.getManifests().length; i++) { var manifest = parentCollection.getManifests()[i]; var tree = manifest.getDefaultTree(); tree.label = manifest.parentLabel || Manifesto.TranslationCollection.getValue(manifest.getLabel(), this.options.locale) || 'manifest ' + (i + 1); tree.navDate = manifest.getNavDate(); tree.data.id = manifest.id; tree.data.type = Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.MANIFEST.toString()); parentCollection.defaultTree.addNode(tree); } } }; Collection.prototype._parseCollections = function (parentCollection) { if (parentCollection.getCollections() && parentCollection.getCollections().length) { for (var i = 0; i < parentCollection.getCollections().length; i++) { var collection = parentCollection.getCollections()[i]; var tree = collection.getDefaultTree(); tree.label = collection.parentLabel || Manifesto.TranslationCollection.getValue(collection.getLabel(), this.options.locale) || 'collection ' + (i + 1); tree.navDate = collection.getNavDate(); tree.data.id = collection.id; tree.data.type = Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.COLLECTION.toString()); parentCollection.defaultTree.addNode(tree); this._parseCollections(collection); } } }; return Collection; }(Manifesto.IIIFResource)); Manifesto.Collection = Collection; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Range = /** @class */ (function (_super) { __extends(Range, _super); function Range(jsonld, options) { var _this = _super.call(this, jsonld, options) || this; _this._ranges = null; _this.canvases = null; _this.items = []; return _this; } Range.prototype.getCanvasIds = function () { if (this.__jsonld.canvases) { return this.__jsonld.canvases; } else if (this.canvases) { return this.canvases; } return []; }; // getCanvases(): ICanvas[] { // if (this._canvases) { // return this._canvases; // } // return this._canvases = <ICanvas[]>this.items.en().where(m => m.isCanvas()).toArray(); // } Range.prototype.getRanges = function () { if (this._ranges) { return this._ranges; } return this._ranges = this.items.en().where(function (m) { return m.isRange(); }).toArray(); }; Range.prototype.getBehavior = function () { if (this.getProperty('behavior')) { return new Manifesto.Behavior(this.getProperty('behavior')); } return null; }; Range.prototype.getViewingDirection = function () { if (this.getProperty('viewingDirection')) { return new Manifesto.ViewingDirection(this.getProperty('viewingDirection')); } return null; }; Range.prototype.getViewingHint = function () { if (this.getProperty('viewingHint')) { return new Manifesto.ViewingHint(this.getProperty('viewingHint')); } return null; }; Range.prototype.getTree = function (treeRoot) { treeRoot.data = this; this.treeNode = treeRoot; var ranges = this.getRanges(); if (ranges && ranges.length) { for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var node = new Manifesto.TreeNode(); treeRoot.addNode(node); this._parseTreeNode(node, range); } } Manifesto.Utils.generateTreeNodeIds(treeRoot); return treeRoot; }; Range.prototype._parseTreeNode = function (node, range) { node.label = Manifesto.TranslationCollection.getValue(range.getLabel(), this.options.locale); node.data = range; node.data.type = Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.RANGE.toString()); range.treeNode = node; var ranges = range.getRanges(); if (ranges && ranges.length) { for (var i = 0; i < ranges.length; i++) { var childRange = ranges[i]; var behavior = childRange.getBehavior(); if (behavior && behavior.toString() === Manifesto.Behavior.NONAV.toString()) { continue; } else { var childNode = new Manifesto.TreeNode(); node.addNode(childNode); this._parseTreeNode(childNode, childRange); } } } }; return Range; }(Manifesto.ManifestResource)); Manifesto.Range = Range; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Rendering = /** @class */ (function (_super) { __extends(Rendering, _super); function Rendering(jsonld, options) { return _super.call(this, jsonld, options) || this; } Rendering.prototype.getFormat = function () { return new Manifesto.RenderingFormat(this.getProperty('format')); }; return Rendering; }(Manifesto.ManifestResource)); Manifesto.Rendering = Rendering; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Sequence = /** @class */ (function (_super) { __extends(Sequence, _super); function Sequence(jsonld, options) { var _this = _super.call(this, jsonld, options) || this; _this.items = []; _this._thumbnails = null; return _this; } Sequence.prototype.getCanvases = function () { if (this.items.length) { return this.items; } var items = this.__jsonld.canvases || this.__jsonld.elements; if (items) { for (var i = 0; i < items.length; i++) { var c = items[i]; var canvas = new Manifesto.Canvas(c, this.options); canvas.index = i; this.items.push(canvas); } } else if (this.__jsonld) { for (var i = 0; i < this.__jsonld.length; i++) { var c = this.__jsonld[i]; var canvas = new Manifesto.Canvas(c, this.options); canvas.index = i; this.items.push(canvas); } } return this.items; }; Sequence.prototype.getCanvasById = function (id) { for (var i = 0; i < this.getTotalCanvases(); i++) { var canvas = this.getCanvasByIndex(i); // normalise canvas id var canvasId = Manifesto.Utils.normaliseUrl(canvas.id); if (Manifesto.Utils.normaliseUrl(id) === canvasId) { return canvas; } } return null; }; Sequence.prototype.getCanvasByIndex = function (canvasIndex) { return this.getCanvases()[canvasIndex]; }; Sequence.prototype.getCanvasIndexById = function (id) { for (var i = 0; i < this.getTotalCanvases(); i++) { var canvas = this.getCanvasByIndex(i); if (canvas.id === id) { return i; } } return null; }; Sequence.prototype.getCanvasIndexByLabel = function (label, foliated) { label = label.trim(); if (!isNaN(label)) { label = parseInt(label, 10).toString(); // trim any preceding zeros. if (foliated) label += 'r'; // default to recto } var doublePageRegExp = /(\d*)\D+(\d*)/; var match, regExp, regStr, labelPart1, labelPart2; for (var i = 0; i < this.getTotalCanvases(); i++) { var canvas = this.getCanvasByIndex(i); // check if there's a literal match if (Manifesto.TranslationCollection.getValue(canvas.getLabel(), this.options.locale) === label) { return i; } // check if there's a match for double-page spreads e.g. 100-101, 100_101, 100 101 match = doublePageRegExp.exec(label); if (!match) continue; labelPart1 = match[1]; labelPart2 = match[2]; if (!labelPart2) continue; regStr = "^" + labelPart1 + "\\D+" + labelPart2 + "$"; regExp = new RegExp(regStr); if (regExp.test(canvas.getLabel().toString())) { return i; } } return -1; }; Sequence.prototype.getLastCanvasLabel = function (alphanumeric) { for (var i = this.getTotalCanvases() - 1; i >= 0; i--) { var canvas = this.getCanvasByIndex(i); var label = Manifesto.TranslationCollection.getValue(canvas.getLabel(), this.options.locale); if (alphanumeric) { var regExp = /^[a-zA-Z0-9]*$/; if (regExp.test(label)) { return label; } } else if (label) { return label; } } return this.options.defaultLabel; }; Sequence.prototype.getLastPageIndex = function () { return this.getTotalCanvases() - 1; }; Sequence.prototype.getNextPageIndex = function (canvasIndex, pagingEnabled) { var index; if (pagingEnabled) { var indices = this.getPagedIndices(canvasIndex); if (this.getViewingDirection().toString() === Manifesto.ViewingDirection.RIGHTTOLEFT.toString()) { index = indices[0] + 1; } else { index = indices[indices.length - 1] + 1; } } else { index = canvasIndex + 1; } if (index > this.getLastPageIndex()) { return -1; } return index; }; Sequence.prototype.getPagedIndices = function (canvasIndex, pagingEnabled) { var indices = []; if (!pagingEnabled) { indices.push(canvasIndex); } else { if (this.isFirstCanvas(canvasIndex) || this.isLastCanvas(canvasIndex)) { indices = [canvasIndex]; } else if (canvasIndex % 2) { indices = [canvasIndex, canvasIndex + 1]; } else { indices = [canvasIndex - 1, canvasIndex]; } if (this.getViewingDirection().toString() === Manifesto.ViewingDirection.RIGHTTOLEFT.toString()) { indices = indices.reverse(); } } return indices; }; Sequence.prototype.getPrevPageIndex = function (canvasIndex, pagingEnabled) { var index; if (pagingEnabled) { var indices = this.getPagedIndices(canvasIndex); if (this.getViewingDirection().toString() === Manifesto.ViewingDirection.RIGHTTOLEFT.toString()) { index = indices[indices.length - 1] - 1; } else { index = indices[0] - 1; } } else { index = canvasIndex - 1; } return index; }; Sequence.prototype.getStartCanvasIndex = function () { var startCanvas = this.getStartCanvas(); if (startCanvas) { // if there's a startCanvas attribute, loop through the canvases and return the matching index. for (var i = 0; i < this.getTotalCanvases(); i++) { var canvas = this.getCanvasByIndex(i); if (canvas.id === startCanvas) return i; } } // default to first canvas. return 0; }; // todo: deprecate Sequence.prototype.getThumbs = function (width, height) { console.warn('getThumbs will be deprecated, use getThumbnails instead'); var thumbs = []; var totalCanvases = this.getTotalCanvases(); for (var i = 0; i < totalCanvases; i++) { var canvas = this.getCanvasByIndex(i); var thumb = new Manifesto.Thumb(width, canvas); thumbs.push(thumb); } return thumbs; }; Sequence.prototype.getThumbnails = function () { if (this._thumbnails != null) return this._thumbnails; this._thumbnails = []; var canvases = this.getCanvases(); for (var i = 0; i < canvases.length; i++) { var thumbnail = canvases[i].getThumbnail(); if (thumbnail) { this._thumbnails.push(thumbnail); } } return this._thumbnails; }; Sequence.prototype.getStartCanvas = function () { return this.getProperty('startCanvas'); }; Sequence.prototype.getTotalCanvases = function () { return this.getCanvases().length; }; Sequence.prototype.getViewingDirection = function () { if (this.getProperty('viewingDirection')) { return new Manifesto.ViewingDirection(this.getProperty('viewingDirection')); } else if (this.options.resource.getViewingDirection) { return this.options.resource.getViewingDirection(); } return Manifesto.ViewingDirection.LEFTTORIGHT; }; Sequence.prototype.getViewingHint = function () { if (this.getProperty('viewingHint')) { return new Manifesto.ViewingHint(this.getProperty('viewingHint')); } return Manifesto.ViewingHint.EMPTY; }; Sequence.prototype.isCanvasIndexOutOfRange = function (canvasIndex) { return canvasIndex > this.getTotalCanvases() - 1; }; Sequence.prototype.isFirstCanvas = function (canvasIndex) { return canvasIndex === 0; }; Sequence.prototype.isLastCanvas = function (canvasIndex) { return canvasIndex === this.getTotalCanvases() - 1; }; Sequence.prototype.isMultiCanvas = function () { return this.getTotalCanvases() > 1; }; Sequence.prototype.isPagingEnabled = function () { return this.getViewingHint().toString() === Manifesto.ViewingHint.PAGED.toString(); }; // checks if the number of canvases is even - therefore has a front and back cover Sequence.prototype.isTotalCanvasesEven = function () { return this.getTotalCanvases() % 2 === 0; }; return Sequence; }(Manifesto.ManifestResource)); Manifesto.Sequence = Sequence; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var Deserialiser = /** @class */ (function () { function Deserialiser() { } Deserialiser.parse = function (manifest, options) { if (typeof manifest === 'string') { manifest = JSON.parse(manifest); } return this.parseJson(manifest, options); }; Deserialiser.parseJson = function (json, options) { var resource; // have options been passed for the manifest to inherit? if (options) { if (options.navDate && !isNaN(options.navDate.getTime())) { json.navDate = options.navDate.toString(); } } if (json['@type']) { switch (json['@type']) { case 'sc:Collection': resource = this.parseCollection(json, options); break; case 'sc:Manifest': resource = this.parseManifest(json, options); break; default: return null; } } else { // presentation 3 switch (json['type']) { case 'Collection': resource = this.parseCollection(json, options); break; case 'Manifest': resource = this.parseManifest(json, options); break; default: return null; } } // Top-level resource was loaded from a URI, so flag it to prevent // unnecessary reload: resource.isLoaded = true; return resource; }; Deserialiser.parseCollection = function (json, options) { var collection = new Manifesto.Collection(json, options); if (options) { collection.index = options.index || 0; } else { collection.index = 0; } this.parseCollections(collection, options); this.parseManifests(collection, options); this.parseItems(collection, options); return collection; }; Deserialiser.parseCollections = function (collection, options) { var items; if (collection.__jsonld.collections) { items = collection.__jsonld.collections; } else if (collection.__jsonld.items) { items = collection.__jsonld.items.en().where(function (m) { return m.type.toLowerCase() === 'collection'; }).toArray(); } if (items) { for (var i = 0; i < items.length; i++) { if (options) { options.index = i; } var item = this.parseCollection(items[i], options); item.index = i; item.parentCollection = collection; collection.items.push(item); } } }; Deserialiser.parseManifest = function (json, options) { var manifest = new Manifesto.Manifest(json, options); return manifest; }; Deserialiser.parseManifests = function (collection, options) { var items; if (collection.__jsonld.manifests) { items = collection.__jsonld.manifests; } else if (collection.__jsonld.items) { items = collection.__jsonld.items.en().where(function (m) { return m.type.toLowerCase() === 'manifest'; }).toArray(); } if (items) { for (var i = 0; i < items.length; i++) { var item = this.parseManifest(items[i], options); item.index = i; item.parentCollection = collection; collection.items.push(item); } } }; Deserialiser.parseItem = function (json, options) { if (json['@type']) { if (json['@type'].toLowerCase() === 'sc:manifest') { return this.parseManifest(json, options); } else if (json['@type'].toLowerCase() === 'sc:collection') { return this.parseCollection(json, options); } } else if (json.type) { if (json.type.toLowerCase() === 'manifest') { return this.parseManifest(json, options); } else if (json.type.toLowerCase() === 'collection') { return this.parseCollection(json, options); } } return null; }; Deserialiser.parseItems = function (collection, options) { var items = collection.__jsonld.members || collection.__jsonld.items; if (items) { var _loop_1 = function (i) { if (options) { options.index = i; } var item = this_1.parseItem(items[i], options); if (!item) return { value: void 0 }; // only add to items if not already parsed from backwards-compatible collections/manifests arrays if (collection.items.en().where(function (m) { return m.id === item.id; }).first()) { return "continue"; } item.index = i; item.parentCollection = collection; collection.items.push(item); }; var this_1 = this; for (var i = 0; i < items.length; i++) { var state_1 = _loop_1(i); if (typeof state_1 === "object") return state_1.value; } } }; return Deserialiser; }()); Manifesto.Deserialiser = Deserialiser; var Serialiser = /** @class */ (function () { function Serialiser() { } Serialiser.serialise = function (manifest) { // todo return ""; }; return Serialiser; }()); Manifesto.Serialiser = Serialiser; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Service = /** @class */ (function (_super) { __extends(Service, _super); function Service(jsonld, options) { return _super.call(this, jsonld, options) || this; } Service.prototype.getProfile = function () { var profile = this.getProperty('profile'); if (!profile) { profile = this.getProperty('dcterms:conformsTo'); } if (Array.isArray(profile)) { return new Manifesto.ServiceProfile(profile[0]); } return new Manifesto.ServiceProfile(profile); }; Service.prototype.getConfirmLabel = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('confirmLabel'), this.options.locale); }; Service.prototype.getDescription = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('description'), this.options.locale); }; Service.prototype.getFailureDescription = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('failureDescription'), this.options.locale); }; Service.prototype.getFailureHeader = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('failureHeader'), this.options.locale); }; Service.prototype.getHeader = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('header'), this.options.locale); }; Service.prototype.getServiceLabel = function () { return Manifesto.Utils.getLocalisedValue(this.getProperty('label'), this.options.locale); }; Service.prototype.getInfoUri = function () { var infoUri = this.id; if (!infoUri.endsWith('/')) { infoUri += '/'; } infoUri += 'info.json'; return infoUri; }; return Service; }(Manifesto.ManifestResource)); Manifesto.Service = Service; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { // todo: deprecate // this is used by Sequence.getThumbs var Thumb = /** @class */ (function () { function Thumb(width, canvas) { this.data = canvas; this.index = canvas.index; this.width = width; var heightRatio = canvas.getHeight() / canvas.getWidth(); if (heightRatio) { this.height = Math.floor(this.width * heightRatio); } else { this.height = width; } this.uri = canvas.getCanonicalImageUri(width); this.label = Manifesto.TranslationCollection.getValue(canvas.getLabel()); // todo: pass locale? } return Thumb; }()); Manifesto.Thumb = Thumb; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var TreeNode = /** @class */ (function () { function TreeNode(label, data) { this.label = label; this.data = data || {}; this.nodes = []; } TreeNode.prototype.addNode = function (node) { this.nodes.push(node); node.parentNode = this; }; TreeNode.prototype.isCollection = function () { return this.data.type === Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.COLLECTION.toString()); }; TreeNode.prototype.isManifest = function () { return this.data.type === Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.MANIFEST.toString()); }; TreeNode.prototype.isRange = function () { return this.data.type === Manifesto.Utils.normaliseType(Manifesto.TreeNodeType.RANGE.toString()); }; return TreeNode; }()); Manifesto.TreeNode = TreeNode; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var TreeNodeType = /** @class */ (function (_super) { __extends(TreeNodeType, _super); function TreeNodeType() { return _super !== null && _super.apply(this, arguments) || this; } // todo: use getters when ES3 target is no longer required. TreeNodeType.prototype.collection = function () { return new TreeNodeType(TreeNodeType.COLLECTION.toString()); }; TreeNodeType.prototype.manifest = function () { return new TreeNodeType(TreeNodeType.MANIFEST.toString()); }; TreeNodeType.prototype.range = function () { return new TreeNodeType(TreeNodeType.RANGE.toString()); }; TreeNodeType.COLLECTION = new TreeNodeType("collection"); TreeNodeType.MANIFEST = new TreeNodeType("manifest"); TreeNodeType.RANGE = new TreeNodeType("range"); return TreeNodeType; }(Manifesto.StringValue)); Manifesto.TreeNodeType = TreeNodeType; })(Manifesto || (Manifesto = {})); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(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 = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, 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 http = require('http'); var https = require('https'); var url = require('url'); var Manifesto; (function (Manifesto) { var Utils = /** @class */ (function () { function Utils() { } Utils.getMediaType = function (type) { type = type.toLowerCase(); type = type.split(';')[0]; return type.trim(); }; Utils.getImageQuality = function (profile) { var p = profile.toString(); if (p === Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE1.toString() || p === Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE2.toString() || p === Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE1.toString() || p === Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE2.toString() || p === Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE1.toString() || p === Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE2.toString() || p === Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE1.toString() || p === Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE2.toString() || p === Manifesto.ServiceProfile.IIIF1IMAGELEVEL1.toString() || p === Manifesto.ServiceProfile.IIIF1IMAGELEVEL1PROFILE.toString() || p === Manifesto.ServiceProfile.IIIF1IMAGELEVEL2.toString() || p === Manifesto.ServiceProfile.IIIF1IMAGELEVEL2PROFILE.toString()) { return 'native'; } return 'default'; }; Utils.getInexactLocale = function (locale) { if (locale.indexOf('-') !== -1) { return locale.substr(0, locale.indexOf('-')); } return locale; }; Utils.getLocalisedValue = function (resource, locale) { // if the resource is not an array of translations, return the string. if (!Array.isArray(resource)) { return resource; } // test for exact match for (var i = 0; i < resource.length; i++) { var value_1 = resource[i]; var language_1 = value_1['@language']; if (locale === language_1) { return value_1['@value']; } } // test for inexact match var match = locale.substr(0, locale.indexOf('-')); for (var i = 0; i < resource.length; i++) { var value = resource[i]; var language = value['@language']; if (language === match) { return value['@value']; } } return null; }; Utils.generateTreeNodeIds = function (treeNode, index) { if (index === void 0) { index = 0; } var id; if (!treeNode.parentNode) { id = '0'; } else { id = treeNode.parentNode.id + "-" + index; } treeNode.id = id; for (var i = 0; i < treeNode.nodes.length; i++) { var n = treeNode.nodes[i]; Utils.generateTreeNodeIds(n, i); } }; Utils.normaliseType = function (type) { type = type.toLowerCase(); if (type.indexOf(':') !== -1) { var split = type.split(':'); return split[1]; } return type; }; Utils.normaliseUrl = function (url) { url = url.substr(url.indexOf('://')); if (url.indexOf('#') !== -1) { url = url.split('#')[0]; } return url; }; Utils.normalisedUrlsMatch = function (url1, url2) { return Utils.normaliseUrl(url1) === Utils.normaliseUrl(url2); }; Utils.isImageProfile = function (profile) { if (Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL0PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL1PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL2PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL0PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL1PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL2PROFILE.toString())) { return true; } return false; }; Utils.isLevel0ImageProfile = function (profile) { if (Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL0PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL0.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL0PROFILE.toString())) { return true; } return false; }; Utils.isLevel1ImageProfile = function (profile) { if (Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL1PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL1.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL1PROFILE.toString())) { return true; } return false; }; Utils.isLevel2ImageProfile = function (profile) { if (Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECOMPLIANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECOMPLIANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIFIMAGECONFORMANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.STANFORDIIIF1IMAGECONFORMANCE2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF1IMAGELEVEL2PROFILE.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL2.toString()) || Utils.normalisedUrlsMatch(profile.toString(), Manifesto.ServiceProfile.IIIF2IMAGELEVEL2PROFILE.toString())) { return true; } return false; }; Utils.loadResource = function (uri) { return new Promise(function (resolve, reject) { var u = url.parse(uri); var req; var opts = { host: u.hostname, port: u.port, path: u.path, method: "GET", withCredentials: false }; switch (u.protocol) { case 'https:': req = https.request(opts, function (response) { var result = ""; response.on('data', function (chunk) { result += chunk; }); response.on('end', function () { resolve(result); }); }); req.on('error', function (error) { reject(error); }); req.end(); break; case 'dat:': var xhr_1 = new XMLHttpRequest(); xhr_1.onreadystatechange = function () { if (xhr_1.readyState === 4) { resolve(xhr_1.response); } }; xhr_1.open("GET", uri, true); xhr_1.send(); break; default: req = http.request(opts, function (response) { var result = ""; response.on('data', function (chunk) { result += chunk; }); response.on('end', function () { resolve(result); }); }); req.on('error', function (error) { reject(error); }); req.end(); break; } }); }; Utils.loadExternalResourcesAuth1 = function (resources, openContentProviderInteraction, openTokenService, getStoredAccessToken, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages) { return new Promise(function (resolve, reject) { var promises = resources.map(function (resource) { return Utils.loadExternalResourceAuth1(resource, openContentProviderInteraction, openTokenService, getStoredAccessToken, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages); }); Promise.all(promises) .then(function () { resolve(resources); })["catch"](function (error) { reject(error); }); }); }; Utils.loadExternalResourceAuth1 = function (resource, openContentProviderInteraction, openTokenService, getStoredAccessToken, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages) { return __awaiter(this, void 0, void 0, function () { var storedAccessToken; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getStoredAccessToken(resource)]; case 1: storedAccessToken = _a.sent(); if (!storedAccessToken) return [3 /*break*/, 6]; return [4 /*yield*/, resource.getData(storedAccessToken)]; case 2: _a.sent(); if (!(resource.status === HTTPStatusCode.OK)) return [3 /*break*/, 3]; return [2 /*return*/, resource]; case 3: // the stored token is no good for this resource return [4 /*yield*/, Utils.doAuthChain(resource, openContentProviderInteraction, openTokenService, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages)]; case 4: // the stored token is no good for this resource _a.sent(); _a.label = 5; case 5: if (resource.status === HTTPStatusCode.OK || resource.status === HTTPStatusCode.MOVED_TEMPORARILY) { return [2 /*return*/, resource]; } throw Utils.createAuthorizationFailedError(); case 6: return [4 /*yield*/, resource.getData()]; case 7: _a.sent(); if (!(resource.status === HTTPStatusCode.MOVED_TEMPORARILY || resource.status === HTTPStatusCode.UNAUTHORIZED)) return [3 /*break*/, 9]; return [4 /*yield*/, Utils.doAuthChain(resource, openContentProviderInteraction, openTokenService, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages)]; case 8: _a.sent(); _a.label = 9; case 9: if (resource.status === HTTPStatusCode.OK || resource.status === HTTPStatusCode.MOVED_TEMPORARILY) { return [2 /*return*/, resource]; } throw Utils.createAuthorizationFailedError(); } }); }); }; Utils.doAuthChain = function (resource, openContentProviderInteraction, openTokenService, userInteractedWithContentProvider, getContentProviderInteraction, handleMovedTemporarily, showOutOfOptionsMessages) { return __awaiter(this, void 0, void 0, function () { var externalService, kioskService, clickThroughService, loginService, serviceToTry, lastAttempted, kioskInteraction, contentProviderInteraction, contentProviderInteraction; return __generator(this, function (_a) { switch (_a.label) { case 0: // This function enters the flowchart at the < External? > junction // http://iiif.io/api/auth/1.0/#workflow-from-the-browser-client-perspective if (!resource.isAccessControlled()) { return [2 /*return*/, resource]; // no services found } externalService = resource.externalService; if (externalService) { externalService.options = resource.options; } kioskService = resource.kioskService; if (kioskService) { kioskService.options = resource.options; } clickThroughService = resource.clickThroughService; if (clickThroughService) { clickThroughService.options = resource.options; } loginService = resource.loginService; if (loginService) { loginService.options = resource.options; } if (!(!resource.isResponseHandled && resource.status === HTTPStatusCode.MOVED_TEMPORARILY)) return [3 /*break*/, 2]; return [4 /*yield*/, handleMovedTemporarily(resource)]; case 1: _a.sent(); return [2 /*return*/, resource]; case 2: serviceToTry = null; lastAttempted = null; // repetition of logic is left in these steps for clarity: // Looking for external pattern serviceToTry = externalService; if (!serviceToTry) return [3 /*break*/, 4]; lastAttempted = serviceToTry; return [4 /*yield*/, Utils.attemptResourceWithToken(resource, openTokenService, serviceToTry)]; case 3: _a.sent(); return [2 /*return*/, resource]; case 4: // Looking for kiosk pattern serviceToTry = kioskService; if (!serviceToTry) return [3 /*break*/, 7]; lastAttempted = serviceToTry; kioskInteraction = openContentProviderInteraction(serviceToTry); if (!kioskInteraction) return [3 /*break*/, 7]; return [4 /*yield*/, userInteractedWithContentProvider(kioskInteraction)]; case 5: _a.sent(); return [4 /*yield*/, Utils.attemptResourceWithToken(resource, openTokenService, serviceToTry)]; case 6: _a.sent(); return [2 /*return*/, resource]; case 7: // The code for the next two patterns is identical (other than the profile name). // The difference is in the expected behaviour of // // await userInteractedWithContentProvider(contentProviderInteraction); // // For clickthrough the opened window should close immediately having established // a session, whereas for login the user might spend some time entering credentials etc. // Looking for clickthrough pattern serviceToTry = clickThroughService; if (!serviceToTry) return [3 /*break*/, 11]; lastAttempted = serviceToTry; return [4 /*yield*/, getContentProviderInteraction(resource, serviceToTry)]; case 8: contentProviderInteraction = _a.sent(); if (!contentProviderInteraction) return [3 /*break*/, 11]; // should close immediately return [4 /*yield*/, userInteractedWithContentProvider(contentProviderInteraction)]; case 9: // should close immediately _a.sent(); return [4 /*yield*/, Utils.attemptResourceWithToken(resource, openTokenService, serviceToTry)]; case 10: _a.sent(); return [2 /*return*/, resource]; case 11: // Looking for login pattern serviceToTry = loginService; if (!serviceToTry) return [3 /*break*/, 15]; lastAttempted = serviceToTry; return [4 /*yield*/, getContentProviderInteraction(resource, serviceToTry)]; case 12: contentProviderInteraction = _a.sent(); if (!contentProviderInteraction) return [3 /*break*/, 15]; // we expect the user to spend some time interacting return [4 /*yield*/, userInteractedWithContentProvider(contentProviderInteraction)]; case 13: // we expect the user to spend some time interacting _a.sent(); return [4 /*yield*/, Utils.attemptResourceWithToken(resource, openTokenService, serviceToTry)]; case 14: _a.sent(); return [2 /*return*/, resource]; case 15: // nothing worked! Use the most recently tried service as the source of // messages to show to the user. if (lastAttempted) { showOutOfOptionsMessages(resource, lastAttempted); } return [2 /*return*/]; } }); }); }; Utils.attemptResourceWithToken = function (resource, openTokenService, authService) { return __awaiter(this, void 0, void 0, function () { var tokenService, tokenMessage; return __generator(this, function (_a) { switch (_a.label) { case 0: tokenService = authService.getService(Manifesto.ServiceProfile.AUTH1TOKEN.toString()); if (!tokenService) return [3 /*break*/, 3]; return [4 /*yield*/, openTokenService(resource, tokenService)]; case 1: tokenMessage = _a.sent(); if (!(tokenMessage && tokenMessage.accessToken)) return [3 /*break*/, 3]; return [4 /*yield*/, resource.getData(tokenMessage)]; case 2: _a.sent(); return [2 /*return*/, resource]; case 3: return [2 /*return*/]; } }); }); }; Utils.loadExternalResourcesAuth09 = function (resources, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken, handleResourceResponse, options) { return new Promise(function (resolve, reject) { var promises = resources.map(function (resource) { return Utils.loadExternalResourceAuth09(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken, handleResourceResponse, options); }); Promise.all(promises) .then(function () { resolve(resources); })["catch"](function (error) { reject(error); }); }); }; // IIIF auth api pre v1.0 // Keeping this around for now until the auth 1.0 implementation is stable Utils.loadExternalResourceAuth09 = function (resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken, handleResourceResponse, options) { return new Promise(function (resolve, reject) { if (options && options.pessimisticAccessControl) { // pessimistic: access control cookies may have been deleted. // always request the access token for every access controlled info.json request // returned access tokens are not stored, therefore the login window flashes for every request. resource.getData().then(function () { if (resource.isAccessControlled()) { // if the resource has a click through service, use that. if (resource.clickThroughService) { resolve(clickThrough(resource)); //} else if(resource.restrictedService) { resolve(restricted(resource)); } else { login(resource).then(function () { getAccessToken(resource, true).then(function (token) { resource.getData(token).then(function () { resolve(handleResourceResponse(resource)); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); } } else { // this info.json isn't access controlled, therefore no need to request an access token. resolve(resource); } })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); } else { // optimistic: access control cookies may not have been deleted. // store access tokens to avoid login window flashes. // if cookies are deleted a page refresh is required. // try loading the resource using an access token that matches the info.json domain. // if an access token is found, request the resource using it regardless of whether it is access controlled. getStoredAccessToken(resource, tokenStorageStrategy).then(function (storedAccessToken) { if (storedAccessToken) { // try using the stored access token resource.getData(storedAccessToken).then(function () { // if the info.json loaded using the stored access token if (resource.status === HTTPStatusCode.OK) { resolve(handleResourceResponse(resource)); } else { // otherwise, load the resource data to determine the correct access control services. // if access controlled, do login. Utils.authorize(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken).then(function () { resolve(handleResourceResponse(resource)); })["catch"](function (error) { // if (resource.restrictedService){ // reject(Utils.createRestrictedError()); // } else { reject(Utils.createAuthorizationFailedError()); //} }); } })["catch"](function (error) { reject(Utils.createAuthorizationFailedError()); }); } else { Utils.authorize(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken).then(function () { resolve(handleResourceResponse(resource)); })["catch"](function (error) { reject(Utils.createAuthorizationFailedError()); }); } })["catch"](function (error) { reject(Utils.createAuthorizationFailedError()); }); } }); }; Utils.createError = function (name, message) { var error = new Error(); error.message = message; error.name = name; return error; }; Utils.createAuthorizationFailedError = function () { return Utils.createError(manifesto.StatusCodes.AUTHORIZATION_FAILED.toString(), "Authorization failed"); }; Utils.createRestrictedError = function () { return Utils.createError(manifesto.StatusCodes.RESTRICTED.toString(), "Restricted"); }; Utils.createInternalServerError = function (message) { return Utils.createError(manifesto.StatusCodes.INTERNAL_SERVER_ERROR.toString(), message); }; Utils.authorize = function (resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, getStoredAccessToken) { return new Promise(function (resolve, reject) { resource.getData().then(function () { if (resource.isAccessControlled()) { getStoredAccessToken(resource, tokenStorageStrategy).then(function (storedAccessToken) { if (storedAccessToken) { // try using the stored access token resource.getData(storedAccessToken).then(function () { if (resource.status === HTTPStatusCode.OK) { resolve(resource); // happy path ended } else { // the stored token is no good for this resource Utils.showAuthInteraction(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, resolve, reject); } })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); } else { // There was no stored token, but the user might have a cookie that will grant a token getAccessToken(resource, false).then(function (accessToken) { if (accessToken) { storeAccessToken(resource, accessToken, tokenStorageStrategy).then(function () { // try using the fresh access token resource.getData(accessToken).then(function () { if (resource.status === HTTPStatusCode.OK) { resolve(resource); } else { // User has a token, but it's not good enough Utils.showAuthInteraction(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, resolve, reject); } })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { // not able to store access token reject(Utils.createInternalServerError(message)); }); } else { // The user did not have a cookie that granted a token Utils.showAuthInteraction(resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, resolve, reject); } }); } })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); } else { // this info.json isn't access controlled, therefore there's no need to request an access token resolve(resource); } }); }); }; Utils.showAuthInteraction = function (resource, tokenStorageStrategy, clickThrough, restricted, login, getAccessToken, storeAccessToken, resolve, reject) { if (resource.status === HTTPStatusCode.MOVED_TEMPORARILY && !resource.isResponseHandled) { // if the resource was redirected to a degraded version // and the response hasn't been handled yet. // if the client wishes to trigger a login, set resource.isResponseHandled to true // and call loadExternalResources() again passing the resource. resolve(resource); // } else if (resource.restrictedService) { // resolve(restricted(resource)); // // TODO: move to next etc } else if (resource.clickThroughService && !resource.isResponseHandled) { // if the resource has a click through service, use that. clickThrough(resource).then(function () { getAccessToken(resource, true).then(function (accessToken) { storeAccessToken(resource, accessToken, tokenStorageStrategy).then(function () { resource.getData(accessToken).then(function () { resolve(resource); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); }); } else { // get an access token login(resource).then(function () { getAccessToken(resource, true).then(function (accessToken) { storeAccessToken(resource, accessToken, tokenStorageStrategy).then(function () { resource.getData(accessToken).then(function () { resolve(resource); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); })["catch"](function (message) { reject(Utils.createInternalServerError(message)); }); }); } }; ; Utils.getService = function (resource, profile) { var services = this.getServices(resource); // coerce profile to string if (typeof (profile) !== 'string') { profile = profile.toString(); } for (var i = 0; i < services.length; i++) { var service = services[i]; if (service.getProfile().toString() === profile) { return service; } } return null; }; Utils.getResourceById = function (parentResource, id) { return [parentResource.__jsonld].en().traverseUnique(function (x) { return Utils.getAllArrays(x); }) .first(function (r) { return r['@id'] === id; }); }; Utils.getAllArrays = function (obj) { var all = [].en(); if (!obj) return all; for (var key in obj) { var val = obj[key]; if (Array.isArray(val)) { all = all.concat(val); } } return all; }; Utils.getServices = function (resource) { var service; // if passing a manifesto-parsed object, use the __jsonld.service property, // otherwise look for a service property (info.json services) if (resource.__jsonld) { service = resource.__jsonld.service; } else { service = resource.service; } var services = []; if (!service) return services; // coerce to array if (!Array.isArray(service)) { service = [service]; } for (var i = 0; i < service.length; i++) { var s = service[i]; if (typeof (s) === 'string') { var r = this.getResourceById(resource.options.resource, s); if (r) { services.push(new Manifesto.Service(r.__jsonld || r, resource.options)); } } else { services.push(new Manifesto.Service(s, resource.options)); } } return services; }; return Utils; }()); Manifesto.Utils = Utils; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var MetadataItem = /** @class */ (function () { function MetadataItem(defaultLocale) { this.defaultLocale = defaultLocale; } MetadataItem.prototype.parse = function (resource) { this.resource = resource; this.label = Manifesto.TranslationCollection.parse(this.resource.label, this.defaultLocale); this.value = Manifesto.TranslationCollection.parse(this.resource.value, this.defaultLocale); }; // shortcuts to get/set values based on default locale MetadataItem.prototype.getLabel = function () { if (this.label) { return Manifesto.TranslationCollection.getValue(this.label, this.defaultLocale); } return null; }; MetadataItem.prototype.setLabel = function (value) { var _this = this; if (this.label && this.label.length) { var t = this.label.en().where(function (x) { return x.locale === _this.defaultLocale || x.locale === Manifesto.Utils.getInexactLocale(_this.defaultLocale); }).first(); if (t) t.value = value; } }; MetadataItem.prototype.getValue = function () { if (this.value) { var locale = this.defaultLocale; // if the label has a locale, prefer that to the default locale if (this.label.length && this.label[0].locale) { locale = this.label[0].locale; } return Manifesto.TranslationCollection.getValue(this.value, locale); } return null; }; MetadataItem.prototype.setValue = function (value) { var _this = this; if (this.value && this.value.length) { var t = this.value.en().where(function (x) { return x.locale === _this.defaultLocale || x.locale === Manifesto.Utils.getInexactLocale(_this.defaultLocale); }).first(); if (t) t.value = value; } }; return MetadataItem; }()); Manifesto.MetadataItem = MetadataItem; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var Translation = /** @class */ (function () { function Translation(value, locale) { this.value = value; this.locale = locale; } return Translation; }()); Manifesto.Translation = Translation; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var TranslationCollection = /** @class */ (function (_super) { __extends(TranslationCollection, _super); function TranslationCollection() { return _super !== null && _super.apply(this, arguments) || this; } TranslationCollection.parse = function (translation, defaultLocale) { var tc = []; var t; if (!translation) { return tc; } else if (Array.isArray(translation)) { for (var i = 0; i < translation.length; i++) { var value = translation[i]; if (typeof (value) === 'string') { t = new Manifesto.Translation(value, defaultLocale); } else { t = new Manifesto.Translation(value['@value'], value['@language'] || defaultLocale); } tc.push(t); } } else if (typeof (translation) === 'string') { // if it's just a single string value, create one translation in the configured locale t = new Manifesto.Translation(translation, defaultLocale); tc.push(t); return tc; } else { // it's an object if (translation['@value']) { // presentation 2 t = new Manifesto.Translation(translation['@value'], translation['@language'] || defaultLocale); tc.push(t); } else { // presentation 3 Object.keys(translation).forEach(function (key) { // todo: support multiple values in array if (translation[key].length) { t = new Manifesto.Translation(translation[key][0], key); tc.push(t); } else { throw new Error('Translation must have a value'); } }); } } return tc; }; TranslationCollection.getValue = function (translationCollection, locale) { if (translationCollection.length) { if (locale) { var translation = translationCollection.en().where(function (t) { return t.locale === locale || Manifesto.Utils.getInexactLocale(t.locale) === Manifesto.Utils.getInexactLocale(locale); }).first(); if (translation) { return translation.value; } } // return the first valuel return translationCollection[0].value; } return null; }; return TranslationCollection; }(Array)); Manifesto.TranslationCollection = TranslationCollection; })(Manifesto || (Manifesto = {})); var Manifesto; (function (Manifesto) { var Size = /** @class */ (function () { function Size(width, height) { this.width = width; this.height = height; } return Size; }()); Manifesto.Size = Size; })(Manifesto || (Manifesto = {})); /// <reference types="http-status-codes" /> global.manifesto = global.Manifesto = module.exports = { AnnotationMotivation: new Manifesto.AnnotationMotivation(), Behavior: new Manifesto.Behavior(), IIIFResourceType: new Manifesto.IIIFResourceType(), ManifestType: new Manifesto.ManifestType(), MediaType: new Manifesto.MediaType(), MetadataItem: Manifesto.MetadataItem, RenderingFormat: new Manifesto.RenderingFormat(), ResourceType: new Manifesto.ResourceType(), ServiceProfile: new Manifesto.ServiceProfile(), Size: Manifesto.Size, Translation: Manifesto.Translation, TranslationCollection: Manifesto.TranslationCollection, TreeNode: Manifesto.TreeNode, TreeNodeType: new Manifesto.TreeNodeType(), Utils: Manifesto.Utils, ViewingDirection: new Manifesto.ViewingDirection(), ViewingHint: new Manifesto.ViewingHint(), StatusCodes: { AUTHORIZATION_FAILED: 1, FORBIDDEN: 2, INTERNAL_SERVER_ERROR: 3, RESTRICTED: 4 }, create: function (manifest, options) { return Manifesto.Deserialiser.parse(manifest, options); }, loadManifest: function (uri) { return Manifesto.Utils.loadResource(uri); } }; 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 Manifesto; (function (Manifesto) { var Annotation = /** @class */ (function (_super) { __extends(Annotation, _super); function Annotation(jsonld, options) { return _super.call(this, jsonld, options) || this; } Annotation.prototype.getBody = function () { var bodies = []; var body = this.getProperty('body'); // todo: make this a generic "property that can be an object or array enumerator" util if (body) { if (Array.isArray(body)) { for (var i = 0; i < body.length; i++) { var b = body[i]; if (b.items) { for (var i_1 = 0; i_1 < b.items.length; i_1++) { var c = b.items[i_1]; bodies.push(new Manifesto.AnnotationBody(c, this.options)); } } else { bodies.push(new Manifesto.AnnotationBody(b, this.options)); } } } else if (body.items) { for (var i = 0; i < body.items.length; i++) { var b = body.items[i]; bodies.push(new Manifesto.AnnotationBody(b, this.options)); } } else { bodies.push(new Manifesto.AnnotationBody(body, this.options)); } } return bodies; }; Annotation.prototype.getMotivation = function () { var motivation = this.getProperty('motivation'); if (motivation) { return new Manifesto.AnnotationMotivation(motivation.toLowerCase()); } return null; }; // open annotation Annotation.prototype.getOn = function () { return this.getProperty('on'); }; Annotation.prototype.getTarget = function () { return this.getProperty('target'); }; Annotation.prototype.getResource = function () { return new Manifesto.Resource(this.getProperty('resource'), this.options); }; return Annotation; }(Manifesto.ManifestResource)); Manifesto.Annotation = Annotation; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var AnnotationBody = /** @class */ (function (_super) { __extends(AnnotationBody, _super); function AnnotationBody(jsonld, options) { return _super.call(this, jsonld, options) || this; } AnnotationBody.prototype.getFormat = function () { var format = this.getProperty('format'); if (format) { return new Manifesto.MediaType(Manifesto.Utils.getMediaType(format)); } return null; }; AnnotationBody.prototype.getType = function () { var type = this.getProperty('type'); if (type) { return new Manifesto.ResourceType(Manifesto.Utils.normaliseType(this.getProperty('type'))); } return null; }; return AnnotationBody; }(Manifesto.ManifestResource)); Manifesto.AnnotationBody = AnnotationBody; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var AnnotationList = /** @class */ (function (_super) { __extends(AnnotationList, _super); function AnnotationList(label, jsonld, options) { var _this = _super.call(this, jsonld) || this; _this.label = label; _this.options = options; return _this; } AnnotationList.prototype.getIIIFResourceType = function () { return new Manifesto.IIIFResourceType(Manifesto.Utils.normaliseType(this.getProperty('type'))); }; AnnotationList.prototype.getLabel = function () { return this.label; }; AnnotationList.prototype.getResources = function () { var _this = this; var resources = this.getProperty('resources'); return resources.map(function (resource) { return new Manifesto.Annotation(resource, _this.options); }); }; AnnotationList.prototype.load = function () { var _this = this; return new Promise(function (resolve, reject) { if (_this.isLoaded) { resolve(_this); } else { var id = _this.__jsonld.id; if (!id) { id = _this.__jsonld['@id']; } Manifesto.Utils.loadResource(id).then(function (data) { _this.__jsonld = JSON.parse(data); _this.context = _this.getProperty('context'); _this.id = _this.getProperty('id'); _this.isLoaded = true; resolve(_this); }).catch(reject); } }); }; return AnnotationList; }(Manifesto.JSONLDResource)); Manifesto.AnnotationList = AnnotationList; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var AnnotationPage = /** @class */ (function (_super) { __extends(AnnotationPage, _super); function AnnotationPage(jsonld, options) { return _super.call(this, jsonld, options) || this; } AnnotationPage.prototype.getItems = function () { return this.getProperty('items'); }; return AnnotationPage; }(Manifesto.ManifestResource)); Manifesto.AnnotationPage = AnnotationPage; })(Manifesto || (Manifesto = {})); 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 Manifesto; (function (Manifesto) { var Thumbnail = /** @class */ (function (_super) { __extends(Thumbnail, _super); function Thumbnail(jsonld, options) { return _super.call(this, jsonld, options) || this; } return Thumbnail; }(Manifesto.Resource)); Manifesto.Thumbnail = Thumbnail; })(Manifesto || (Manifesto = {})); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"http":30,"https":8,"url":35}],2:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],3:[function(require,module,exports){ },{}],4:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).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 true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":2,"ieee754":9,"isarray":12}],5:[function(require,module,exports){ module.exports = { "100": "Continue", "101": "Switching Protocols", "102": "Processing", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-Authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "207": "Multi-Status", "208": "Already Reported", "226": "IM Used", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "307": "Temporary Redirect", "308": "Permanent Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Payload Too Large", "414": "URI Too Long", "415": "Unsupported Media Type", "416": "Range Not Satisfiable", "417": "Expectation Failed", "418": "I'm a teapot", "421": "Misdirected Request", "422": "Unprocessable Entity", "423": "Locked", "424": "Failed Dependency", "425": "Unordered Collection", "426": "Upgrade Required", "428": "Precondition Required", "429": "Too Many Requests", "431": "Request Header Fields Too Large", "451": "Unavailable For Legal Reasons", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported", "506": "Variant Also Negotiates", "507": "Insufficient Storage", "508": "Loop Detected", "509": "Bandwidth Limit Exceeded", "510": "Not Extended", "511": "Network Authentication Required" } },{}],6:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":11}],7:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],8:[function(require,module,exports){ var http = require('http'); var https = module.exports; for (var key in http) { if (http.hasOwnProperty(key)) https[key] = http[key]; }; https.request = function (params, cb) { if (!params) params = {}; params.scheme = 'https'; params.protocol = 'https:'; return http.request.call(this, params, cb); } },{"http":30}],9:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],10:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],11:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],12:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],13:[function(require,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,require('_process')) },{"_process":14}],14:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],15:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],16:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],17:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],18:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":16,"./encode":17}],19:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var processNextTick = require('process-nextick-args').nextTick; /*</replacement>*/ /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. processNextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); processNextTick(cb, err); }; function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":21,"./_stream_writable":23,"core-util-is":6,"inherits":10,"process-nextick-args":13}],20:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":22,"core-util-is":6,"inherits":10}],21:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var processNextTick = require('process-nextick-args').nextTick; /*</replacement>*/ module.exports = Readable; /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /*</replacement>*/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; processNextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { processNextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; processNextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; processNextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":19,"./internal/streams/BufferList":24,"./internal/streams/destroy":25,"./internal/streams/stream":26,"_process":14,"core-util-is":6,"events":7,"inherits":10,"isarray":12,"process-nextick-args":13,"safe-buffer":29,"string_decoder/":27,"util":3}],22:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":19,"core-util-is":6,"inherits":10}],23:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /*<replacement>*/ var processNextTick = require('process-nextick-args').nextTick; /*</replacement>*/ module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); processNextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); processNextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack processNextTick(cb, er); // this can emit finish, and it will always happen // after error processNextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /*<replacement>*/ asyncWrite(afterWrite, stream, state, finished, cb); /*</replacement>*/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; processNextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) processNextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":19,"./internal/streams/destroy":25,"./internal/streams/stream":26,"_process":14,"core-util-is":6,"inherits":10,"process-nextick-args":13,"safe-buffer":29,"util-deprecate":37}],24:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; var util = require('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":29,"util":3}],25:[function(require,module,exports){ 'use strict'; /*<replacement>*/ var processNextTick = require('process-nextick-args').nextTick; /*</replacement>*/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { processNextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { processNextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":13}],26:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":7}],27:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return -1; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'.repeat(p); } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'.repeat(p + 1); } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'.repeat(p + 2); } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":29}],28:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":19,"./lib/_stream_passthrough.js":20,"./lib/_stream_readable.js":21,"./lib/_stream_transform.js":22,"./lib/_stream_writable.js":23}],29:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":4}],30:[function(require,module,exports){ (function (global){ var ClientRequest = require('./lib/request') var IncomingMessage = require('./lib/response') var extend = require('xtend') var statusCodes = require('builtin-status-codes') var url = require('url') var http = exports http.request = function (opts, cb) { if (typeof opts === 'string') opts = url.parse(opts) else opts = extend(opts) // Normally, the page is loaded from http or https, so not specifying a protocol // will result in a (valid) protocol-relative url. However, this won't work if // the protocol is something else, like 'file:' var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' var protocol = opts.protocol || defaultProtocol var host = opts.hostname || opts.host var port = opts.port var path = opts.path || '/' // Necessary for IPv6 addresses if (host && host.indexOf(':') !== -1) host = '[' + host + ']' // This may be a relative url. The browser should always be able to interpret it correctly. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path opts.method = (opts.method || 'GET').toUpperCase() opts.headers = opts.headers || {} // Also valid opts.auth, opts.mode var req = new ClientRequest(opts) if (cb) req.on('response', cb) return req } http.get = function get (opts, cb) { var req = http.request(opts, cb) req.end() return req } http.ClientRequest = ClientRequest http.IncomingMessage = IncomingMessage http.Agent = function () {} http.Agent.defaultMaxSockets = 4 http.STATUS_CODES = statusCodes http.METHODS = [ 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REPORT', 'SEARCH', 'SUBSCRIBE', 'TRACE', 'UNLOCK', 'UNSUBSCRIBE' ] }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./lib/request":32,"./lib/response":33,"builtin-status-codes":5,"url":35,"xtend":38}],31:[function(require,module,exports){ (function (global){ exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) exports.writableStream = isFunction(global.WritableStream) exports.abortController = isFunction(global.AbortController) exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) exports.blobConstructor = true } catch (e) {} // The xhr request to example.com may violate some restrictive CSP configurations, // so if we're running in a browser that supports `fetch`, avoid calling getXHR() // and assume support for certain features below. var xhr function getXHR () { // Cache the xhr value if (xhr !== undefined) return xhr if (global.XMLHttpRequest) { xhr = new global.XMLHttpRequest() // If XDomainRequest is available (ie only, where xhr might not work // cross domain), use the page location. Otherwise use example.com // Note: this doesn't actually make an http request. try { xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') } catch(e) { xhr = null } } else { // Service workers don't have XHR xhr = null } return xhr } function checkTypeSupport (type) { var xhr = getXHR() if (!xhr) return false try { xhr.responseType = type return xhr.responseType === type } catch (e) {} return false } // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. // Safari 7.1 appears to have fixed this bug. var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) // If fetch is supported, then arraybuffer will be supported too. Skip calling // checkTypeSupport(), since that calls getXHR(). exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) // These next two tests unavoidably show warnings in Chrome. Since fetch will always // be used if it's available, just return false for these to avoid the warnings. exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer') // If fetch is supported, then overrideMimeType will be supported too. Skip calling // getXHR(). exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) exports.vbArray = isFunction(global.VBArray) function isFunction (value) { return typeof value === 'function' } xhr = null // Help gc }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],32:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') var response = require('./response') var stream = require('readable-stream') var toArrayBuffer = require('to-arraybuffer') var IncomingMessage = response.IncomingMessage var rStates = response.readyStates function decideMode (preferBinary, useFetch) { if (capability.fetch && useFetch) { return 'fetch' } else if (capability.mozchunkedarraybuffer) { return 'moz-chunked-arraybuffer' } else if (capability.msstream) { return 'ms-stream' } else if (capability.arraybuffer && preferBinary) { return 'arraybuffer' } else if (capability.vbArray && preferBinary) { return 'text:vbarray' } else { return 'text' } } var ClientRequest = module.exports = function (opts) { var self = this stream.Writable.call(self) self._opts = opts self._body = [] self._headers = {} if (opts.auth) self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) Object.keys(opts.headers).forEach(function (name) { self.setHeader(name, opts.headers[name]) }) var preferBinary var useFetch = true if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { // If the use of XHR should be preferred. Not typically needed. useFetch = false preferBinary = true } else if (opts.mode === 'prefer-streaming') { // If streaming is a high priority but binary compatibility and // the accuracy of the 'content-type' header aren't preferBinary = false } else if (opts.mode === 'allow-wrong-content-type') { // If streaming is more important than preserving the 'content-type' header preferBinary = !capability.overrideMimeType } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { // Use binary if text streaming may corrupt data or the content-type header, or for speed preferBinary = true } else { throw new Error('Invalid value for opts.mode') } self._mode = decideMode(preferBinary, useFetch) self.on('finish', function () { self._onFinish() }) } inherits(ClientRequest, stream.Writable) ClientRequest.prototype.setHeader = function (name, value) { var self = this var lowerName = name.toLowerCase() // This check is not necessary, but it prevents warnings from browsers about setting unsafe // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but // http-browserify did it, so I will too. if (unsafeHeaders.indexOf(lowerName) !== -1) return self._headers[lowerName] = { name: name, value: value } } ClientRequest.prototype.getHeader = function (name) { var header = this._headers[name.toLowerCase()] if (header) return header.value return null } ClientRequest.prototype.removeHeader = function (name) { var self = this delete self._headers[name.toLowerCase()] } ClientRequest.prototype._onFinish = function () { var self = this if (self._destroyed) return var opts = self._opts var headersObj = self._headers var body = null if (opts.method !== 'GET' && opts.method !== 'HEAD') { if (capability.arraybuffer) { body = toArrayBuffer(Buffer.concat(self._body)) } else if (capability.blobConstructor) { body = new global.Blob(self._body.map(function (buffer) { return toArrayBuffer(buffer) }), { type: (headersObj['content-type'] || {}).value || '' }) } else { // get utf8 string body = Buffer.concat(self._body).toString() } } // create flattened list of headers var headersList = [] Object.keys(headersObj).forEach(function (keyName) { var name = headersObj[keyName].name var value = headersObj[keyName].value if (Array.isArray(value)) { value.forEach(function (v) { headersList.push([name, v]) }) } else { headersList.push([name, value]) } }) if (self._mode === 'fetch') { var signal = null if (capability.abortController) { var controller = new AbortController() signal = controller.signal self._fetchAbortController = controller if ('requestTimeout' in opts && opts.requestTimeout !== 0) { global.setTimeout(function () { self.emit('requestTimeout') if (self._fetchAbortController) self._fetchAbortController.abort() }, opts.requestTimeout) } } global.fetch(self._opts.url, { method: self._opts.method, headers: headersList, body: body || undefined, mode: 'cors', credentials: opts.withCredentials ? 'include' : 'same-origin', signal: signal }).then(function (response) { self._fetchResponse = response self._connect() }, function (reason) { self.emit('error', reason) }) } else { var xhr = self._xhr = new global.XMLHttpRequest() try { xhr.open(self._opts.method, self._opts.url, true) } catch (err) { process.nextTick(function () { self.emit('error', err) }) return } // Can't set responseType on really old browsers if ('responseType' in xhr) xhr.responseType = self._mode.split(':')[0] if ('withCredentials' in xhr) xhr.withCredentials = !!opts.withCredentials if (self._mode === 'text' && 'overrideMimeType' in xhr) xhr.overrideMimeType('text/plain; charset=x-user-defined') if ('requestTimeout' in opts) { xhr.timeout = opts.requestTimeout xhr.ontimeout = function () { self.emit('requestTimeout') } } headersList.forEach(function (header) { xhr.setRequestHeader(header[0], header[1]) }) self._response = null xhr.onreadystatechange = function () { switch (xhr.readyState) { case rStates.LOADING: case rStates.DONE: self._onXHRProgress() break } } // Necessary for streaming in Firefox, since xhr.response is ONLY defined // in onprogress, not in onreadystatechange with xhr.readyState = 3 if (self._mode === 'moz-chunked-arraybuffer') { xhr.onprogress = function () { self._onXHRProgress() } } xhr.onerror = function () { if (self._destroyed) return self.emit('error', new Error('XHR error')) } try { xhr.send(body) } catch (err) { process.nextTick(function () { self.emit('error', err) }) return } } } /** * Checks if xhr.status is readable and non-zero, indicating no error. * Even though the spec says it should be available in readyState 3, * accessing it throws an exception in IE8 */ function statusValid (xhr) { try { var status = xhr.status return (status !== null && status !== 0) } catch (e) { return false } } ClientRequest.prototype._onXHRProgress = function () { var self = this if (!statusValid(self._xhr) || self._destroyed) return if (!self._response) self._connect() self._response._onXHRProgress() } ClientRequest.prototype._connect = function () { var self = this if (self._destroyed) return self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) self._response.on('error', function(err) { self.emit('error', err) }) self.emit('response', self._response) } ClientRequest.prototype._write = function (chunk, encoding, cb) { var self = this self._body.push(chunk) cb() } ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { var self = this self._destroyed = true if (self._response) self._response._destroyed = true if (self._xhr) self._xhr.abort() else if (self._fetchAbortController) self._fetchAbortController.abort() } ClientRequest.prototype.end = function (data, encoding, cb) { var self = this if (typeof data === 'function') { cb = data data = undefined } stream.Writable.prototype.end.call(self, data, encoding, cb) } ClientRequest.prototype.flushHeaders = function () {} ClientRequest.prototype.setTimeout = function () {} ClientRequest.prototype.setNoDelay = function () {} ClientRequest.prototype.setSocketKeepAlive = function () {} // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method var unsafeHeaders = [ 'accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via' ] }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":31,"./response":33,"_process":14,"buffer":4,"inherits":10,"readable-stream":28,"to-arraybuffer":34}],33:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') var stream = require('readable-stream') var rStates = exports.readyStates = { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 } var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { var self = this stream.Readable.call(self) self._mode = mode self.headers = {} self.rawHeaders = [] self.trailers = {} self.rawTrailers = [] // Fake the 'close' event, but only once 'end' fires self.on('end', function () { // The nextTick is necessary to prevent the 'request' module from causing an infinite loop process.nextTick(function () { self.emit('close') }) }) if (mode === 'fetch') { self._fetchResponse = response self.url = response.url self.statusCode = response.status self.statusMessage = response.statusText response.headers.forEach(function (header, key){ self.headers[key.toLowerCase()] = header self.rawHeaders.push(key, header) }) if (capability.writableStream) { var writable = new WritableStream({ write: function (chunk) { return new Promise(function (resolve, reject) { if (self._destroyed) { return } else if(self.push(new Buffer(chunk))) { resolve() } else { self._resumeFetch = resolve } }) }, close: function () { if (!self._destroyed) self.push(null) }, abort: function (err) { if (!self._destroyed) self.emit('error', err) } }) try { response.body.pipeTo(writable) return } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this } // fallback for when writableStream or pipeTo aren't available var reader = response.body.getReader() function read () { reader.read().then(function (result) { if (self._destroyed) return if (result.done) { self.push(null) return } self.push(new Buffer(result.value)) read() }).catch(function(err) { if (!self._destroyed) self.emit('error', err) }) } read() } else { self._xhr = xhr self._pos = 0 self.url = xhr.responseURL self.statusCode = xhr.status self.statusMessage = xhr.statusText var headers = xhr.getAllResponseHeaders().split(/\r?\n/) headers.forEach(function (header) { var matches = header.match(/^([^:]+):\s*(.*)/) if (matches) { var key = matches[1].toLowerCase() if (key === 'set-cookie') { if (self.headers[key] === undefined) { self.headers[key] = [] } self.headers[key].push(matches[2]) } else if (self.headers[key] !== undefined) { self.headers[key] += ', ' + matches[2] } else { self.headers[key] = matches[2] } self.rawHeaders.push(matches[1], matches[2]) } }) self._charset = 'x-user-defined' if (!capability.overrideMimeType) { var mimeType = self.rawHeaders['mime-type'] if (mimeType) { var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) if (charsetMatch) { self._charset = charsetMatch[1].toLowerCase() } } if (!self._charset) self._charset = 'utf-8' // best guess } } } inherits(IncomingMessage, stream.Readable) IncomingMessage.prototype._read = function () { var self = this var resolve = self._resumeFetch if (resolve) { self._resumeFetch = null resolve() } } IncomingMessage.prototype._onXHRProgress = function () { var self = this var xhr = self._xhr var response = null switch (self._mode) { case 'text:vbarray': // For IE9 if (xhr.readyState !== rStates.DONE) break try { // This fails in IE8 response = new global.VBArray(xhr.responseBody).toArray() } catch (e) {} if (response !== null) { self.push(new Buffer(response)) break } // Falls through in IE8 case 'text': try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 response = xhr.responseText } catch (e) { self._mode = 'text:vbarray' break } if (response.length > self._pos) { var newData = response.substr(self._pos) if (self._charset === 'x-user-defined') { var buffer = new Buffer(newData.length) for (var i = 0; i < newData.length; i++) buffer[i] = newData.charCodeAt(i) & 0xff self.push(buffer) } else { self.push(newData, self._charset) } self._pos = response.length } break case 'arraybuffer': if (xhr.readyState !== rStates.DONE || !xhr.response) break response = xhr.response self.push(new Buffer(new Uint8Array(response))) break case 'moz-chunked-arraybuffer': // take whole response = xhr.response if (xhr.readyState !== rStates.LOADING || !response) break self.push(new Buffer(new Uint8Array(response))) break case 'ms-stream': response = xhr.response if (xhr.readyState !== rStates.LOADING) break var reader = new global.MSStreamReader() reader.onprogress = function () { if (reader.result.byteLength > self._pos) { self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) self._pos = reader.result.byteLength } } reader.onload = function () { self.push(null) } // reader.onerror = ??? // TODO: this reader.readAsArrayBuffer(response) break } // The ms-stream case handles end separately in reader.onload() if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { self.push(null) } } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":31,"_process":14,"buffer":4,"inherits":10,"readable-stream":28}],34:[function(require,module,exports){ var Buffer = require('buffer').Buffer module.exports = function (buf) { // If the buffer is backed by a Uint8Array, a faster version will work if (buf instanceof Uint8Array) { // If the buffer isn't a subarray, return the underlying ArrayBuffer if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { return buf.buffer } else if (typeof buf.buffer.slice === 'function') { // Otherwise we need to get a proper copy return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) } } if (Buffer.isBuffer(buf)) { // This is the slow version that will work with any Buffer // implementation (even in old browsers) var arrayCopy = new Uint8Array(buf.length) var len = buf.length for (var i = 0; i < len; i++) { arrayCopy[i] = buf[i] } return arrayCopy.buffer } else { throw new Error('Argument must be a Buffer') } } },{"buffer":4}],35:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var punycode = require('punycode'); var util = require('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":36,"punycode":15,"querystring":18}],36:[function(require,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],37:[function(require,module,exports){ (function (global){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],38:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}]},{},[1])(1) });
/* * jQuery appear plugin * * Copyright (c) 2012 Andrey Sidorov * licensed under MIT license. * * https://github.com/morr/jquery.appear/ * * Version: 0.3.3 */ (function($) { var selectors = []; var check_binded = false; var check_lock = false; var defaults = { interval: 250, force_process: false } var $window = $(window); var $prior_appeared; function process() { check_lock = false; for (var index = 0; index < selectors.length; index++) { var $appeared = $(selectors[index]).filter(function() { return $(this).is(':appeared'); }); $appeared.trigger('appear', [$appeared]); if ($prior_appeared) { var $disappeared = $prior_appeared.not($appeared); $disappeared.trigger('disappear', [$disappeared]); } $prior_appeared = $appeared; } } // "appeared" custom filter $.expr[':']['appeared'] = function(element) { var $element = $(element); if (!$element.is(':visible')) { return false; } var window_left = $window.scrollLeft(); var window_top = $window.scrollTop(); var offset = $element.offset(); var left = offset.left; var top = offset.top; if (top + $element.height() >= window_top && top - ($element.data('appear-top-offset') || 0) <= window_top + $window.height() && left + $element.width() >= window_left && left - ($element.data('appear-left-offset') || 0) <= window_left + $window.width()) { return true; } else { return false; } } $.fn.extend({ // watching for element's appearance in browser viewport appear: function(options) { var opts = $.extend({}, defaults, options || {}); var selector = this.selector || this; if (!check_binded) { var on_check = function() { if (check_lock) { return; } check_lock = true; setTimeout(process, opts.interval); }; $(window).scroll(on_check).resize(on_check); check_binded = true; } if (opts.force_process) { setTimeout(process, opts.interval); } selectors.push(selector); return $(selector); } }); $.extend({ // force elements's appearance check force_appear: function() { if (check_binded) { process(); return true; }; return false; } }); })(jQuery);
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('mdl-layout-title', 'Integration | Component | mdl layout title', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{mdl-layout-title}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#mdl-layout-title}} template block text {{/mdl-layout-title}} `); assert.equal(this.$().text().trim(), 'template block text'); });
/**! * * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. */ 'use strict'; module.exports = require('sinon');
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat (MIT) */ /* Lithuanian (UTF-8) initialisation for the jQuery UI date picker plugin. */ /* @author Arturas Paleicikas <[email protected]> */ jQuery(function($){ $.datepicker.regional['lt'] = { closeText: 'Uždaryti', prevText: '&#x3C;Atgal', nextText: 'Pirmyn&#x3E;', currentText: 'Šiandien', monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis', 'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'], monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir', 'Lie','Rugp','Rugs','Spa','Lap','Gru'], dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'], dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'], dayNamesMin: ['Se','Pr','An','Tr','Ke','Pe','Še'], weekHeader: 'Wk', dateFormat: 'yy-mm-dd', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['lt']); }); /* @license-end */
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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. # coding: utf-8 """ Polyaxon SDKs and REST API specification. Polyaxon SDKs and REST API specification. # noqa: E501 The version of the OpenAPI document: 1.8.3 Contact: [email protected] Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from polyaxon_sdk.configuration import Configuration class V1OwnerSubEntityResourceRequestByUid(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'owner': 'str', 'entity': 'str', 'uuid': 'str' } attribute_map = { 'owner': 'owner', 'entity': 'entity', 'uuid': 'uuid' } def __init__(self, owner=None, entity=None, uuid=None, local_vars_configuration=None): # noqa: E501 """V1OwnerSubEntityResourceRequestByUid - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._owner = None self._entity = None self._uuid = None self.discriminator = None if owner is not None: self.owner = owner if entity is not None: self.entity = entity if uuid is not None: self.uuid = uuid @property def owner(self): """Gets the owner of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :return: The owner of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :rtype: str """ return self._owner @owner.setter def owner(self, owner): """Sets the owner of this V1OwnerSubEntityResourceRequestByUid. :param owner: The owner of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :type: str """ self._owner = owner @property def entity(self): """Gets the entity of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 Entity: project name, hub name, registry name, ... # noqa: E501 :return: The entity of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :rtype: str """ return self._entity @entity.setter def entity(self, entity): """Sets the entity of this V1OwnerSubEntityResourceRequestByUid. Entity: project name, hub name, registry name, ... # noqa: E501 :param entity: The entity of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :type: str """ self._entity = entity @property def uuid(self): """Gets the uuid of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :return: The uuid of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :rtype: str """ return self._uuid @uuid.setter def uuid(self, uuid): """Sets the uuid of this V1OwnerSubEntityResourceRequestByUid. :param uuid: The uuid of this V1OwnerSubEntityResourceRequestByUid. # noqa: E501 :type: str """ self._uuid = uuid def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1OwnerSubEntityResourceRequestByUid): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1OwnerSubEntityResourceRequestByUid): return True return self.to_dict() != other.to_dict()
from collections.abc import Mapping from struct import unpack, pack __all__ = ['IncorrectHeaderException', 'Field', 'FieldMap', 'FixedHeaderField', 'UInt8Field', 'Int16Field', 'Int32Field', 'Int64Field', 'UInt32Field', 'UInt64Field', 'FloatField', 'DoubleField', 'EnumField', 'BoolField', 'StringField', 'ByteStringField', 'ArrayField', 'ModelField', 'ConditionalField', 'ConditionalBlockStart', 'ConditionalBlockEnd'] class IncorrectHeaderException(IOError): pass class Field(object): __field_counter = 0 type_name = NotImplemented hidden = False store_value = write_value = True always_read = False def __init__(self): self.initialization_order = Field.__field_counter Field.__field_counter += 1 def read(self, input_stream, model): raise NotImplementedError def write(self, value, output_stream, model): raise NotImplementedError class FieldMap(Mapping): _dict = {} def __init__(self, dict): self._dict = dict def __getitem__(self, item): return self._dict.__getitem__(item) def __iter__(self): return self._dict.__iter__() def __len__(self): return len(self._dict) def __getattribute__(self, name): if name != '_dict' and name in self._dict: return self._dict[name] return super().__getattribute__(name) def __setattr__(self, name, value): if name != '_dict' and name in self._dict: raise AttributeError("can't set attribute") super().__setattr__(name, value) class FixedHeaderField(Field): type_name = 'header' def __init__(self, header, encoding='ISO 8859-1'): self.header = header self.encoding = encoding super().__init__() def read(self, input_stream, model): if input_stream.read(len(self.header)).decode(self.encoding) != self.header: raise IncorrectHeaderException return self.header def write(self, value, output_stream, model): output_stream.write(self.header.encode(self.encoding)) class FixedSizeNumberField(Field): size = None fmt = None def read(self, input_stream, model): return unpack(self.fmt, input_stream.read(self.size))[0] def write(self, value, output_stream, model): output_stream.write(pack(self.fmt, value)) class UInt8Field(FixedSizeNumberField): type_name = 'uint8' size = 1 fmt = '<B' class Int16Field(FixedSizeNumberField): type_name = 'int16' size = 2 fmt = '<h' class Int32Field(FixedSizeNumberField): type_name = 'int32' size = 4 fmt = '<l' class Int64Field(FixedSizeNumberField): type_name = 'int64' size = 8 fmt = '<q' class UInt32Field(FixedSizeNumberField): type_name = 'uint32' size = 4 fmt = '<L' class UInt64Field(FixedSizeNumberField): type_name = 'uint64' size = 8 fmt = '<Q' class FloatField(FixedSizeNumberField): type_name = 'float' size = 4 fmt = '<f' class DoubleField(FixedSizeNumberField): type_name = 'double' size = 8 fmt = '<d' class EnumField(Field): type_name = 'enum' enum_values = {} base_type = Int32Field def __init__(self): self.field = self.base_type() if isinstance(self.enum_values, dict): self.enum_values = self.enum_values elif isinstance(self.enum_values, (tuple, list)): self.enum_values = {i: v for i, v in enumerate(self.enum_values)} else: raise TypeError() super().__init__() def read(self, input_stream, model): return self.field.read(input_stream, model) def write(self, value, output_stream, model): self.field.write(value, output_stream, model) class BoolField(EnumField): enum_values = ('False', 'True') base_type = UInt8Field class StringField(Field): type_name = 'string' def __init__(self, encoding='utf-8'): self.encoding = encoding super().__init__() def read(self, input_stream, model): length = input_stream.read(1)[0] return input_stream.read(length).decode(self.encoding) def write(self, value, output_stream, model): value = value.encode(self.encoding) output_stream.write(pack('B', len(value)) + value) class ByteStringField(Field): type_name = 'bytestring' def __init__(self, format='HEX', length_field=Int32Field, length_func=None): self.format = format if isinstance(length_field, str): self.length_field = length_field elif isinstance(length_field, type): self.length_field = length_field() else: self.length_field = length_field self.length_func = length_func super().__init__() def read(self, input_stream, model): if isinstance(self.length_field, str): length = model.__getattribute__(self.length_field) if self.length_func is not None: length = self.length_func(length) else: length = self.length_field.read(input_stream, model) return input_stream.read(length) def write(self, value, output_stream, model): if isinstance(self.length_field, str): length = model.__getattribute__(self.length_field) if self.length_func is not None: length = self.length_func(length) if length != len(value): raise ValueError('Value length does not match one specified by {0}'.format(self.length_field)) else: length = len(value) self.length_field.write(length, output_stream, model) output_stream.write(value) class ArrayField(Field): type_name = 'array' def __init__(self, item_field, length_field=Int32Field, length_func=None, index_enum=None): self.item_field = item_field() if isinstance(item_field, type) else item_field if isinstance(length_field, str): self.length_field = length_field elif isinstance(length_field, type): self.length_field = length_field() else: self.length_field = length_field self.length_func = length_func self.index_enum = index_enum() if isinstance(index_enum, type) else index_enum super().__init__() def read(self, input_stream, model): if isinstance(self.length_field, str): length = model.__getattribute__(self.length_field) if self.length_func is not None: length = self.length_func(length) else: length = self.length_field.read(input_stream, model) return [self.item_field.read(input_stream, model) for i in range(length)] def write(self, value, output_stream, model): if isinstance(self.length_field, str): length = model.__getattribute__(self.length_field) if self.length_func is not None: length = self.length_func(length) if length != len(value): raise ValueError('Value length does not match one specified by {0}'.format(self.length_field)) else: length = len(value) self.length_field.write(length, output_stream, model) for item in value: self.item_field.write(item, output_stream, model) class ModelField(Field): type_name = 'struct' def __init__(self, model_class): self.model_class = model_class super().__init__() def read(self, input_stream, model): local_model = self.model_class() local_model.read(input_stream) return local_model def write(self, value, output_stream, model): if value: value.write(output_stream) class ConditionMixin(object): def _check_condition(self, model): if self.condition_func is None: return True args = [model.__getattribute__(field) for field in self.arg_fields] return self.condition_func(*args) class ConditionalField(Field, ConditionMixin): def __init__(self, field, arg_fields=[], condition_func=None): self.field = field() if isinstance(field, type) else field self.arg_fields = arg_fields if isinstance(arg_fields, (list, tuple)) else [arg_fields] self.condition_func = condition_func super().__init__() def read(self, input_stream, model): if self._check_condition(model): return self.field.read(input_stream, model) return None def write(self, value, output_stream, model): if self._check_condition(model): self.field.write(value, output_stream, model) class ConditionalBlockStart(Field, ConditionMixin): hidden = True store_value = write_value = False always_read = True def __init__(self, arg_fields=[], condition_func=None): self.arg_fields = arg_fields if isinstance(arg_fields, (list, tuple)) else [arg_fields] self.condition_func = condition_func super().__init__() def read(self, input_stream, model): return self._check_condition(model) def write(self, value, output_stream, model): pass class ConditionalBlockEnd(Field): hidden = True store_value = write_value = False always_read = True def read(self, input_stream, model): return None def write(self, value, output_stream, model): pass
import axios from 'axios'; import qs from 'qs'; import {Message} from '@alifd/next'; import {isPlainObject} from './nacosutil'; // import { SUCCESS_RESULT_CODE } from '../constants'; const API_GENERAL_ERROR_MESSAGE = 'Request error, please try again later!'; const request = () => { const instance = axios.create(); instance.interceptors.request.use( config => { const { url, params, data, method, headers } = config; if (!params) { config.params = {}; } if (!url.includes('auth/users/login')) { const { accessToken = '' } = JSON.parse(sessionStorage.token || '{}'); config.params.accessToken = accessToken; config.headers = Object.assign({}, headers, { accessToken }); } if (data && isPlainObject(data) && ['post', 'put'].includes(method)) { config.data = qs.stringify(data); if (!headers) { config.headers = {}; } config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; } return config; }, error => Promise.reject(error) ); instance.interceptors.response.use( response => { const { success, resultCode, resultMessage = API_GENERAL_ERROR_MESSAGE } = response.data; // if (!success && resultCode !== SUCCESS_RESULT_CODE) { // Message.error(resultMessage); // return Promise.reject(new Error(resultMessage)); // } return response.data; }, error => { if (error.response) { const { data = {}, status } = error.response; let message = `HTTP ERROR: ${status}`; if (typeof data === 'string') { message = data; } else if (typeof data === 'object') { message = data.message; } Message.error(message); if ( [401, 403].includes(status) && ['unknown user!', 'token invalid', 'token expired!'].includes(message) ) { sessionStorage.removeItem('token'); const [baseUrl] = location.href.split('#'); location.href = `${baseUrl}#/login`; } return Promise.reject(error.response); } Message.error(API_GENERAL_ERROR_MESSAGE); return Promise.reject(error); } ); return instance; }; export default request();
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/ // for more of what you can do here. const Sequelize = require('sequelize'); const DataTypes = Sequelize.DataTypes; module.exports = function (app) { const sequelizeClient = app.get('sequelizeClient'); const phones = sequelizeClient.define('phones', { number: { type: DataTypes.STRING, allowNull: false, unique: true }, country: { type: DataTypes.STRING, allowNull: true }, city: { type: DataTypes.STRING, allowNull: true }, state: { type: DataTypes.STRING, allowNull: true }, zip: { type: DataTypes.STRING, allowNull: true, }, SEEDFILE: { type: DataTypes.STRING, allowNull: true } }); // eslint-disable-next-line no-unused-vars phones.associate = function () { // Define associations here // See http://docs.sequelizejs.com/en/latest/docs/associations/ }; return phones; };
from output.models.ms_data.model_groups.mg_m008_xsd.mg_m008 import ( Doc, Foo, ) __all__ = [ "Doc", "Foo", ]
/// <reference types="cypress" /> context('Assertions', () => { beforeEach(() => { cy.visit('https://example.cypress.io/commands/assertions') }) describe('Implicit Assertions', () => { it('.should() - make an assertion about the current subject', () => { // https://on.cypress.io/should cy.get('.assertion-table') .find('tbody tr:last') .should('have.class', 'success') .find('td') .first() // checking the text of the <td> element in various ways .should('have.text', 'Column content') .should('contain', 'Column content') .should('have.html', 'Column content') // chai-jquery uses "is()" to check if element matches selector .should('match', 'td') // to match text content against a regular expression // first need to invoke jQuery method text() // and then match using regular expression .invoke('text') .should('match', /column content/i) // a better way to check element's text content against a regular expression // is to use "cy.contains" // https://on.cypress.io/contains cy.get('.assertion-table') .find('tbody tr:last') // finds first <td> element with text content matching regular expression .contains('td', /column content/i) .should('be.visible') // for more information about asserting element's text // see https://on.cypress.io/using-cypress-faq#How-do-I-get-an-element’s-text-contents }) it('.and() - chain multiple assertions together', () => { // https://on.cypress.io/and cy.get('.assertions-link') .should('have.class', 'active') .and('have.attr', 'href') .and('include', 'cypress.io') }) }) describe('Explicit Assertions', () => { // https://on.cypress.io/assertions it('expect - make an assertion about a specified subject', () => { // We can use Chai's BDD style assertions expect(true).to.be.true const o = { foo: 'bar' } expect(o).to.equal(o) expect(o).to.deep.equal({ foo: 'bar' }) // matching text using regular expression expect('FooBar').to.match(/bar$/i) }) it('pass your own callback function to should()', () => { // Pass a function to should that can have any number // of explicit assertions within it. // The ".should(cb)" function will be retried // automatically until it passes all your explicit assertions or times out. cy.get('.assertions-p') .find('p') .should(($p) => { // https://on.cypress.io/$ // return an array of texts from all of the p's // @ts-ignore TS6133 unused variable const texts = $p.map((i, el) => Cypress.$(el).text()) // jquery map returns jquery object // and .get() convert this to simple array const paragraphs = texts.get() // array should have length of 3 expect(paragraphs, 'has 3 paragraphs').to.have.length(3) // use second argument to expect(...) to provide clear // message with each assertion expect(paragraphs, 'has expected text in each paragraph').to.deep.eq([ 'Some text from first p', 'More text from second p', 'And even more text from third p', ]) }) }) it('finds element by class name regex', () => { cy.get('.docs-header') .find('div') // .should(cb) callback function will be retried .should(($div) => { expect($div).to.have.length(1) const className = $div[0].className expect(className).to.match(/heading-/) }) // .then(cb) callback is not retried, // it either passes or fails .then(($div) => { expect($div, 'text content').to.have.text('Introduction') }) }) it('can throw any error', () => { cy.get('.docs-header') .find('div') .should(($div) => { if ($div.length !== 1) { // you can throw your own errors throw new Error('Did not find 1 element') } const className = $div[0].className if (!className.match(/heading-/)) { throw new Error(`Could not find class "heading-" in ${className}`) } }) }) it('matches unknown text between two elements', () => { /** * Text from the first element. * @type {string} */ let text /** * Normalizes passed text, * useful before comparing text with spaces and different capitalization. * @param {string} s Text to normalize */ const normalizeText = (s) => s.replace(/\s/g, '').toLowerCase() cy.get('.two-elements') .find('.first') .then(($first) => { // save text from the first element text = normalizeText($first.text()) }) cy.get('.two-elements') .find('.second') .should(($div) => { // we can massage text before comparing const secondText = normalizeText($div.text()) expect(secondText, 'second text').to.equal(text) }) }) it('assert - assert shape of an object', () => { const person = { name: 'Joe', age: 20, } assert.isObject(person, 'value is object') }) it('retries the should callback until assertions pass', () => { cy.get('#random-number').should(($div) => { const n = parseFloat($div.text()) expect(n).to.be.gte(1).and.be.lte(10) }) }) }) })
// ==UserScript== // @name Mod Batch Comment Deleter // @description Batch delete comments using comment permalinks from SEDE https://data.stackexchange.com/stackoverflow/query/1131935 // @homepage https://github.com/samliew/personal-userscripts // @author @samliew // @version 2.0.2 // // @include https://*stackoverflow.com/admin/deleter // @include https://*serverfault.com/admin/deleter // @include https://*superuser.com/admin/deleter // @include https://*askubuntu.com/admin/deleter // @include https://*mathoverflow.net/admin/deleter // @include https://*.stackexchange.com/admin/deleter // ==/UserScript== (function() { 'use strict'; const fkey = StackExchange.options.user.fkey; const params = { itemsPerBatch: 1000, delayPerBatch: 5000, }; let content, button, preview, textarea; let isRunning = false; let failures = 0, retryCount = 0; function deleteOne(url, callback = null) { $.ajax({ url: url, method: 'POST', data: { fkey: fkey, sendCommentBackInMessage: false, }, dataType: 'json', }).done(function(response) { if(response.success == false) { failures++; } if(typeof callback == 'function') callback(); }).fail(function(jqXHR, textStatus, errorThrown) { failures++; }); } function bulkDeleteComments(commentIds) { return new Promise(function(resolve, reject) { if(typeof commentIds === 'undefined' || commentIds.length === 0) { reject(); return; } const datastring = 'commentIds%5B%5D=' + commentIds.join('&commentIds%5B%5D=') + '&action=delete&fkey=' + fkey; $.post(`https://${location.hostname}/admin/comment/bulk-comment-change`, datastring) .done(function(response) { if(response.includes('ok') === false) { failures++; } }).fail(function() { failures++; }); }); } let doDeleteAll = function() { const startTime = new Date(); let linkElems = preview.find('a').hide(); //let links = linkElems.get().map(el => { // if(!el.href.includes('/vote/10')) { return el.href + '/vote/10' } // return el.href; //}); let commentIds = linkElems.get().map(el => el.href.match(/\/(\d+)/)[1]); let total = typeof links !== 'undefined' ? links.length : commentIds.length; let currentNum = 0; linkElems.remove(); // Save memory? // Calculate and update progress function updateProgress() { const minsElapsed = (Date.now() - startTime) / 60000; const minsRemaining = (minsElapsed / currentNum) * (total - currentNum); document.title = `${currentNum.toLocaleString()}/${total.toLocaleString()} (${(currentNum/total*100).toFixed(1)}%)`; preview.text(document.title + `. ${Math.floor(minsElapsed)} mins elapsed, ${Math.round(minsRemaining)} mins remaining`); } // Callback function processNextBatch() { if(currentNum >= total) cleanup(); //links.slice(currentNum, currentNum + params.itemsPerBatch).forEach(v => { deleteOne(v); }); bulkDeleteComments( commentIds.slice(currentNum, currentNum + params.itemsPerBatch) ); currentNum += params.itemsPerBatch; if(currentNum > total) currentNum = total; } // After a batch of ajax calls complete $(document).unbind('ajaxStop').ajaxStop(function() { updateProgress(); // Some errors, wait and try up to 3 times if(failures > 1) { // Too many errors, stop if(retryCount >= 10) { cleanup(true); return; } // Reset and try last batch again in 2 minutes retryCount++; failures = 0; $('input[data-param-name="itemsPerBatch"]').val('20').trigger('change'); $('input[data-param-name="delayPerBatch"]').val('20').trigger('change'); currentNum -= params.itemsPerBatch; setTimeout(processNextBatch, 300000); } // Continue next batch after a delay else { setTimeout(processNextBatch, params.delayPerBatch); } }); // Begin isRunning = true; processNextBatch(); // Confirm when leaving page if batch script running $(window).on('beforeunload', function(evt) { return isRunning && confirm('Are you sure you wish to leave this page?'); }); // Stop everything and exit function cleanup(hasError = false) { isRunning = false; $(document).unbind('ajaxStop'); $(window).off('beforeunload'); button.remove(); const endTime = new Date(); preview.text(hasError ? `Receiving response errors. Check if you are rate-limited or these items are already deleted. Stopped at ${currentNum - params.itemsPerBatch} items.` : `Completed ${total} items in ${Math.round((endTime - startTime) / 60000)} minutes!` ); document.title = hasError ? 'Error!' : 'Completed!'; } // for safety, doDeleteAll can be called once only doDeleteAll = function() {}; } function parseInputUpdatePreview(evt) { // Do nothing and wait for another event if(this.value.trim() == '') { console.log('input empty!'); $(this).one('change keyup', parseInputUpdatePreview); return false; } $(this).hide(); // HTML pasted from SEDE if(this.value.includes('grid-canvas')) { preview.html(this.value); } // Links pasted from CSV else { preview.html(`<a href="//${location.hostname}/` + this.value.replace(/[\s\n\r]+/g, ' ').trim().split(/\s?site:\/\//).join(`" target="_blank">link</a> <a href="//${location.hostname}/`) + `" target="_blank">link</a>`); preview.children().first().remove(); } // Show delete all button button.insertBefore(preview).text('Delete ALL ' + preview.find('a').length.toLocaleString()); } function doPageload() { document.title = "Batch Comment Deleter - " + StackExchange.options.site.name; // Init UI content = $('#content').empty().prepend(` <div id="mainbar-full"> <div class="grid ai-center jc-space-between mb12 bb bc-black-3 pb12"> <div class="fs-body3 grid--cell fl1 mr12">Batch Comment Deleter</div> </div> <div class="deleter-info">items per batch: <input type="number" min="1" max="100" class="inline" data-param-name="itemsPerBatch" value="${params.itemsPerBatch}" />; secs delay between batches: <input type="number" min="0" max="60" class="inline" data-param-name="delayPerBatch" data-multiplier="1000" value="${params.delayPerBatch/1000}" /></div> </div> `); button = $(`<button>Delete ALL</button>`).on('click', function() { $(this).prop('disabled', true).text('processing...'); doDeleteAll(); }); preview = $(`<div class="html-preview">Use this <a href="https://data.stackexchange.com/stackoverflow/query/1131935" target="_blank">SEDE query</a> to find comments to delete. Download results and paste the comment permalinks column below.</div>`).appendTo(content); textarea = $('<textarea placeholder="paste comment permalinks from exported query" class="html-editor"></textarea>').appendTo(content).one('change keyup', parseInputUpdatePreview); // Events to update params content.on('change', 'input[data-param-name]', function(evt) { const paramName = this.dataset.paramName; const num = Number(this.value) * (Number(this.dataset.multiplier) || 1); const isNum = !isNaN(num); if(this.value != '') params[paramName] = isNum ? num : this.value; //console.log('params updated:', params); }); } function appendStyles() { $(` <style> .slick-header.ui-state-default,.slick-headerrow.ui-state-default { width: 100%; overflow: hidden; border-left: 0; } .slick-header-columns,.slick-headerrow-columns { position: relative; white-space: nowrap; cursor: default; overflow: hidden; } .slick-header-column.ui-state-default { position: relative; display: inline-block; overflow: hidden; -o-text-overflow: ellipsis; text-overflow: ellipsis; height: 16px; line-height: 16px; margin: 0; padding: 4px; border-right: 1px solid var(--silver); border-left: 0; border-top: 0; border-bottom: 0; float: left; } .slick-headerrow-column.ui-state-default { padding: 4px } .slick-header-column-sorted { font-style: italic; } .slick-sort-indicator { display: inline-block; width: 8px; height: 5px; margin-left: 4px; margin-top: 6px; } .slick-sort-indicator-desc { background: url(/Content/slickgrid/images/sort-desc.gif); } .slick-sort-indicator-asc { background: url(/Content/slickgrid/images/sort-asc.gif); } .slick-resizable-handle { position: absolute; font-size: .1px; display: block; cursor: col-resize; width: 4px; right: 0; top: 0; height: 100%; } .slick-sortable-placeholder { background: var(--silver); } .grid-canvas { position: relative; outline: 0; } .slick-row.ui-widget-content,.slick-row.ui-state-active { position: absolute; border: 0; width: 100%; } .slick-cell,.slick-headerrow-column { position: absolute; border: 1px solid transparent; border-right: 1px dotted var(--silver); border-bottom-color: var(--silver); overflow: hidden; -o-text-overflow: ellipsis; text-overflow: ellipsis; vertical-align: middle; z-index: 1; padding: 1px 2px 2px 1px; margin: 0; white-space: nowrap; cursor: default; } .slick-group { } .slick-group-toggle { display: inline-block; } .slick-cell.highlighted { background: #87cefa; background: rgba(0,0,255,.2); -webkit-transition: all .5s; -moz-transition: all .5s; -o-transition: all .5s; transition: all .5s; } .slick-cell.flashing { border: 1px solid var(--red-500) !important; } .slick-cell.editable { z-index: 11; overflow: visible; background: var(--white); border-color: var(--black); border-style: solid; } .slick-cell:focus { outline: none; } .slick-reorder-proxy { display: inline-block; background: var(--blue-500); opacity: .15; filter: alpha(opacity=15); cursor: move; } .slick-reorder-guide { display: inline-block; height: 2px; background: var(--blue-500); opacity: .7; filter: alpha(opacity=70); } .slick-selection { z-index: 10; position: absolute; border: 2px dashed #000; } .tab-counter { color: #b0b0b0; display: none; margin-left: 4px; } .youarehere .tab-counter:hover { color: var(--blue-400); } #resultSets { position: relative; } #resultSets .subpanel { cursor: default; display: none; min-height: 500px; } .slick-header .slick-header-column { background-color: var(--black-025); color: var(--black-500); border-bottom: 1px dotted var(--black-150); display: block; font-weight: bold; padding: 6px 8px 5px 8px; text-align: center; } .slick-header .slick-header-column-sorted { color: var(--blue-500); font-style: normal; } .slick-sort-indicator { background-image: url(/Content/slickgrid/images/sort-asc-inactive.gif); background-repeat: no-repeat; height: 7px; } .slick-sort-indicator.slick-sort-indicator-asc { background-image: url(/Content/slickgrid/images/sort-asc.gif); } .slick-sort-indicator.slick-sort-indicator-desc { background-image: url(/Content/slickgrid/images/sort-desc.gif); } .slick-row.odd { background-color: var(--black-025); } .slick-cell { padding: 6px 8px 5px 8px; border-bottom: 1px dotted var(--black-150); border-right: 1px dotted var(--black-150); } .slick-cell.number { text-align: right; } .grid-canvas { display: table; position: relative !important; width: auto !important; height: auto !important; } .slick-row { display: table-row; position: relative !important; } .slick-cell, .slick-header-column { display: table-cell; position: relative !important; max-width: 450px; width: auto !important; height: auto !important; } .slick-header-columns { display: table; position: relative !important; left: 0 !important; top: 0; width: auto !important; } #mainbar-full + button { margin-top: 20px; } .html-editor { width: 100%; height: 150px; margin: 20px auto; } .html-preview { margin: 20px auto; } input.inline { width: 100px; padding: 4px 7px !important; border: none !important; border-bottom: 1px dotted var(--black-700) !important; } </style> `).appendTo(document.body); } // On page load appendStyles(); doPageload(); })();
import React from 'react' import styles from './layout.module.scss' import Header from './header.js' import Footer from './footer.js' export default ({ children }) => ( <div className={styles.container}> <Header /> <div className={styles.content}> {children} </div> <Footer> My new Gatsby Blog 2019 </Footer> </div> )
const gulp = require('gulp'); const babel = require('gulp-babel'); const uglify = require('gulp-uglify'); gulp.task('default', () => { return gulp.src('src/nanomsg.js') .pipe(babel({ presets: ['@babel/env'] })) .pipe(uglify()) .pipe(gulp.dest('dist/')); });
# https://leetcode.com/problems/validate-binary-search-tree/ import sys # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.utilValid(root, -sys.maxsize-1, sys.maxsize) def utilValid(self,root, min, max): #base case if root == None: #print("T") return True #print(min,max,root.val) if root.val>min and root.val<max: return self.utilValid(root.left,min,root.val) and self.utilValid(root.right,root.val,max) #print("F", root.val) else: return False
var nijs = require('nijs'); exports.pkg = function(args) { return new nijs.NixAssert({ conditionExpr: true, body: new nijs.NixLet({ value: { test: true }, body: args.writeTextFile({ name : "conditionals", text : new nijs.NixIf({ ifExpr: new nijs.NixExpression("test"), thenExpr: "It is true!", elseExpr: "It is false!" }) }) }) }); };
'use strict'; describe('Controller: FormsWizardCtrl', function () { // load the controller's module beforeEach(module('minovateApp')); var FormsWizardCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); FormsWizardCtrl = $controller('FormsWizardCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
var webpack = require('webpack'); var config = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/app', filename: 'bundle.js' }, plugins: [ new webpack.DefinePlugin({ ON_TEST: process.env.NODE_ENV === 'test' }) ], module: { loaders: [ {test: /\.js$/, loader: 'ng-annotate!babel', exclude: /node_modules/}, {test: /\.html$/, loader: 'raw', exclude: /node_modules/}, {test: /\.css$/, loader: 'style!css', exclude: /node_modules/}, {test: /\.styl$/, loader: 'style!css!stylus', exclude: /node_modules/} ] } }; if (process.env.NODE_ENV === 'production') { config.output.path = __dirname + '/dist'; config.plugins.push(new webpack.optimize.UglifyJsPlugin()); config.devtool = 'source-map'; } module.exports = config;
""" (c) ΔQ Programming LLP, 2021 This program is free software; you may redistribute and/or modify it under the terms of the Apache License v2.0. """ import os import pathlib from django.core.management.base import BaseCommand import csv from thoth.models import Thema class Command(BaseCommand): """ A management command that installs Thema code support """ help = "Installs Thema code functionality into Thoth components" def handle(self, *args, **options): script_dir = pathlib.Path(__file__).parent.parent.parent.resolve() path = os.path.join(script_dir, 'fixtures', 'thema.csv') if not os.path.isfile(path): print('Please place thema.csv, converted from ' 'https://www.editeur.org/151/Thema/, ' 'in the thoth/fixtures directory.') return with open(path, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: thema_model = Thema.objects.get_or_create( code=row['Code'], heading=row['English Heading'])[0] thema_model.save() print("Thema fixtures installed. At next Thoth sync, subject codes " "will be linked to THEMA entries.")
import React from 'react'; import styles from './styles.less'; const ScopedAnimations = () => ( <div className={styles.root}> <div className={styles.ball} /> </div> ); export default ScopedAnimations;
import React from 'react'; import moment from 'moment'; import {compose} from '@truefit/bach'; import {withSelector} from '@truefit/bach-redux'; import Typography from '@material-ui/core/Typography'; import Divider from './sessionModalDivider'; import { roomForSessionSelector, speakersForSessionSelector, tagsForSessionSelector, } from '../selectors'; const SessionDetail = ({speakers, room, tags, session}) => ( <div> <Typography variant="subtitle2"> <span className="bold">Room: </span> {room.name} </Typography> <Typography variant="subtitle2"> <span className="bold">Speaker{speakers.length === 1 ? '' : 's'}: </span> {speakers.map(s => s.name).join(', ')} </Typography> <Typography variant="subtitle2"> <span className="bold">Tags: </span> {tags.map(c => c.name).join(', ')} </Typography> <Typography variant="subtitle2"> <span className="bold">{(moment() - moment(session.startTime) >= 0) ? 'Started' : 'Starts'}: </span> {moment(session.startTime).format('LT')} ({moment(session.startTime).fromNow()}) </Typography> <Typography variant="subtitle2"> <span className="bold">{(moment() - moment(session.endTime) >= 0) ? 'Ended' : 'Ends'}: </span> {moment(session.endTime).format('LT')} ({moment(session.endTime).fromNow()}) </Typography> <Divider /> <Typography component="p" variant="body2" dangerouslySetInnerHTML={{__html: session.description}} /> </div> ); export default compose( withSelector('room', roomForSessionSelector), withSelector('speakers', speakersForSessionSelector), withSelector('tags', tagsForSessionSelector), )(SessionDetail);
""" Simple event server for Tuesday's THW This is simplistic event bus setup for doing serverside notebook answer checks for Tuesday's The Hacker Within Python Olympics. """ import os import json import time import uuid from flask import Flask, request from flask_cors import CORS from pymongo import MongoClient app = Flask(__name__) # Insecure! Let's not do this forever :D cors = CORS(app) BASE_PATH = os.path.abspath('.') event_handlers = {} client = MongoClient('localhost', 27017, connect=False) def handle_event(event_type): def decorated_f(f): event_handlers[event_type] = f return f return decorated_f @handle_event('notebook_opened') def notebook_started(event): event_payload = event['payload'] query = { 'username': event_payload['username'], 'notebook_key': event_payload['notebook_key'] } if not client.thw.notebook_starts.find_one(query): # First time notebook opening! data = query.copy() data['started_at'] = event['timestamp'] data['event'] = event client.thw.notebook_starts.insert_one(data) @handle_event('correct_answer') def correct_answer(event): event_payload = event['payload']['original']['payload'] notebook_query = { 'username': event_payload['username'], 'notebook_key': event_payload['notebook_key'] } notebook_started = client.thw.notebook_starts.find_one(notebook_query) answer_query = { 'username': event_payload['username'], 'notebook_key': event_payload['notebook_key'], 'answer_key': event_payload['answer_key'], } if not client.thw.answers.find_one(answer_query): data = answer_query.copy() data.update({ 'event': event, 'time_from_start': event['timestamp'] - notebook_started['started_at'] }) client.thw.answers.insert_one(data) @handle_event('cell_execute') def execute_test(event): event_payload = event['payload'] if not all([key in event_payload for key in ['username', 'notebook_key', 'answer_key', 'code', 'output']]): return {'status': 'not-ok'} file_path = os.path.abspath(os.path.join(BASE_PATH, event_payload['notebook_key'], event_payload['answer_key'])) if not file_path.startswith(BASE_PATH): # Directory traversal attack! # FIXME: Make these statuses actually understandable! return {'status': 'invalid-keys'} if os.path.exists(file_path): with open(file_path) as f: answer = f.read().strip() if answer == event_payload['output'].strip(): # Don't return this - only return correct # FIXME: wtf do we do with this? In process event listeners ugh dispatch_event(make_event('correct_answer', {'original': event})) return {'status': 'correct'} return {'status': 'incorrect'} def write_event(event): """ Writes the event out to a file, as atomically as possible. """ print(repr(event)) # OMG, pymongo modifies the data you pass it! WTF PYMONGO # Shallow copy is ok, since pymongo doesn't reach into objects and change # them client.thw.events.insert_one(event.copy()) def make_event(event_type, event_payload): return { "timestamp": time.time(), "type": event_type, "payload": event_payload, "id": str(uuid.uuid4()) } def dispatch_event(event): event_type = event['type'] write_event(event) if event_type in event_handlers: return event_handlers[event_type](event) return {} @app.route('/receive/<string:event_type>', methods=['POST']) def receive(event_type): event_payload = request.get_json(force=True) event = make_event(event_type, event_payload) ret = { 'response': dispatch_event(event), 'event': event } print(repr(ret)) return json.dumps(ret) @app.route('/board/<string:notebook_key>') def show_board(notebook_key): answers = client.thw.answers.find({'notebook_key': notebook_key}) board = {} for answer in answers: user = board.get(answer['username'], {}) user[answer['answer_key']] = answer['time_from_start'] board[answer['username']] = user return json.dumps(board) if __name__ == '__main__': app.run(debug=True)
const cp = require('child_process'); const fs = require('fs'); const path = require('path'); const BASE = path.resolve(__dirname, '../..'); const NAN_DIR = path.resolve(BASE, 'third_party', 'nan'); const NPX_CMD = process.platform === 'win32' ? 'npx.cmd' : 'npx'; const utils = require('./lib/utils'); const { YARN_VERSION } = require('./yarn'); if (!process.mainModule) { throw new Error('Must call the nan spec runner directly'); } async function main () { const nodeDir = path.resolve(BASE, `out/${utils.OUT_DIR}/gen/node_headers`); const env = Object.assign({}, process.env, { npm_config_nodedir: nodeDir, npm_config_msvs_version: '2017', npm_config_arch: process.env.NPM_CONFIG_ARCH }); const { status: buildStatus } = cp.spawnSync(NPX_CMD, ['node-gyp', 'rebuild', '--directory', 'test'], { env, cwd: NAN_DIR, stdio: 'inherit' }); if (buildStatus !== 0) { console.error('Failed to build nan test modules'); return process.exit(buildStatus); } const { status: installStatus } = cp.spawnSync(NPX_CMD, [`yarn@${YARN_VERSION}`, 'install'], { env, cwd: NAN_DIR, stdio: 'inherit' }); if (installStatus !== 0) { console.error('Failed to install nan node_modules'); return process.exit(installStatus); } const DISABLED_TESTS = ['nannew-test.js']; const testsToRun = fs.readdirSync(path.resolve(NAN_DIR, 'test', 'js')) .filter(test => !DISABLED_TESTS.includes(test)) .map(test => `test/js/${test}`); const testChild = cp.spawn(utils.getAbsoluteElectronExec(), ['node_modules/.bin/tap', ...testsToRun], { env: { ...process.env, ELECTRON_RUN_AS_NODE: 'true' }, cwd: NAN_DIR, stdio: 'inherit' }); testChild.on('exit', (testCode) => { process.exit(testCode); }); } main().catch((err) => { console.error('An unhandled error occurred in the nan spec runner', err); process.exit(1); });
# -*- encoding: utf-8 -*- """ @Author : zYx.Tom @Contact : [email protected] @site : https://github.com/zhuyuanxiang/tensorflow_cookbook --------------------------- @Software : PyCharm @Project : TensorFlow_Machine_Learning_Cookbook @File : C0404_svm_kernels.py @Version : v0.1 @Time : 2019-11-01 16:38 @License : (C)Copyright 2018-2019, zYx.Tom @Reference : 《TensorFlow机器学习实战指南,Nick McClure》, Sec0404,P77 @Desc : 基于 TensorFlow 的线性回归,使用 TensorFlow 实现 基于核函数的支持向量机 """ # common imports import os import sys import matplotlib.pyplot as plt import numpy as np # pip install numpy<1.17,小于1.17就不会报错 import sklearn import tensorflow as tf import winsound from tensorflow.python.framework import ops # 设置数据显示的精确度为小数点后3位 np.set_printoptions(precision = 8, suppress = True, threshold = np.inf, linewidth = 200) # 利用随机种子,保证随机数据的稳定性,使得每次随机测试的结果一样 seed = 42 np.random.seed(seed) tf.set_random_seed(seed) # 初始化默认的计算图 ops.reset_default_graph() # Python ≥3.5 is required assert sys.version_info >= (3, 5) # Scikit-Learn ≥0.20 is required assert sklearn.__version__ >= "0.20" # 屏蔽警告:Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Open graph session sess = tf.Session() # 从这一节开始,主要难点在于高斯核函数推导过程的实现。 # 书中没有详细介绍核函数算法的公式 # 书中的公式与代码中的实现无法匹配 # 虽然代码正确运行,但是没有推导无法真正理解原理,也就很正确推广 # 4.5 对非线性核的实现也存在同样的问题 # 4.6 对多类别分类的实现也存在同样的问题 # Generate non-linear data # 数据量和批量数据个数会影响最终判断的效果 # 如果数据量与批量数据个数相等,那么不在聚焦区内的数据默认使用外面那个圈的值(-1) # 如果数据量大于批量数据个数,那么不在聚焦区内的数据默认使用里面那个圈的值(1) (x_vals, y_vals) = sklearn.datasets.make_circles(n_samples = 350, factor = .5, noise = .1) y_vals = np.array([1 if y == 1 else -1 for y in y_vals]) class1_x = [x[0] for i, x in enumerate(x_vals) if y_vals[i] == 1] class1_y = [x[1] for i, x in enumerate(x_vals) if y_vals[i] == 1] class2_x = [x[0] for i, x in enumerate(x_vals) if y_vals[i] == -1] class2_y = [x[1] for i, x in enumerate(x_vals) if y_vals[i] == -1] # Declare batch size batch_size = 50 learning_rate = 0.002 iterations = 1500 # Initialize placeholders # [None,2]表示需要提供n个2维数据,即n*2维数据 x_data = tf.placeholder(shape = [None, 2], dtype = tf.float32) y_target = tf.placeholder(shape = [None, 1], dtype = tf.float32) prediction_grid = tf.placeholder(shape = [None, 2], dtype = tf.float32) # Create variables for svm b = tf.Variable(tf.random_normal(shape = [1, batch_size])) # Apply kernel # 线性核没有高斯核的精度好。 # Gaussian (RBF) kernel # ToDo: 没有具体的公式,不明白计算的原理。 gamma = tf.constant(-50.0) # dist是列向量,先将x_data每个元素求平方,然后把所有结果相加,再全部转换为n个一维数据 dist = tf.reshape(tf.reduce_sum(tf.square(x_data), 1), [-1, 1]) data_dist = 2. * (x_data @ tf.transpose(x_data)) # data_dist是矩阵,一个批次的训练数据*一个批次的训练数据的转置, sq_dists = dist - data_dist + tf.transpose(dist) # sq_dists被处理成矩阵对角线全部为0 my_kernel = tf.exp(gamma * tf.abs(sq_dists)) # exp{-gamma*||x-y||^2} # Linear Kernel # my_kernel = tf.matmul(x_data, tf.transpose(x_data)) # Compute SVM model model_output = b @ my_kernel first_term = tf.reduce_sum(b) b_vec_cross = tf.transpose(b) @ b y_target_cross = y_target @ tf.transpose(y_target) second_term = tf.reduce_sum((my_kernel * (b_vec_cross * y_target_cross))) loss = tf.negative(first_term - second_term) # Create Prediction Kernel # Gaussian(RBF) prediction kernel rA = tf.reshape(tf.reduce_sum(tf.square(x_data), 1), [-1, 1]) rB = tf.reshape(tf.reduce_sum(tf.square(prediction_grid), 1), [-1, 1]) pred_dist = tf.multiply(2., tf.matmul(x_data, tf.transpose(prediction_grid))) pred_sq_dist = tf.add(tf.subtract(rA, pred_dist), tf.transpose(rB)) pred_kernel = tf.exp(tf.multiply(gamma, tf.abs(pred_sq_dist))) # Linear Prediction Kernel # my_kernel = tf.matmul(x_data, tf.transpose(prediction_grid)) prediction_output = (tf.transpose(y_target) * b) @ pred_kernel prediction = tf.sign(prediction_output - tf.reduce_mean(prediction_output)) accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.squeeze(prediction), tf.squeeze(y_target)), tf.float32)) # Declare optimizer my_opt = tf.train.GradientDescentOptimizer(learning_rate) train_step = my_opt.minimize(loss) # Initialize variables init = tf.global_variables_initializer() sess.run(init) # Training loop loss_vec = [] batch_accuracy = [] rand_x = [] rand_y = [] for i in range(iterations): rand_index = np.random.choice(len(x_vals), size = batch_size) rand_x = x_vals[rand_index] rand_y = np.transpose([y_vals[rand_index]]) sess.run(train_step, feed_dict = {x_data: rand_x, y_target: rand_y}) temp_loss = sess.run(loss, feed_dict = {x_data: rand_x, y_target: rand_y}) loss_vec.append(temp_loss) temp_acc = sess.run(accuracy, feed_dict = { x_data: rand_x, y_target: rand_y, prediction_grid: rand_x }) batch_accuracy.append(temp_acc) if (i + 1) % 250 == 0: print("Step #", i + 1) print("Loss = ", temp_loss) print("Accuracy = ", temp_acc) pass pass # Create a mesh to plot points in x_min, x_max = x_vals[:, 0].min() - 1, x_vals[:, 0].max() + 1 y_min, y_max = x_vals[:, 1].min() - 1, x_vals[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) # Translates slice objects to concatenation along the second axis. # 将所有数据都转换到矩阵的第二维中。数值默认为一个2维的矩阵数据 # np.c_[np.array([[[1,2,3]]]), 0, 0, np.array([[4,5,6]])] --> [[1,2,3,0,0,4,5,6] # 将所有同维的矩阵合并到同维的一个矩阵中。 # np.c_[np.array([[[1,2,3]]]), np.array([[[4,5,6]]])] --> [[[1,2,3,4,5,6]]] grid_points = np.c_[xx.ravel(), yy.ravel()] grid_predictions = sess.run( prediction, feed_dict = { x_data: rand_x, y_target: rand_y, prediction_grid: grid_points }).reshape(xx.shape) # Plot points and grid plt.figure() plt.contourf(xx, yy, grid_predictions, cmap = plt.cm.Paired, alpha = 0.8) plt.plot(class1_x, class1_y, 'ro', label = "Class 1") plt.plot(class2_x, class2_y, 'bx', label = "Class -1") plt.title("图4-8:使用非线性的高斯核函数 SVM 在非线性可分的数据集上进行分割") plt.xlabel('x') plt.ylabel('y') plt.legend(loc = "lower right") plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) # Plot batch accuracy plt.figure() plt.plot(batch_accuracy, 'b-', label = 'Accuracy') plt.title("批处理的精确度") plt.xlabel("迭代次数") plt.ylabel("精确度") plt.legend(loc = "lower right") # Plot loss over time plt.figure() plt.plot(loss_vec, 'b-') plt.title("每次迭代的损失代价") plt.xlabel("迭代次数") plt.ylabel("损失代价") # Evaluate on new/unseen data points # New data points: new_points = np.array( [[0.1751517, - 0.2138658], [0.1951517, - 0.2138658], [0.2151517, - 0.2138658], [0.2351517, - 0.2138658], [0.2551517, - 0.2138658], [0.2751517, - 0.2138658], [0.2951517, - 0.2138658], [0.3151517, - 0.2138658], [0.3351517, - 0.2138658], [0.3551517, - 0.2138658], [0.3751517, - 0.2138658], [0.3951517, - 0.2138658], [0.4151517, - 0.2138658], [0.4351517, - 0.2138658], [0.4551517, - 0.2138658], ]) # new_points = np.array([(-0.75, -0.75), (-0.5, -0.5), (-0.25, -0.25), (0.25, 0.25), (0.5, 0.5), (0.75, 0.75)]) [evaluations] = sess.run(prediction, feed_dict = { x_data: rand_x, y_target: rand_y, prediction_grid: new_points }) for ix, p in enumerate(new_points): print('{} : class = {}'.format(p, evaluations[ix])) pass # ----------------------------------------------------------------- # 运行结束的提醒 winsound.Beep(600, 500) if len(plt.get_fignums()) != 0: plt.show() pass
// (function () { // 'use strict' // // Fetch all the forms we want to apply custom Bootstrap validation styles to // var forms = document.querySelectorAll('.needs-validation') // // Loop over them and prevent submission // Array.prototype.slice.call(forms) // .forEach(function (form) { // form.addEventListener('submit', function (event) { // if (!form.checkValidity()) { // event.preventDefault() // event.stopPropagation() // } // form.classList.add('was-validated') // if (form.checkValidity()) { // } // }, ) // }) // forms.submit() // })()
import glob import pkg_resources import subprocess import sys import pathlib import pkg_resources import json def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) req = glob.glob("/project/**/requirements.txt", recursive=True) install("pipenv") install("pip-licenses") #add preinstalled packages to ignore list with subprocess.Popen([sys.executable, "-m", "pipenv", "run", "pip-licenses", "--format=json-license-finder"], stdout=subprocess.PIPE) as proc: preinstalled = json.loads(proc.stdout.read()) ignore=[i['name'] for i in preinstalled] for r in req: print("Processing {}".format(r)) with pathlib.Path(r).open() as requirements_txt: install_requires = [str(requirement) for requirement in pkg_resources.parse_requirements(requirements_txt)] subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", r]) subprocess.check_call([sys.executable, "-m", "pipenv", "run", "pip-licenses", "--order=license", "--format=csv", "--output-file=/project/licenses.csv", "--ignore-packages"] + ignore)
// import {login, logout, getInfo} from '@/api/user' import {getUserInfo, login} from '@/api/user' import {getToken, setToken, removeToken, getUser, setUser, removeUser} from '@/utils/auth' import {Encrypt} from '@/utils/crypto' // import { resetRouter } from '@/router' const getDefaultState = () => { const user = JSON.parse(getUser()); if (user != null) { return { token: getToken(), name: user.userName, avatar: user.userPicPath, uid: user.userId, ulv: user.userLevel, ulvprogress: user.userLevelProgress } } else { return { token: '', name: '', avatar: '', uid: '', ulv: '', ulvprogress: '' } } } const state = getDefaultState() const mutations = { RESET_STATE: (state) => { Object.assign(state, getDefaultState()) }, SET_TOKEN: (state, token) => { state.token = token }, SET_NAME: (state, name) => { state.name = name }, SET_ULV: (state, ulv) => { state.ulv = ulv }, SET_ULVPROGRESS: (state, ulvprogress) => { state.ulvprogress = ulvprogress }, SET_UID: (state, uid) => { state.uid = uid }, SET_AVATAR: (state, avatar) => { state.avatar = avatar } } const actions = { // user login login({commit}, userInfo) { const {userAccount, password} = userInfo return new Promise((resolve, reject) => { window.console.log(userAccount, Encrypt(password)) login({"userAccount": userAccount, "password": Encrypt(password)}).then(response => { window.console.log(response); if (response.code === 0) { const {data} = response; commit('SET_TOKEN', data.token); commit('SET_ULV', data.user.userLevel); commit('SET_ULVPROGRESS', data.user.userLevelProgress); commit('SET_UID', data.user.userId); commit('SET_NAME', data.user.userName); commit('SET_AVATAR', data.user.userPicPath) setToken(data.token) setUser(data.user) } resolve(response.code) }).catch(error => { reject(error) }) }) }, // get user info getInfo({commit, state}) { return new Promise((resolve, reject) => { getUserInfo({userId: state.uid}).then(response => { window.console.log(response) const {user} = response.data if (!user) { reject('Verification failed, please Login again.') } commit('SET_ULV', user.userLevel); commit('SET_ULVPROGRESS', user.userLevelProgress); commit('SET_UID', user.userId); commit('SET_NAME', user.userName); commit('SET_AVATAR', user.userPicPath) setUser(user) resolve(user) }).catch(error => { reject(error) }) }) }, // user logout // eslint-disable-next-line no-unused-vars logout({commit, state}) { return new Promise((resolve, reject) => { // logout(state.token).then(() => { // removeToken() // must remove token first // // resetRouter() // commit('RESET_STATE') // resolve(0) // }).catch(error => { // reject(error) // }) try { removeToken(); // must remove token first removeUser(); // resetRouter() commit('RESET_STATE') resolve(0) } catch (error) { reject(error) } }) }, // remove token resetToken({commit}) { return new Promise(resolve => { removeToken() // must remove token first removeUser() commit('RESET_STATE') resolve() }) } } export default { namespaced: true, state, mutations, actions }
from agent.strategy.base_strategy import BaseStrategy import numpy as np class EpsilonGreedyStrategy(BaseStrategy): def __init__(self, start, end, decay): super().__init__(start, end, decay) def select_action(self, aq_pairs): threshold = self.get_decayed_rate() try: if (threshold == 0) or (np.random.random() > threshold): # Get action corresponding to maximum q action = aq_pairs[np.argmax(aq_pairs[:, 1])][0] else: action = np.random.choice(aq_pairs[:, 0]) except: raise ValueError(f"{aq_pairs} not valid action/q-value array") self.current_step += 1 return int(action)
function exportHandlerMagstrat(event) { var charts = new Array( $("#magstrat-container-declination").highcharts(), $("#magstrat-container-binary").highcharts(), $("#magstrat-container-inclination").highcharts() ); if(charts.includes(undefined)) { return notify("danger", "Can not export charts that are not rendered."); } exportChartsWrapper("magstrat", charts, event.target.id); } function exportHandlerPredicted(event) { var charts = new Array( $("#declination-container").highcharts(), $("#inclination-container").highcharts(), $("#paleolatitude-container").highcharts() ); if(charts.includes(undefined)) { return notify("danger", "Can not export charts that are not rendered."); } exportChartsWrapper("predicted", charts, event.target.id); } document.getElementById("export-predicted-png").addEventListener("click", exportHandlerPredicted); document.getElementById("export-predicted-pdf").addEventListener("click", exportHandlerPredicted); document.getElementById("export-predicted-svg").addEventListener("click", exportHandlerPredicted); document.getElementById("export-magstrat-png").addEventListener("click", exportHandlerMagstrat); document.getElementById("export-magstrat-pdf").addEventListener("click", exportHandlerMagstrat); document.getElementById("export-magstrat-svg").addEventListener("click", exportHandlerMagstrat);
/* eslint-env browser */ import Url from 'url'; import _ from 'lodash'; import {CLOSE_REPLACED} from '../base-client'; import {log} from '../util'; export default superclass => class BrowserMixin extends superclass { _connect() { if (this._closed) { return; } this._disconnect(CLOSE_REPLACED); const url = this._formatUrl(); const socket = new WebSocket(url); log(`[${this.id}] created anew`); socket.onopen = () => { this._onconnect(socket); }; socket.onerror = () => { this._onerror(new Error('handshake failed')); }; } _formatUrl() { const {hostname, port, pathname, query} = Url.parse(this.url, true); const urlObject = { protocol: location.protocol === 'https:' ? 'wss' : 'ws', slashes: true, hostname: hostname || location.hostname, port: port || location.port, pathname, query: _.extend(query, {id: this.id}) }; return Url.format(urlObject); } _send(data, cb) { super._send(data, cb); this._socket.send(data); cb(null); } };
import random import math import fractions from ..__init__ import * from .addition import * from .subtraction import * from .multiplication import * from .division import * from .binary_complement_1s import * from .modulo_division import * from .square_root import * from .power_rule_differentiation import * from .square import * from .lcm import * from .gcd import * from .basic_algebra import * from .log import * from .int_division import * from .decimal_to_binary import * from .binary_to_decimal import * from .divide_fractions import * from .multiply_int_to_22_matrix import * from .area_of_triangle import * from .valid_triangle import * from .midpoint_of_two_points import * from .factoring import * from .third_angle_of_triangle import * from .system_of_equations import * from .distance_two_points import * from .pythagorean_theorem import * from .linear_equations import * from .prime_factors import * from .fraction_multiplication import * from .angle_regular_polygon import * from .combinations import * from .factorial import * from .surface_area_cube import * from .surface_area_cuboid import * from .surface_area_cylinder import * from .volume_cube import * from .volume_cuboid import * from .volume_cylinder import * from .surface_area_cone import * from .volume_cone import * from .common_factors import * from .intersection_of_two_lines import * from .permutation import * from .vector_cross import * from .compare_fractions import * from .simple_interest import * from .matrix_multiplication import * from .cube_root import * from .power_rule_integration import * from .fourth_angle_of_quadrilateral import * from .quadratic_equation import * from .hcf import * from .dice_sum_probability import * from .exponentiation import * from .confidence_interval import * from .surds_comparison import * from .fibonacci_series import * from .basic_trigonometry import * from .sum_of_polygon_angles import * from .data_summary import * from .surface_area_sphere import * from .volume_sphere import * from .nth_fibonacci_number import * from .profit_loss_percent import * from .binary_to_hex import * from .multiply_complex_numbers import * from .geometric_progression import * from .geometric_mean import * from .harmonic_mean import * from .euclidian_norm import * from .angle_btw_vectors import * from .absolute_difference import * from .vector_dot import * from .binary_2s_complement import * from .invert_matrix import * from .sector_area import * from .mean_median import * from .int_matrix_22_determinant import * from .compound_interest import * from .decimal_to_hexadeci import * from .percentage import * from .celsius_to_fahrenheit import * from .arithmetic_progression_term import * from .arithmetic_progression_sum import * from .decimal_to_octal import * from .decimal_to_roman_numerals import * from .degree_to_rad import * from .radian_to_deg import * from .differentiation import * from .definite_integral import * from .is_prime import * from .bcd_to_decimal import * from .complex_to_polar import * from .set_operation import * from .base_conversion import * from .curved_surface_area_cylinder import * from .perimeter_of_polygons import * from .power_of_powers import * from .quotient_of_power_same_base import * from .quotient_of_power_same_power import * from .complex_quadratic import * from .is_leap_year import * from .minutes_to_hours import * from .decimal_to_bcd import * from .circumference import * from .combine_like_terms import * from .conditional_probability import *
""" Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from cfnlint.rules.resources.properties.Password import Password # pylint: disable=E0401 from ... import BaseRuleTestCase class TestPropertyPassword(BaseRuleTestCase): """Test Password Property Configuration""" def setUp(self): """Setup""" super(TestPropertyPassword, self).setUp() self.collection.register(Password()) self.success_templates = [ 'test/fixtures/templates/good/resources/properties/password.yaml' ] def test_file_positive(self): """Test Positive""" self.helper_file_positive() def test_file_negative(self): """Test failure""" self.helper_file_negative('test/fixtures/templates/bad/properties_password.yaml', 3)
# Copyright 2020 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. """This script demonstrates the concept of referencing multiple forms of side input data in GCS with main input data loaded from pubsub, and triggering the refresh of side input data via PubSub notification on demand Description of main and side inputs with sample records: ------------------------------------------------------- Main Input: Sales event with schema: {"Txid":1, "productname": "Product 5 XL", "qty": 1, "sales": 97.65, "event_timestamp": "2020-05-02 19:08:24.796892"} Example contains 3 side inputs: Bonus points, Discount percent and Category 1. Bonus points -> {"productname": "Product 2", "bonuspoints": 204} 2. Discount percent -> {"productname": "Product 2", "discountpct": 0.62} 3. Category -> {"productname": "Product 3", "category": "laptop"} Args: --project: GCP project ID --sideinput-notification-subscription: pub sub subscription name notifying new base path from which the side input data needs to be reloaded. --maininput-subscription: pub sub subscription name from which main input (i.e sales events) are consumed --sideinput-window-duration: Side Input window duration. Ideally Global window needs to be used instead of fixed window. However on refresh new state is not replacing old state. Hence Fixed windows of longer duration (180 days to an year) can be used to avoid expiration of window. Duration must be provided in seconds. --maininput-window-duration: Main Input window duration in seconds (--demorun | --outputpath=<OUTPUTPATH>): Use demo run if ouptput should be written to log/stdout for inspection and specify output path for writing to persistent storage . Example Usage: python -m sideinput_refresh --project=<project> --region=us-central1 --runner=DataFlowRunner \ --sideinput-notification-subscription=<subscription-name> \ --maininput-subscription=<subscription-name> \ --sideinput-window-duration=<518400> \ --maininput-window-duration=<300> \ (--demorun | --outputpath=<GCS path>) \ --staging_location=<GCS path> \ --temp_location=<GCS Path> """ import argparse import json import logging import re from typing import Dict, List, Tuple import apache_beam as beam from apache_beam.options.pipeline_options import (GoogleCloudOptions, PipelineOptions, SetupOptions, StandardOptions) from apache_beam.pvalue import AsDict from sideinput_refresh import dofns, transforms def get_subscription_path(project: str, subscription_name: str) -> str: """"Helper function to build topic subscription path from project and subscription name Args: project: GCP Project id subscription_name: PubSub Subscription name Returns: PubSub Subscription Path """ if re.match('projects/([^/]+)/subscriptions/(.+)', subscription_name): return subscription_name return f"projects/{project}/subscriptions/{subscription_name}" def parse_cliargs(argv: List[str]) -> Tuple[argparse.Namespace, List[str]]: """"Parses Command line arguments Args: argv: List of command line arguments Returns: Tuple containing Namespace object with specified arguments and list of extra arguments """ args_parser = argparse.ArgumentParser() args_parser.add_argument('--project', type=str, help="Google Cloud project id", required=True) args_parser.add_argument( '--sideinput-notification-subscription', type=str, help="Cloud Pub/Sub Side input notificaton subscription name", required=True) args_parser.add_argument('--maininput-subscription', type=str, help="Cloud Pub/Sub main input subscription name", required=True) args_parser.add_argument( '--sideinput-window-duration', type=int, help="Duration of the side input window in seconds", required=True) args_parser.add_argument( '--maininput-window-duration', type=int, help="Duration of the main input window in seconds", required=True) sink_choices = args_parser.add_mutually_exclusive_group(required=True) sink_choices.add_argument( '--demorun', help="Flag to write the output to log sink instead of file sink", action='store_true') sink_choices.add_argument( '--outputpath', type=str, help="Output file path e.g: (gs://<buckername>/prefix)", action='store') return args_parser.parse_known_args(argv) def get_sideinput_collections(sideinput_filepath: beam.pvalue.PCollection, readTransform: beam.PTransform) \ -> Dict[str,beam.pvalue.PCollection]: """"Load Side Input data from respective file paths Args: sideinput_filepath: File path representing base path for side inputs to be loaded readTransform: Transform responsible for loading the side input data Returns: Dictionary containing Side Input name as key and corresponding PCollection as value """ sideinput_types = get_sideinput_types() # yapf: disable filepaths = (sideinput_filepath | "Get side input paths from base path" >> beam.ParDo( dofns.SplitToMultiple(sideinput_types)).with_outputs(*sideinput_types) ) sideinput_collections = {} for sideinput_type in sideinput_types: sideinput_collections[sideinput_type] = (filepaths[sideinput_type] | f"Read {sideinput_type}" >> readTransform | f"{sideinput_type}:Extract KV" >> beam.Map( transforms.kv_of, "productname", sideinput_type) ) # yapf: enable return sideinput_collections def get_enriched_events(salesevent: beam.pvalue.PCollection,sideinput_collections: Dict[str,beam.pvalue.PCollection]) \ -> beam.pvalue.PCollection: """Gets enriched events by a) Call a transform that combining primary event with corresponding side input values b) Group events by dummy key to combine all events in a window into one shard c) Discard dummy key Args: salesevent: Event representing sales transaction sideinput_collections: Set of Side Input Collections """ # yapf: disable return (salesevent | "Enrich event" >> beam.Map(transforms.enrich_event, AsDict(sideinput_collections["bonuspoints"]), AsDict(sideinput_collections["discountpct"]), AsDict(sideinput_collections["category"])) | "Group events by dummy Key" >> beam.GroupByKey() | "Discard dummy Key" >> beam.Values() ) # yapf: enable def get_sideinput_types() -> List[str]: """Returns list of side input types Returns: Side Input types """ return ["bonuspoints", "discountpct", "category"] def run(argv: List[str] = None, save_main_session: bool = True) -> None: """"Driver function to parse command line args, build pipeline options and invokes pipeline Args: argv: Command line arguments specified by the user save_main_session: Setting to indicate the visibility of modules to beam Returns: None """ known_args, extra_args = parse_cliargs(argv) known_args.maininput_subscription = get_subscription_path( known_args.project, known_args.maininput_subscription) known_args.sideinput_notification_subscription = get_subscription_path( known_args.project, known_args.sideinput_notification_subscription) pipeline_options = PipelineOptions(flags=extra_args) pipeline_options.view_as(GoogleCloudOptions).project = known_args.project pipeline_options.view_as(SetupOptions).save_main_session = save_main_session pipeline_options.view_as(StandardOptions).streaming = True pipeline = beam.Pipeline(options=pipeline_options) # Get Side Input Refresh Notification # yapf: disable sideinput_filepath = (pipeline | "Read Side input file path from pubsub subscription" >> beam.io.ReadFromPubSub(subscription=known_args.sideinput_notification_subscription) | "Side input fixed window with early trigger" >> beam.WindowInto( beam.window.FixedWindows(known_args.sideinput_window_duration), trigger=beam.trigger.Repeatedly(beam.trigger.AfterCount(1)), accumulation_mode=beam.trigger.AccumulationMode.DISCARDING) ) # Get Side Input data # Ideally instead of writing transform to ReadSideInputData, an inbuilt transform textio.ReadAllFromText(coder=coders.UTF8JsonCoder()) # can be used. However when ReadAllFromText is used despite of loading all data certain elements are not propogating well as side input # Created a BEAM issue https://issues.apache.org/jira/browse/BEAM-10148 for further investigation # Once issue is fixed transforms.ReadSideInputData() will be replaced with apache_beam.io.textio.ReadAllFromText(coder=coders.UTF8JsonCoder())) sideinput_collections = get_sideinput_collections(sideinput_filepath,transforms.ReadSideInputData()) # Get Sales as main input primary_events = (pipeline | "Read sales events from pubsub subscription" >> beam.io.ReadFromPubSub(subscription=known_args.maininput_subscription) | "Main input fixed window" >> beam.WindowInto(beam.window.FixedWindows(known_args.maininput_window_duration)) ) # Enrich primary events with side input data enriched_events = get_enriched_events(primary_events, sideinput_collections) # Write enriched events to sink if known_args.demorun: enriched_events | "Write output to Log" >> transforms.LogEvents() else: (enriched_events | "Unpack the events" >> beam.FlatMap(lambda x: list(map(json.dumps, x))) | "Write output to GCS" >> beam.io.fileio.WriteToFiles(known_args.outputpath, shards=1) ) # yapf: enable pipeline_result = pipeline.run() # Used while testing locally if pipeline_options.view_as(StandardOptions).runner == "DirectRunner": pipeline_result.wait_until_finish() if __name__ == "__main__": logging.getLogger().setLevel(level=logging.INFO) run()
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-3e15998 */ function MdDividerDirective(e){return{restrict:"E",link:e}}goog.provide("ng.material.components.divider"),goog.require("ng.material.core"),angular.module("material.components.divider",["material.core"]).directive("mdDivider",MdDividerDirective),MdDividerDirective.$inject=["$mdTheming"],ng.material.components.divider=angular.module("material.components.divider");
#!/usr/bin/env node const log = console.log; log(`process.argv =`, process.argv[2]); // String heterogeneous homogeneity judgment const SHHJ = (str = ``) => { const [s1, s2] = str.trim().split(` `); let result = false; let a = s1.split(``).sort().join(``); let b = s2.split(``).sort().join(``); if(a === b) { result = true; } log(`result`, result); return result; } // node.js 命令行工具 const args = process.argv[2]; SHHJ(args);
import $ from 'jquery'; pageflow.DomOrderScrollNavigator = function(slideshow, entryData) { this.getLandingPage = function(pages) { return pages.first(); }; this.back = function(currentPage, pages) { var position = 'bottom'; var previousPage = this.getPreviousPage(currentPage, pages); if (previousPage.is(getParentPage(currentPage, pages))) { position = null; } slideshow.goTo(previousPage, { position: position, ignoreInHistory: true }); }; this.next = function(currentPage, pages) { slideshow.goTo(this.getNextPage(currentPage, pages), { ignoreInHistory: true }); }; this.nextPageExists = function(currentPage, pages) { return !!this.getNextPage(currentPage, pages).length; }; this.previousPageExists = function(currentPage, pages) { return !!this.getPreviousPage(currentPage, pages).length; }; this.getNextPage = function(currentPage, pages) { var currentPageIndex = pages.index(currentPage); var nextPage = currentPageIndex < pages.length - 1 ? $(pages.get(currentPageIndex + 1)) : $(); if (sameStoryline(currentPage, nextPage)) { return nextPage; } var scrollSuccessor = getScrollSuccessor(currentPage, pages); if (scrollSuccessor.length) { return scrollSuccessor; } return getParentPage(currentPage, pages); }; this.getPreviousPage = function(currentPage, pages) { var currentPageIndex = pages.index(currentPage); var previousPage = currentPageIndex > 0 ? $(pages.get(currentPageIndex - 1)) : $(); if (sameStoryline(currentPage, previousPage)) { return previousPage; } return getParentPage(currentPage, pages); }; this.getTransitionDirection = function(previousPage, currentPage, pages, options) { return (pages.index(currentPage) > pages.index(previousPage) ? 'forwards' : 'backwards'); }; this.getDefaultTransition = function(previousPage, currentPage, pages) { if (inParentStorylineOf(currentPage, previousPage, pages)) { return getStorylinePageTransition(currentPage); } else if (inParentStorylineOf(previousPage, currentPage, pages)) { return getStorylinePageTransition(previousPage); } }; function inParentStorylineOf(page, otherPage, pages) { var parentPage = getParentPage(page, pages); return entryData.getStorylineIdByPagePermaId(parentPage.page('getPermaId')) == entryData.getStorylineIdByPagePermaId(otherPage.page('getPermaId')); } function sameStoryline(page1, page2) { return entryData.getStorylineIdByPagePermaId(page1.page('getPermaId')) == entryData.getStorylineIdByPagePermaId(page2.page('getPermaId')); } function getParentPage(page, pages) { var storylineConfiguration = getStorylineConfiguration(page); if ('parent_page_perma_id' in storylineConfiguration && entryData.getThemingOption('change_to_parent_page_at_storyline_boundary')) { return pages.filter('#' + storylineConfiguration.parent_page_perma_id); } return $(); } function getStorylinePageTransition(page) { var storylineConfiguration = getStorylineConfiguration(page); return storylineConfiguration.page_transition || 'scroll_over_from_right'; } function getScrollSuccessor(page, pages) { var storylineConfiguration = getStorylineConfiguration(page); if ('scroll_successor_id' in storylineConfiguration) { return pages.filter('#' + storylineConfiguration.scroll_successor_id); } return $(); } function getStorylineConfiguration(page) { var permaId = page.page('getPermaId'); var storylineId = entryData.getStorylineIdByPagePermaId(permaId); return entryData.getStorylineConfiguration(storylineId); } };
import logging from selinon import StoragePool _LOGGER = logging.getLogger(__name__) def iter_travis_repos(storage_pool: StoragePool, node_args: dict) -> list: """Iterate over repos and extend node args with the repo name.""" try: repos = storage_pool.get('TravisActiveRepos') new_node_args = [] for repo in repos: new_node_args.append(dict(repo=repo, **node_args)) return new_node_args except Exception as exc: _LOGGER.exception(str(exc)) return [] def iter_travis_builds(storage_pool: StoragePool, node_args: dict) -> list: """Iterate over builds found and extend node args with the build information.""" try: builds = storage_pool.get('TravisRepoBuilds') new_node_args = [] for build in builds: new_node_args.append(dict(**build, **node_args)) return new_node_args except Exception as exc: _LOGGER.exception(str(exc)) return [] def iter_travis_builds_count(storage_pool: StoragePool, node_args: dict) -> list: """Iterate over build counts respecting offset so build id downloads can be done in parallel.""" try: builds_count = storage_pool.get('TravisRepoBuildsCount')['count'] new_node_args = [] for offset in range(builds_count): new_node_args.append(dict(**node_args, offset=offset)) return new_node_args except Exception as exc: _LOGGER.exception(str(exc)) return []
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2019 Huawei # GNU General Public License v3.0+ (see COPYING or # https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ############################################################################### # Documentation ############################################################################### ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: hwc_vpc_port description: - vpc port management. short_description: Creates a resource of Vpc/Port in Huawei Cloud version_added: '2.9' author: Huawei Inc. (@huaweicloud) requirements: - keystoneauth1 >= 3.6.0 options: state: description: - Whether the given object should exist in Huawei Cloud. type: str choices: ['present', 'absent'] default: 'present' filters: description: - A list of filters to apply when deciding whether existing resources match and should be altered. The item of filters is the name of input options. type: list required: true timeouts: description: - The timeouts for each operations. type: dict suboptions: create: description: - The timeouts for create operation. type: str default: '15m' subnet_id: description: - Specifies the ID of the subnet to which the port belongs. type: str required: true admin_state_up: description: - Specifies the administrative state of the port. type: bool required: false allowed_address_pairs: description: - Specifies a set of zero or more allowed address pairs. required: false suboptions: ip_address: description: - Specifies the IP address. It cannot set it to 0.0.0.0. Configure an independent security group for the port if a large CIDR block (subnet mask less than 24) is configured for parameter allowed_address_pairs. type: str required: false mac_address: description: - Specifies the MAC address. type: str required: false extra_dhcp_opts: description: - Specifies the extended option of DHCP. type: complex required: false suboptions: name: description: - Specifies the option name. type: str required: false value: description: - Specifies the option value. type: str required: false ip_address: description: - Specifies the port IP address. type: str required: false name: description: - Specifies the port name. The value can contain no more than 255 characters. type: str required: false security_groups: description: - Specifies the ID of the security group. type: list required: false extends_documentation_fragment: hwc ''' EXAMPLES = ''' # create a port - name: create vpc hwc_network_vpc: cidr: "192.168.100.0/24" name: "ansible_network_vpc_test" register: vpc - name: create subnet hwc_vpc_subnet: gateway_ip: "192.168.100.32" name: "ansible_network_subnet_test" dhcp_enable: True vpc_id: "{{ vpc.id }}" filters: - "name" cidr: "192.168.100.0/26" register: subnet - name: create a port hwc_vpc_port: subnet_id: "{{ subnet.id }}" ip_address: "192.168.100.33" filters: - "name" - "network_id" - "ip_address" ''' RETURN = ''' subnet_id: description: - Specifies the ID of the subnet to which the port belongs. type: str returned: success admin_state_up: description: - Specifies the administrative state of the port. type: bool returned: success allowed_address_pairs: description: - Specifies a set of zero or more allowed address pairs. type: complex returned: success contains: ip_address: description: - Specifies the IP address. It cannot set it to 0.0.0.0. Configure an independent security group for the port if a large CIDR block (subnet mask less than 24) is configured for parameter allowed_address_pairs. type: str returned: success mac_address: description: - Specifies the MAC address. type: str returned: success extra_dhcp_opts: description: - Specifies the extended option of DHCP. type: complex returned: success contains: name: description: - Specifies the option name. type: str returned: success value: description: - Specifies the option value. type: str returned: success ip_address: description: - Specifies the port IP address. type: str returned: success name: description: - Specifies the port name. The value can contain no more than 255 characters. type: str returned: success security_groups: description: - Specifies the ID of the security group. type: list returned: success mac_address: description: - Specifies the port MAC address. type: str returned: success ''' from ansible.module_utils.hwc_utils import ( Config, HwcClientException, HwcClientException404, HwcModule, are_different_dicts, build_path, get_region, is_empty_value, navigate_value, wait_to_finish) def build_module(): return HwcModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), filters=dict(required=True, type='list', elements='str'), timeouts=dict(type='dict', options=dict( create=dict(default='15m', type='str'), ), default=dict()), subnet_id=dict(type='str', required=True), admin_state_up=dict(type='bool'), allowed_address_pairs=dict( type='list', elements='dict', options=dict( ip_address=dict(type='str'), mac_address=dict(type='str') ), ), extra_dhcp_opts=dict(type='list', elements='dict', options=dict( name=dict(type='str'), value=dict(type='str') )), ip_address=dict(type='str'), name=dict(type='str'), security_groups=dict(type='list', elements='str') ), supports_check_mode=True, ) def main(): """Main function""" module = build_module() config = Config(module, "vpc") try: resource = None if module.params['id']: resource = True else: v = search_resource(config) if len(v) > 1: raise Exception("find more than one resources(%s)" % ", ".join([ navigate_value(i, ["id"]) for i in v])) if len(v) == 1: resource = v[0] module.params['id'] = navigate_value(resource, ["id"]) result = {} changed = False if module.params['state'] == 'present': if resource is None: if not module.check_mode: create(config) changed = True current = read_resource(config, exclude_output=True) expect = user_input_parameters(module) if are_different_dicts(expect, current): if not module.check_mode: update(config) changed = True result = read_resource(config) result['id'] = module.params.get('id') else: if resource: if not module.check_mode: delete(config) changed = True except Exception as ex: module.fail_json(msg=str(ex)) else: result['changed'] = changed module.exit_json(**result) def user_input_parameters(module): return { "admin_state_up": module.params.get("admin_state_up"), "allowed_address_pairs": module.params.get("allowed_address_pairs"), "extra_dhcp_opts": module.params.get("extra_dhcp_opts"), "ip_address": module.params.get("ip_address"), "name": module.params.get("name"), "security_groups": module.params.get("security_groups"), "subnet_id": module.params.get("subnet_id"), } def create(config): module = config.module client = config.client(get_region(module), "vpc", "project") timeout = 60 * int(module.params['timeouts']['create'].rstrip('m')) opts = user_input_parameters(module) params = build_create_parameters(opts) r = send_create_request(module, params, client) obj = async_wait_create(config, r, client, timeout) module.params['id'] = navigate_value(obj, ["port", "id"]) def update(config): module = config.module client = config.client(get_region(module), "vpc", "project") opts = user_input_parameters(module) params = build_update_parameters(opts) if params: send_update_request(module, params, client) def delete(config): module = config.module client = config.client(get_region(module), "vpc", "project") send_delete_request(module, None, client) url = build_path(module, "ports/{id}") def _refresh_status(): try: client.get(url) except HwcClientException404: return True, "Done" except Exception: return None, "" return True, "Pending" timeout = 60 * int(module.params['timeouts']['create'].rstrip('m')) try: wait_to_finish(["Done"], ["Pending"], _refresh_status, timeout) except Exception as ex: module.fail_json(msg="module(hwc_vpc_port): error " "waiting for api(delete) to " "be done, error= %s" % str(ex)) def read_resource(config, exclude_output=False): module = config.module client = config.client(get_region(module), "vpc", "project") res = {} r = send_read_request(module, client) res["read"] = fill_read_resp_body(r) array_index = { "read.fixed_ips": 0, } return update_properties(module, res, array_index, exclude_output) def _build_query_link(opts): query_params = [] v = navigate_value(opts, ["subnet_id"]) if v: query_params.append("network_id=" + str(v)) v = navigate_value(opts, ["name"]) if v: query_params.append("name=" + str(v)) v = navigate_value(opts, ["admin_state_up"]) if v: query_params.append("admin_state_up=" + str(v)) query_link = "?marker={marker}&limit=10" if query_params: query_link += "&" + "&".join(query_params) return query_link def search_resource(config): module = config.module client = config.client(get_region(module), "vpc", "project") opts = user_input_parameters(module) identity_obj = _build_identity_object(module, opts) query_link = _build_query_link(opts) link = "ports" + query_link result = [] p = {'marker': ''} while True: url = link.format(**p) r = send_list_request(module, client, url) if not r: break for item in r: item = fill_list_resp_body(item) if not are_different_dicts(identity_obj, item): result.append(item) if len(result) > 1: break p['marker'] = r[-1].get('id') return result def build_create_parameters(opts): params = dict() v = navigate_value(opts, ["admin_state_up"], None) if not is_empty_value(v): params["admin_state_up"] = v v = expand_create_allowed_address_pairs(opts, None) if not is_empty_value(v): params["allowed_address_pairs"] = v v = expand_create_extra_dhcp_opts(opts, None) if not is_empty_value(v): params["extra_dhcp_opts"] = v v = expand_create_fixed_ips(opts, None) if not is_empty_value(v): params["fixed_ips"] = v v = navigate_value(opts, ["name"], None) if not is_empty_value(v): params["name"] = v v = navigate_value(opts, ["subnet_id"], None) if not is_empty_value(v): params["network_id"] = v v = navigate_value(opts, ["security_groups"], None) if not is_empty_value(v): params["security_groups"] = v if not params: return params params = {"port": params} return params def expand_create_allowed_address_pairs(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["allowed_address_pairs"], new_array_index) if not v: return req n = len(v) for i in range(n): new_array_index["allowed_address_pairs"] = i transformed = dict() v = navigate_value(d, ["allowed_address_pairs", "ip_address"], new_array_index) if not is_empty_value(v): transformed["ip_address"] = v v = navigate_value(d, ["allowed_address_pairs", "mac_address"], new_array_index) if not is_empty_value(v): transformed["mac_address"] = v if transformed: req.append(transformed) return req def expand_create_extra_dhcp_opts(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["extra_dhcp_opts"], new_array_index) if not v: return req n = len(v) for i in range(n): new_array_index["extra_dhcp_opts"] = i transformed = dict() v = navigate_value(d, ["extra_dhcp_opts", "name"], new_array_index) if not is_empty_value(v): transformed["opt_name"] = v v = navigate_value(d, ["extra_dhcp_opts", "value"], new_array_index) if not is_empty_value(v): transformed["opt_value"] = v if transformed: req.append(transformed) return req def expand_create_fixed_ips(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] n = 1 for i in range(n): transformed = dict() v = navigate_value(d, ["ip_address"], new_array_index) if not is_empty_value(v): transformed["ip_address"] = v if transformed: req.append(transformed) return req def send_create_request(module, params, client): url = "ports" try: r = client.post(url, params) except HwcClientException as ex: msg = ("module(hwc_vpc_port): error running " "api(create), error: %s" % str(ex)) module.fail_json(msg=msg) return r def async_wait_create(config, result, client, timeout): module = config.module path_parameters = { "port_id": ["port", "id"], } data = { key: navigate_value(result, path) for key, path in path_parameters.items() } url = build_path(module, "ports/{port_id}", data) def _query_status(): r = None try: r = client.get(url, timeout=timeout) except HwcClientException: return None, "" try: s = navigate_value(r, ["port", "status"]) return r, s except Exception: return None, "" try: return wait_to_finish( ["ACTIVE", "DOWN"], ["BUILD"], _query_status, timeout) except Exception as ex: module.fail_json(msg="module(hwc_vpc_port): error " "waiting for api(create) to " "be done, error= %s" % str(ex)) def build_update_parameters(opts): params = dict() v = expand_update_allowed_address_pairs(opts, None) if v is not None: params["allowed_address_pairs"] = v v = expand_update_extra_dhcp_opts(opts, None) if v is not None: params["extra_dhcp_opts"] = v v = navigate_value(opts, ["name"], None) if not is_empty_value(v): params["name"] = v v = navigate_value(opts, ["security_groups"], None) if not is_empty_value(v): params["security_groups"] = v if not params: return params params = {"port": params} return params def expand_update_allowed_address_pairs(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["allowed_address_pairs"], new_array_index) if not v: return req n = len(v) for i in range(n): new_array_index["allowed_address_pairs"] = i transformed = dict() v = navigate_value(d, ["allowed_address_pairs", "ip_address"], new_array_index) if not is_empty_value(v): transformed["ip_address"] = v v = navigate_value(d, ["allowed_address_pairs", "mac_address"], new_array_index) if not is_empty_value(v): transformed["mac_address"] = v if transformed: req.append(transformed) return req def expand_update_extra_dhcp_opts(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["extra_dhcp_opts"], new_array_index) if not v: return req n = len(v) for i in range(n): new_array_index["extra_dhcp_opts"] = i transformed = dict() v = navigate_value(d, ["extra_dhcp_opts", "name"], new_array_index) if not is_empty_value(v): transformed["opt_name"] = v v = navigate_value(d, ["extra_dhcp_opts", "value"], new_array_index) if not is_empty_value(v): transformed["opt_value"] = v if transformed: req.append(transformed) return req def send_update_request(module, params, client): url = build_path(module, "ports/{id}") try: r = client.put(url, params) except HwcClientException as ex: msg = ("module(hwc_vpc_port): error running " "api(update), error: %s" % str(ex)) module.fail_json(msg=msg) return r def send_delete_request(module, params, client): url = build_path(module, "ports/{id}") try: r = client.delete(url, params) except HwcClientException as ex: msg = ("module(hwc_vpc_port): error running " "api(delete), error: %s" % str(ex)) module.fail_json(msg=msg) return r def send_read_request(module, client): url = build_path(module, "ports/{id}") r = None try: r = client.get(url) except HwcClientException as ex: msg = ("module(hwc_vpc_port): error running " "api(read), error: %s" % str(ex)) module.fail_json(msg=msg) return navigate_value(r, ["port"], None) def fill_read_resp_body(body): result = dict() result["admin_state_up"] = body.get("admin_state_up") v = fill_read_resp_allowed_address_pairs(body.get("allowed_address_pairs")) result["allowed_address_pairs"] = v result["binding_host_id"] = body.get("binding_host_id") result["binding_vnic_type"] = body.get("binding_vnic_type") result["device_id"] = body.get("device_id") result["device_owner"] = body.get("device_owner") result["dns_name"] = body.get("dns_name") v = fill_read_resp_extra_dhcp_opts(body.get("extra_dhcp_opts")) result["extra_dhcp_opts"] = v v = fill_read_resp_fixed_ips(body.get("fixed_ips")) result["fixed_ips"] = v result["id"] = body.get("id") result["mac_address"] = body.get("mac_address") result["name"] = body.get("name") result["network_id"] = body.get("network_id") result["security_groups"] = body.get("security_groups") result["status"] = body.get("status") result["tenant_id"] = body.get("tenant_id") return result def fill_read_resp_allowed_address_pairs(value): if not value: return None result = [] for item in value: val = dict() val["ip_address"] = item.get("ip_address") val["mac_address"] = item.get("mac_address") result.append(val) return result def fill_read_resp_extra_dhcp_opts(value): if not value: return None result = [] for item in value: val = dict() val["opt_name"] = item.get("opt_name") val["opt_value"] = item.get("opt_value") result.append(val) return result def fill_read_resp_fixed_ips(value): if not value: return None result = [] for item in value: val = dict() val["ip_address"] = item.get("ip_address") result.append(val) return result def update_properties(module, response, array_index, exclude_output=False): r = user_input_parameters(module) v = navigate_value(response, ["read", "admin_state_up"], array_index) r["admin_state_up"] = v v = r.get("allowed_address_pairs") v = flatten_allowed_address_pairs(response, array_index, v, exclude_output) r["allowed_address_pairs"] = v v = r.get("extra_dhcp_opts") v = flatten_extra_dhcp_opts(response, array_index, v, exclude_output) r["extra_dhcp_opts"] = v v = navigate_value(response, ["read", "fixed_ips", "ip_address"], array_index) r["ip_address"] = v if not exclude_output: v = navigate_value(response, ["read", "mac_address"], array_index) r["mac_address"] = v v = navigate_value(response, ["read", "name"], array_index) r["name"] = v v = navigate_value(response, ["read", "security_groups"], array_index) r["security_groups"] = v v = navigate_value(response, ["read", "network_id"], array_index) r["subnet_id"] = v return r def flatten_allowed_address_pairs(d, array_index, current_value, exclude_output): n = 0 result = current_value has_init_value = True if result: n = len(result) else: has_init_value = False result = [] v = navigate_value(d, ["read", "allowed_address_pairs"], array_index) if not v: return current_value n = len(v) new_array_index = dict() if array_index: new_array_index.update(array_index) for i in range(n): new_array_index["read.allowed_address_pairs"] = i val = dict() if len(result) >= (i + 1) and result[i]: val = result[i] v = navigate_value(d, ["read", "allowed_address_pairs", "ip_address"], new_array_index) val["ip_address"] = v v = navigate_value(d, ["read", "allowed_address_pairs", "mac_address"], new_array_index) val["mac_address"] = v if len(result) >= (i + 1): result[i] = val else: for v in val.values(): if v is not None: result.append(val) break return result if (has_init_value or result) else current_value def flatten_extra_dhcp_opts(d, array_index, current_value, exclude_output): n = 0 result = current_value has_init_value = True if result: n = len(result) else: has_init_value = False result = [] v = navigate_value(d, ["read", "extra_dhcp_opts"], array_index) if not v: return current_value n = len(v) new_array_index = dict() if array_index: new_array_index.update(array_index) for i in range(n): new_array_index["read.extra_dhcp_opts"] = i val = dict() if len(result) >= (i + 1) and result[i]: val = result[i] v = navigate_value(d, ["read", "extra_dhcp_opts", "opt_name"], new_array_index) val["name"] = v v = navigate_value(d, ["read", "extra_dhcp_opts", "opt_value"], new_array_index) val["value"] = v if len(result) >= (i + 1): result[i] = val else: for v in val.values(): if v is not None: result.append(val) break return result if (has_init_value or result) else current_value def send_list_request(module, client, url): r = None try: r = client.get(url) except HwcClientException as ex: msg = ("module(hwc_vpc_port): error running " "api(list), error: %s" % str(ex)) module.fail_json(msg=msg) return navigate_value(r, ["ports"], None) def _build_identity_object(module, all_opts): filters = module.params.get("filters") opts = dict() for k, v in all_opts.items(): opts[k] = v if k in filters else None result = dict() v = navigate_value(opts, ["admin_state_up"], None) result["admin_state_up"] = v v = expand_list_allowed_address_pairs(opts, None) result["allowed_address_pairs"] = v result["binding_host_id"] = None result["binding_vnic_type"] = None result["device_id"] = None result["device_owner"] = None result["dns_name"] = None v = expand_list_extra_dhcp_opts(opts, None) result["extra_dhcp_opts"] = v v = expand_list_fixed_ips(opts, None) result["fixed_ips"] = v result["id"] = None result["mac_address"] = None v = navigate_value(opts, ["name"], None) result["name"] = v v = navigate_value(opts, ["subnet_id"], None) result["network_id"] = v v = navigate_value(opts, ["security_groups"], None) result["security_groups"] = v result["status"] = None result["tenant_id"] = None return result def expand_list_allowed_address_pairs(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["allowed_address_pairs"], new_array_index) n = len(v) if v else 1 for i in range(n): new_array_index["allowed_address_pairs"] = i transformed = dict() v = navigate_value(d, ["allowed_address_pairs", "ip_address"], new_array_index) transformed["ip_address"] = v v = navigate_value(d, ["allowed_address_pairs", "mac_address"], new_array_index) transformed["mac_address"] = v for v in transformed.values(): if v is not None: req.append(transformed) break return req if req else None def expand_list_extra_dhcp_opts(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] v = navigate_value(d, ["extra_dhcp_opts"], new_array_index) n = len(v) if v else 1 for i in range(n): new_array_index["extra_dhcp_opts"] = i transformed = dict() v = navigate_value(d, ["extra_dhcp_opts", "name"], new_array_index) transformed["opt_name"] = v v = navigate_value(d, ["extra_dhcp_opts", "value"], new_array_index) transformed["opt_value"] = v for v in transformed.values(): if v is not None: req.append(transformed) break return req if req else None def expand_list_fixed_ips(d, array_index): new_array_index = dict() if array_index: new_array_index.update(array_index) req = [] n = 1 for i in range(n): transformed = dict() v = navigate_value(d, ["ip_address"], new_array_index) transformed["ip_address"] = v for v in transformed.values(): if v is not None: req.append(transformed) break return req if req else None def fill_list_resp_body(body): result = dict() result["admin_state_up"] = body.get("admin_state_up") v = fill_list_resp_allowed_address_pairs(body.get("allowed_address_pairs")) result["allowed_address_pairs"] = v result["binding_host_id"] = body.get("binding_host_id") result["binding_vnic_type"] = body.get("binding_vnic_type") result["device_id"] = body.get("device_id") result["device_owner"] = body.get("device_owner") result["dns_name"] = body.get("dns_name") v = fill_list_resp_extra_dhcp_opts(body.get("extra_dhcp_opts")) result["extra_dhcp_opts"] = v v = fill_list_resp_fixed_ips(body.get("fixed_ips")) result["fixed_ips"] = v result["id"] = body.get("id") result["mac_address"] = body.get("mac_address") result["name"] = body.get("name") result["network_id"] = body.get("network_id") result["security_groups"] = body.get("security_groups") result["status"] = body.get("status") result["tenant_id"] = body.get("tenant_id") return result def fill_list_resp_allowed_address_pairs(value): if not value: return None result = [] for item in value: val = dict() val["ip_address"] = item.get("ip_address") val["mac_address"] = item.get("mac_address") result.append(val) return result def fill_list_resp_extra_dhcp_opts(value): if not value: return None result = [] for item in value: val = dict() val["opt_name"] = item.get("opt_name") val["opt_value"] = item.get("opt_value") result.append(val) return result def fill_list_resp_fixed_ips(value): if not value: return None result = [] for item in value: val = dict() val["ip_address"] = item.get("ip_address") result.append(val) return result if __name__ == '__main__': main()
"""Mask RCNN with ResNet50-FPN, 1x schedule.""" _base_ = [ "../_base_/models/mask_rcnn_r50_fpn.py", "../_base_/datasets/bdd100k.py", "../_base_/schedules/schedule_1x.py", "../_base_/default_runtime.py", ] load_from = "https://dl.cv.ethz.ch/bdd100k/ins_seg/models/mask_rcnn_r50_fpn_1x_ins_seg_bdd100k.pth"
const vertex = `#version 300 es #define PI 3.1415926535897932384626433832795 #define ASPECT_RATIO 16.0/9.0 uniform float angle; uniform int index; uniform vec2 camera; uniform vec2 position; uniform vec2 size; uniform vec3 dimensions; in vec2 vertex_position; mat3 rotation(float degrees) { float angle = radians(degrees); float c = cos(angle); float s = sin(angle); return mat3( vec3(c, -s, 0), vec3(s, c, 0), vec3(0, 0, 1)); } mat3 scaling(vec2 size) { return mat3( vec3(size.x, 0, 0), vec3( 0, size.y, 0), vec3( 0, 0, 1)); } void main() { mat3 rot = rotation(angle); mat3 scale = scaling(vec2(dimensions.z, dimensions.z)) * scaling(size); vec3 resolution = vec3(dimensions.xy, -1.0); vec3 cam = vec3(camera, 0) / resolution; vec3 pos = vec3(position, float(index)/100.0) / resolution; vec3 vertex = vec3(vertex_position, 1.0); vec3 vertex_aspect = vertex * rot / vec3(ASPECT_RATIO, 1.0, 1.0); gl_Position = vec4(vertex_aspect * scale + pos + cam - 1.0, 1.0); }` const fragment = `#version 300 es precision mediump float; uniform float alpha; uniform vec3 color; out vec4 outColor; void main() { outColor = vec4(color, alpha); }` const ShaderDefault = { vertex, fragment }
// P_2_2_6_01_class_version // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * A chain of linked pendulums. Each a little shorter and faster than the one it's linked to. * Each joint of the pendulum leaves behind its own trail. * * KEYS * 1 : toggle pendulum * 2 : toggle pendulum path * - : decrease speed relation * + : increase speed relation * arrow down : decrease length of lines * arrow up : increase length of lines * arrow left : decrease joints * arrow right : increase joints * del, backspace : clear screen * s : save png * * CONTRIBUTED BY * [Niels Poldervaart](http://NielsPoldervaart.nl) */ 'use strict'; var shape; var joints = 5; var lineLength = 100; var speedRelation = 2; var showPendulum = true; var showPendulumPath = true; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); noFill(); strokeWeight(1); shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } function draw() { background(0, 0, 100); shape.draw(); } function Shape(x, y, joints, lineLength, speedRelation, speed) { this.center = createVector(x, y); this.pendulumPath = []; this.angle = 0; this.maxAngle = 360; this.joints = joints; this.lineLength = lineLength; this.speedRelation = speedRelation || 2; this.speed = speed || (8 / pow(1.75, this.joints - 1) / pow(2, speedRelation - 1)); // new empty array for each joint for (var i = 0; i < this.joints; i++) { this.pendulumPath.push([]); } Shape.prototype.draw = function() { this.angle += this.speed; if (this.angle <= this.maxAngle + this.speed) { // start at the center position var pos = this.center.copy(); for (var i = 0; i < this.joints; i++) { var a = this.angle * pow(speedRelation, i); if (i % 2 == 1) a = -a; var nextPos = p5.Vector.fromAngle(radians(a)); nextPos.setMag((this.lineLength / this.joints) * (this.joints - i)); nextPos.add(pos); if (showPendulum) { noStroke(); fill(0, 10); ellipse(pos.x, pos.y, 4, 4); noFill(); stroke(0, 10); line(pos.x, pos.y, nextPos.x, nextPos.y); } pos = nextPos; this.pendulumPath[i].push(pos); } } if (showPendulumPath) { strokeWeight(1.6); for (var i = 0; i < this.pendulumPath.length; i++) { var path = this.pendulumPath[i]; beginShape(); var hue = map(i, 0, this.joints, 120, 360); stroke(hue, 80, 60, 50); for (var j = 0; j < path.length; j++) { vertex(path[j].x, path[j].y); } endShape(); } } }; } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) { shape = new Shape(width / 2, height / 2, joints, lineLength); } if (keyCode == UP_ARROW) { lineLength += 2; shape.lineLength = lineLength; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (keyCode == DOWN_ARROW) { lineLength -= 2; shape.lineLength = lineLength; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (keyCode == LEFT_ARROW) { joints--; if (joints < 1) joints = 1; shape.joints = joints; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (keyCode == RIGHT_ARROW) { joints++; if (joints > 10) joints = 10; shape.joints = joints; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (key == '+') { speedRelation++; if (speedRelation > 5) speedRelation = 5; shape.speedRelation = speedRelation; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (key == '-') { speedRelation--; if (speedRelation < 2) speedRelation = 2; shape.speedRelation = speedRelation; shape = new Shape(width / 2, height / 2, joints, lineLength, speedRelation); } if (key == '1') showPendulum = !showPendulum; if (key == '2') showPendulumPath = !showPendulumPath; }
"""Support for the SQLite database via pysqlite. Note that pysqlite is the same driver as the ``sqlite3`` module included with the Python distribution. Driver ------ When using Python 2.5 and above, the built in ``sqlite3`` driver is already installed and no additional installation is needed. Otherwise, the ``pysqlite2`` driver needs to be present. This is the same driver as ``sqlite3``, just with a different name. The ``pysqlite2`` driver will be loaded first, and if not found, ``sqlite3`` is loaded. This allows an explicitly installed pysqlite driver to take precedence over the built in one. As with all dialects, a specific DBAPI module may be provided to :func:`~sqlalchemy.create_engine()` to control this explicitly:: from sqlite3 import dbapi2 as sqlite e = create_engine('sqlite+pysqlite:///file.db', module=sqlite) Full documentation on pysqlite is available at: `<http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html>`_ Connect Strings --------------- The file specification for the SQLite database is taken as the "database" portion of the URL. Note that the format of a url is:: driver://user:pass@host/database This means that the actual filename to be used starts with the characters to the **right** of the third slash. So connecting to a relative filepath looks like:: # relative path e = create_engine('sqlite:///path/to/database.db') An absolute path, which is denoted by starting with a slash, means you need **four** slashes:: # absolute path e = create_engine('sqlite:////path/to/database.db') To use a Windows path, regular drive specifications and backslashes can be used. Double backslashes are probably needed:: # absolute path on Windows e = create_engine('sqlite:///C:\\\\path\\\\to\\\\database.db') The sqlite ``:memory:`` identifier is the default if no filepath is present. Specify ``sqlite://`` and nothing else:: # in-memory database e = create_engine('sqlite://') Compatibility with sqlite3 "native" date and datetime types ----------------------------------------------------------- The pysqlite driver includes the sqlite3.PARSE_DECLTYPES and sqlite3.PARSE_COLNAMES options, which have the effect of any column or expression explicitly cast as "date" or "timestamp" will be converted to a Python date or datetime object. The date and datetime types provided with the pysqlite dialect are not currently compatible with these options, since they render the ISO date/datetime including microseconds, which pysqlite's driver does not. Additionally, SQLAlchemy does not at this time automatically render the "cast" syntax required for the freestanding functions "current_timestamp" and "current_date" to return datetime/date types natively. Unfortunately, pysqlite does not provide the standard DBAPI types in `cursor.description`, leaving SQLAlchemy with no way to detect these types on the fly without expensive per-row type checks. Usage of PARSE_DECLTYPES can be forced if one configures "native_datetime=True" on create_engine():: engine = create_engine('sqlite://', connect_args={'detect_types': sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES}, native_datetime=True ) With this flag enabled, the DATE and TIMESTAMP types (but note - not the DATETIME or TIME types...confused yet ?) will not perform any bind parameter or result processing. Execution of "func.current_date()" will return a string. "func.current_timestamp()" is registered as returning a DATETIME type in SQLAlchemy, so this function still receives SQLAlchemy-level result processing. Threading Behavior ------------------ Pysqlite connections do not support being moved between threads, unless the ``check_same_thread`` Pysqlite flag is set to ``False``. In addition, when using an in-memory SQLite database, the full database exists only within the scope of a single connection. It is reported that an in-memory database does not support being shared between threads regardless of the ``check_same_thread`` flag - which means that a multithreaded application **cannot** share data from a ``:memory:`` database across threads unless access to the connection is limited to a single worker thread which communicates through a queueing mechanism to concurrent threads. To provide a default which accomodates SQLite's default threading capabilities somewhat reasonably, the SQLite dialect will specify that the :class:`~sqlalchemy.pool.SingletonThreadPool` be used by default. This pool maintains a single SQLite connection per thread that is held open up to a count of five concurrent threads. When more than five threads are used, a cleanup mechanism will dispose of excess unused connections. Two optional pool implementations that may be appropriate for particular SQLite usage scenarios: * the :class:`sqlalchemy.pool.StaticPool` might be appropriate for a multithreaded application using an in-memory database, assuming the threading issues inherent in pysqlite are somehow accomodated for. This pool holds persistently onto a single connection which is never closed, and is returned for all requests. * the :class:`sqlalchemy.pool.NullPool` might be appropriate for an application that makes use of a file-based sqlite database. This pool disables any actual "pooling" behavior, and simply opens and closes real connections corresonding to the :func:`connect()` and :func:`close()` methods. SQLite can "connect" to a particular file with very high efficiency, so this option may actually perform better without the extra overhead of :class:`SingletonThreadPool`. NullPool will of course render a ``:memory:`` connection useless since the database would be lost as soon as the connection is "returned" to the pool. Unicode ------- In contrast to SQLAlchemy's active handling of date and time types for pysqlite, pysqlite's default behavior regarding Unicode is that all strings are returned as Python unicode objects in all cases. So even if the :class:`~sqlalchemy.types.Unicode` type is *not* used, you will still always receive unicode data back from a result set. It is **strongly** recommended that you do use the :class:`~sqlalchemy.types.Unicode` type to represent strings, since it will raise a warning if a non-unicode Python string is passed from the user application. Mixing the usage of non-unicode objects with returned unicode objects can quickly create confusion, particularly when using the ORM as internal data is not always represented by an actual database result string. """ from sqlalchemy.dialects.sqlite.base import SQLiteDialect, DATETIME, DATE from sqlalchemy import schema, exc, pool from sqlalchemy.engine import default from sqlalchemy import types as sqltypes from sqlalchemy import util class _SQLite_pysqliteTimeStamp(DATETIME): def bind_processor(self, dialect): if dialect.native_datetime: return None else: return DATETIME.bind_processor(self, dialect) def result_processor(self, dialect, coltype): if dialect.native_datetime: return None else: return DATETIME.result_processor(self, dialect, coltype) class _SQLite_pysqliteDate(DATE): def bind_processor(self, dialect): if dialect.native_datetime: return None else: return DATE.bind_processor(self, dialect) def result_processor(self, dialect, coltype): if dialect.native_datetime: return None else: return DATE.result_processor(self, dialect, coltype) class SQLiteDialect_pysqlite(SQLiteDialect): default_paramstyle = 'qmark' poolclass = pool.SingletonThreadPool colspecs = util.update_copy( SQLiteDialect.colspecs, { sqltypes.Date:_SQLite_pysqliteDate, sqltypes.TIMESTAMP:_SQLite_pysqliteTimeStamp, } ) # Py3K #description_encoding = None driver = 'pysqlite' def __init__(self, **kwargs): SQLiteDialect.__init__(self, **kwargs) if self.dbapi is not None: sqlite_ver = self.dbapi.version_info if sqlite_ver < (2, 1, 3): util.warn( ("The installed version of pysqlite2 (%s) is out-dated " "and will cause errors in some cases. Version 2.1.3 " "or greater is recommended.") % '.'.join([str(subver) for subver in sqlite_ver])) @classmethod def dbapi(cls): try: from pysqlite2 import dbapi2 as sqlite except ImportError, e: try: from sqlite3 import dbapi2 as sqlite #try the 2.5+ stdlib name. except ImportError: raise e return sqlite def _get_server_version_info(self, connection): return self.dbapi.sqlite_version_info def create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts) def is_disconnect(self, e): return isinstance(e, self.dbapi.ProgrammingError) and "Cannot operate on a closed database." in str(e) dialect = SQLiteDialect_pysqlite
import React from 'react'; import PropTypes from 'prop-types'; import { Svg, Circle as _Circle, Ellipse, G, LinearGradient, RadialGradient, Line, Path, Polygon, Polyline, Rect, Symbol, Text, Use, Defs, Stop, } from 'react-native-svg'; const Loader = props => { const { color, size, ...otherProps } = props; return ( <Svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...otherProps} > <Line x1="12" y1="2" x2="12" y2="6" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="12" y1="18" x2="12" y2="22" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="4.93" y1="4.93" x2="7.76" y2="7.76" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="16.24" y1="16.24" x2="19.07" y2="19.07" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="2" y1="12" x2="6" y2="12" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="18" y1="12" x2="22" y2="12" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="4.93" y1="19.07" x2="7.76" y2="16.24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <Line x1="16.24" y1="7.76" x2="19.07" y2="4.93" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> </Svg> ); }; Loader.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; Loader.defaultProps = { color: 'black', size: '24', }; export default Loader;
import React from 'react'; import {connect} from 'dva'; import moment from 'moment'; import {Alert, Icon, Menu, message, Popover, Select, Badge, Modal, Tooltip} from 'antd'; import {Link} from 'dva/router'; import copy from 'copy-to-clipboard'; import {locales} from '../common/config/data' import intl from 'react-intl-universal'; import Notification from 'Loopr/Notification' import UserAgent from '../common/utils/useragent.js' import {getFormatNum} from "../common/utils/uiFormatter"; import Sockets from '../modules/socket/containers' import {toBig, toHex} from "../common/Loopring/common/formatter"; import {queryTicketCount, queryTicket} from "../common/Loopring/relay/account"; import {getHash} from "../common/Loopring/ethereum/utils"; function Navbar(props) { let selectedKeys = [] if (props.location && props.match) { let route = props.match.path let url = props.location.pathname if (url.indexOf(route) > -1) { selectedKeys.push(route) } } if (props.match) { } const account = props.account; const localeChange = (value) => { props.dispatch({ type: 'locales/setLocale', payload: { locale: value } }); let currency = value.startsWith('en') ? 'USD' : 'CNY' props.dispatch({ type: 'settings/preferenceChange', payload: { language: value, currency: currency, } }) }; const showModal = (payload) => { props.dispatch({ type: 'modals/modalChange', payload: { ...payload, visible: true } }) } const quit = () => { props.dispatch({ type: 'account/deleteAccount', payload: {} }) }; const needUnlockCheck = (payload) => { const state = window.STORE.getState() if (state && state.account && state.account.walletType === 'Address') { props.dispatch({ type: 'modals/modalChange', payload: { id: 'wallet/watchOnlyToUnlock', originalData: payload, pageFrom: '', visible: true } }) } else { showModal(payload) } } const getFlagIcon = (name) => { switch (name) { case "zh-CN": return ( <img style={{height: '18px', width: '24px'}} src={require('../assets/images/flag-ch.png')}/> ) break; case "en-US": return <img style={{height: '18px', width: '24px'}} src={require('../assets/images/flag-en.png')}/> break; default: return name break; } } const localesOptions = locales.map(locale => <Select.Option className="fs16" value={locale.value} key={locale.value}> {getFlagIcon(locale.value)} </Select.Option> ); function copyToClipboard() { if (account.isUnlocked) { copy(account.address) ? Notification.open({ message: intl.get('navbar.subs.copy_success'), type: 'success', size: 'small' }) : Notification.open({message: intl.get('navbar.subs.copy_failed'), type: "error", size: 'small'}) } else { message.warning(intl.get('navbar.subs.copy')) } } const ua = new UserAgent() const getWalletType = () => { if (!window.WALLET_UNLOCK_TYPE) { return intl.get(`wallet.type_lock`) } if (window.WALLET_UNLOCK_TYPE && window.WALLET_UNLOCK_TYPE.toLowerCase() !== 'address') { return intl.get(`wallet.type_${window.WALLET_UNLOCK_TYPE.toLowerCase()}`) } if (window.WALLET_UNLOCK_TYPE && window.WALLET_UNLOCK_TYPE.toLowerCase() === 'address' && window.IS_DEMO_WALLET) { return intl.get(`wallet.type_demo`) } if (window.WALLET_UNLOCK_TYPE && window.WALLET_UNLOCK_TYPE.toLowerCase() === 'address' && !window.IS_DEMO_WALLET) { return intl.get(`wallet.type_${window.WALLET_UNLOCK_TYPE.toLowerCase()}`) } } const subject = encodeURIComponent(intl.get('feedback.email_subject')).replace(/%2B/gi, '+') const body = encodeURIComponent(intl.get('feedback.email_body', { wallet: getWalletType(), os: ua.getOS().name, browser: ua.getBrowser().full, address: account.isUnlocked ? account.address : getWalletType(), })).replace(/%2B/gi, '+') const emailUrl = `mailto:${intl.get('feedback.email_to')}?subject=${subject}&body=${body}`; const claimTicket = async (assets) => { if (!account.walletType || account.walletType.toLowerCase() === 'address') { Notification.open({type: 'warning', message: intl.get('ticket.unlock_tip')}); return; } if (account.walletType.toLowerCase() === 'trezor') { Notification.open({type: 'warning', message: intl.get('ticket.no_trezor')}); return; } const info = Math.floor(new Date().getTime() / 1000).toString(); const sig = await window.WALLET.signMessage(getHash(info)); const quRes = await queryTicket({ sign: { owner: window.WALLET.getAddress(), timestamp: info, v: sig.v, r: toHex(sig.r), s: toHex(sig.s) } }); if (!(quRes.result && quRes.result.name)) { const res = await queryTicketCount(); if (res.error) { Notification.open({type: 'error', message: intl.get('ticket.claim_fail'), description: res.error.message}); return } else { if (res.result >= 500) { Notification.open({type: 'warning', message: intl.get('ticket.claim_over')}); return; } } const asset = assets.getTokenBySymbol('LRC'); const balance = toBig(asset.balance).div(1e18); if (balance.gte(5000)) { showModal({id: 'wallet/claimTicket'}) } else { Notification.open({type: 'warning', message: intl.get('ticket.open_tip', {amount: getFormatNum(5000)})}) } } else { Modal.confirm({ title: intl.get('ticket.already_claim_tip'), content: intl.get('ticket.already_claim_tip_description'), onOk() { showModal({id: 'wallet/claimTicket'}) }, onCancel() { }, }) } }; const accountMenus = ( <div className="fs18"> { account.isUnlocked && <div style={{width: '260px'}}> <div className="row align-items-center gutter-0 pl15 zb-b-b pr15"> <div className="col pr10 pt10 pb10"> <div className="fs14 color-black-2 text-wrap">{account.address}</div> </div> <div className="col-auto zb-b-l pl10 pt10 pb10 "> <a className="fs12 color-primary-1" type="primary" size="small" onClick={copyToClipboard}>{intl.get('navbar.subs.copy')}</a> </div> </div> <div className="row ml0 mr0 zb-b-b navbar-account-grids"> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid"> <a onClick={showModal.bind(this, {id: 'token/receive', symbol: null})}> <i className="grid-icon icon-loopring icon-loopring-receive fs16 color-black-2 d-block"></i> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.receive')}</div> </a> </div> </div> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid"> <a onClick={needUnlockCheck.bind(this, {id: 'token/transfer', item: ''})}> <i className="grid-icon icon-loopring icon-loopring-transfer fs16 color-black-2 d-block"></i> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.send')}</div> </a> </div> </div> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid"> <Link to="/trade" className='color-black-2'> <i className="grid-icon icon-loopring icon-loopring-trade fs16 color-black-2 d-block"></i> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.trade')}</div> </Link> </div> </div> { (account.walletType === 'KeyStore' || account.walletType === 'Mnemonic' || account.walletType === 'PrivateKey') && <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid"> <a onClick={showModal.bind(this, {id: 'wallet/export/keystore'})}> <Icon type="export" className="d-block grid-icon"/> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.export')}</div> </a> </div> </div> } <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="pointer fs14 color-black-2 navbar-account-grid" onClick={showModal.bind(this, {id: 'settings'})}> <Icon type="setting" className="d-block grid-icon"/> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.settings')}</div> </div> </div> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 text-right navbar-account-grid"> <a onClick={showModal.bind(this, {id: 'wallet/airdrop'})} className="color-black-2 d-block text-center"> <div className="grid-title"> <Icon type="gift" className="grid-icon"/> </div> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.airdrop')}</div> </a> </div> </div> {<div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 text-right navbar-account-grid"> <Sockets.Assets render={(props) => { return ( <a onClick={() => claimTicket(props.assets)} className="color-black-2 d-block text-center"> <div className="grid-title"> <Icon type="gift" className="grid-icon"/> </div> <div className="grid-title text-truncate text-nowrap">{intl.get('ticket.claim')}</div> </a> ) }}/> </div> </div>} <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <Tooltip title={intl.get('global.comingsoon')}> <div className="fs14 color-black-2 navbar-account-grid cursor-not-allowed"> <Icon type="question-circle-o" className="d-block grid-icon"/> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.help')}</div> </div> </Tooltip> </div> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid"> <a href={emailUrl} className="color-black-2"> <Icon type="form" className="d-block grid-icon"/> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.feedback')}</div> </a> </div> </div> <div className="col-sm-4 text-center pl0 pr0 zb-b-b"> <div className="fs14 color-black-2 navbar-account-grid cursor-pointer" onClick={quit}> <Icon type="poweroff" className="d-block grid-icon"/> <div className="grid-title text-truncate text-nowrap">{intl.get('navbar.subs.quit')}</div> </div> </div> </div> { false && <div className="zb-b-t bg-grey-50 fs14 p10 pl15 pr15" style={{borderRadius: '0 0 4px 4px'}}> <div className="row align-items-center "> <div className="col"> </div> </div> </div> } </div> } {!account.isUnlocked && <div> <div className="zb-b-b fs14 p10 pl15 pr15"> <div className="row align-items-center"> <div className="col-auto"> <a onClick={showModal.bind(this, {id: 'wallet/unlock', pageFrom: 'Portfolio', targetModalData: {}})} className="color-grey-900"> <Icon type="unlock" className="mr5"/>{intl.get('navbar.subs.unlock')} </a> </div> </div> </div> <div className="zb-b-b fs14 color-grey-900 p10 pl15 pr15"> <a onClick={showModal.bind(this, {id: 'wallet/generate'})} className="color-grey-900"> <Icon type="plus" className="mr5"/>{intl.get('navbar.subs.generate')} </a> </div> <div className="pointer zb-b-b fs14 color-grey-900 p10 pl15 pr15" onClick={showModal.bind(this, {id: 'settings'})}> <Tooltip title={intl.get('global.comingsoon')}> <Icon type="setting" className="mr5"/>{intl.get('navbar.settings')} </Tooltip> </div> <div className="zb-b-b fs14 color-grey-900 p10 pl15 pr15 cursor-not-allowed"> <Tooltip title={intl.get('global.comingsoon')}> <Icon type="question-circle-o" className="mr5"/>{intl.get('navbar.subs.help')} </Tooltip> </div> </div> } </div> ) const VersionTip = ( <div className="" style={{maxWidth: '280px'}}> <div className="p15"> <div className="fs16 color-primary-1">{intl.get('version.title')}</div> <div className="fs12 color-black-1 mt5">{intl.get('version.description')}</div> </div> <div className="zb-b-t"> <div className="row pl10 pr10" style={{padding: '7px 0px'}}> <div className="col fs12 color-black-2">{intl.get('version.version')}</div> <div className="col-auto fs12 color-black-3">{intl.get('version.label')}</div> </div> </div> { false && <div className="zb-b-t"> <div className="row pl10 pr10" style={{padding: '7px 0px'}}> <div className="col fs12 color-black-2">{intl.get('version.update_time')}</div> <div className="col-auto fs12 color-black-3">{window.uiFormatter.getFormatTime(moment().format('x'), 'YYYYMMDD')}</div> </div> </div> } <div className="zb-b-t"> <div className="row pl10 pr10" style={{padding: '7px 0px'}}> <div className="col fs12 color-black-2">{intl.get('version.feedback')}</div> <div className="col-auto fs12 "> <a href={emailUrl} className="color-primary-1"> {intl.get('version.feedback_submit')} <Icon type="right"/> </a> </div> </div> </div> <div className="zb-b-t"> <div className="row pl10 pr10" style={{padding: '7px 0px'}}> <div className="col fs12 color-black-2">{intl.get('version.roadmap_label')}</div> <div className="col-auto fs12 color-black-3 cursor-not-allowed"> {intl.get('version.roadmap_title')} <Icon type="right"/> </div> </div> </div> </div> ) // window.location.href.indexOf('/trade') >= 0 const isTradingPage = window.location.href.indexOf('/trade') > -1 && window.location.href.indexOf('/trades') < 0 return ( <div className="navbar-loopring zb-b-b"> <div className="container"> {window.WALLET_UNLOCK_TYPE && <Sockets.Assets render={(props) => { return ( <Alert type="success" closable className="mt15" description={ <div> {intl.get('ticket.alert_title')}, <a className='color-blue-500 ml5' onClick={() => claimTicket(props.assets)}>{intl.get('ticket.alert_action')}</a> </div> }/> ) }}/>} <div className="row align-items-stretch ml0 mr0 zb-b-l"> <div className="col-auto pl25 pr10 zb-b-r pr" style={{width: '200px'}}> <Link to="/wallet" className="d-block"> <Popover content={VersionTip} title={null} trigger="hover"> <i className="icon-loopring icon-loopring-logo d-block" style={{fontSize: '36px', marginTop: '0px'}}/> <span style={{position: 'absolute', top: '-22px', right: '50px'}}> <span className="navbar-version-badge"> <Badge status="processing" className=""/> {intl.get('version.label')} </span> </span> </Popover> </Link> </div> { isTradingPage && <div className="col-auto pl20"> <Link to="/wallet" className="d-block"> <i className="icon-loopring icon-loopring-coins fs18 color-balck-1"></i> <span className="fs14 ml5">{intl.get('ticker.back_to_wallet')}</span> </Link> </div> } <div className="col"></div> <div className="col-auto"> <Menu theme="light" className="bg-none border-0" mode="horizontal" style={{lineHeight: '64px'}} selectedKeys={selectedKeys} > { false && window.WALLET && window.WALLET.getAddress() && <Menu.Item key="/wallet"> <Link className="fs16 color-black-1" to="/wallet">{intl.get('navbar.wallet')}</Link> </Menu.Item> } { false && window.WALLET && window.WALLET.getAddress() && <Menu.Item key="/trade"> <Link to="/trade" className="fs16 color-black-1">{intl.get('navbar.trade')}</Link> </Menu.Item> } </Menu> </div> <div className="col zb-b-r"></div> { false && <div className="col-auto pl20 pr20 zb-b-r"> <div className="fs16 color-black-1 cursor-pointer"> <Icon onClick={showModal.bind(this, {id: 'userguide'})} type="question-circle-o"/> </div> </div> } { false && <div className="col-auto pl15 pr15 zb-b-r"> <Tooltip title={intl.get('global.comingsoon')}> <div className="fs16 color-black-1 cursor-pointer"> <Icon type="question-circle-o"/> </div> </Tooltip> </div> } <div className="col-auto pl15 pr15 zb-b-r"> <Select showArrow={false} dropdownMatchSelectWidth={false} value={props.locales.locale} onChange={localeChange} className="navbar-language fs16"> {localesOptions} </Select> </div> <div className="col-auto d-flex align-items-center zb-b-r"> <Popover content={accountMenus} title={null} trigger="hover"> { account.address && <div className="fs16"> <div className="text-left" style={{lineHeight: '20px'}}> <div className="fs14 color-black-1"> {window.uiFormatter.getShortAddress(account.address)} &nbsp; <Icon className="ml0 fs10" type="down"/> </div> <div className="row gutter-0" style={{marginTop: '0px'}}> <div className="col"> <Badge status="processing" className=""/> <span className="fs12 color-primary-1">{getWalletType()}</span> </div> <div className="col-auto d-none"> <span onClick={quit} className="fs12 ml5 color-black-1 cursor-pointer">解锁</span> </div> </div> </div> </div> } { !account.address && <span className="fs16 color-black-1"> {intl.get('navbar.account')} <Icon type="down" className="color-grey-400 fs12 ml5"/> </span> } </Popover> </div> </div> </div> </div> ) } export default connect(({locales, account}) => ({locales, account}))(Navbar)
/* eslint-disable max-classes-per-file */ const {Duplex} = require('stream'); const {totalmem} = require('os'); const LinkedList = require('linkedlist'); class CachingStream extends Duplex { #parent; /** * Construct a StreamingCache for efficient memory caching capability * @param {StreamCache} parent A parent streamcache instance to be bound to */ constructor(parent) { super(); // eslint-disable-next-line no-use-before-define if (!(parent && parent instanceof StreamCache)) throw new TypeError('<parent> must be an instance of a StreamCache'); this.#parent = parent; } // eslint-disable-next-line no-underscore-dangle _write(chunk, _encoding, callback) { this.#parent.cacheBytesOn(this, chunk, callback); } // eslint-disable-next-line no-underscore-dangle _read() { this.#parent.readBytesOn(this); } // eslint-disable-next-line no-underscore-dangle _final(cb) { this.#parent.cacheBytesOn(this, null, cb); } } class StreamCache { #store = { items: new WeakMap(), length: 0, reallocate: false, allocBuffer: [], maxCapacity: 209715200, nowarn: false, meta: { max: 0, tickIndex: 0, totalComputed: 0, }, }; /** * Construct a managed StreamCache for efficient memory caching across variable streams * @param {{size: number; reallocate: boolean; nowarn: boolean;}} opts Options * @param [opts.size] Maximum shared buffer size **Default**: `209715200` (200 MiB) * @param [opts.reallocate] Whether or not to reallocate overflowing chunk slices **Default**: `false` * @param [opts.nowarn] Hide memory warning when cache capacity is more than 40% of total memory */ constructor(opts) { opts = opts || {}; if ('nowarn' in opts && opts.nowarn !== undefined) if (typeof opts.nowarn !== 'boolean') throw new TypeError('<opts.nowarn>, if defined must be a valid boolean'); else this.#store.nowarn = opts.nowarn; if ('size' in opts && opts.size !== undefined) if (!Number.isSafeInteger(opts.size)) throw new TypeError('<opts.size>, if defined must be a valid number'); else this.setCapacity(opts.size); if ('reallocate' in opts && opts.reallocate !== undefined) if (typeof opts.reallocate !== 'boolean') throw new TypeError('<opts.reallocate>, if defined must be a valid boolean'); else this.#store.reallocate = opts.reallocate; } new() { const stream = new CachingStream(this); this.#store.items.set(stream, {buffer: new LinkedList(), pendingWrites: 0, pendingReads: 0}); return stream; } #getStack = function getStack(stream, callback) { const stack = this.#store.items.get(stream); if (!stack) { callback(new Error('<stream> input is not a valid child of the StreamCache')); return false; } return stack; }; cacheBytesOn(stream, chunk, callback) { const stack = this.#getStack(stream, callback); if (!stack) return; this.#allocOn(stream, stack, chunk, callback); } readBytesOn(stream) { const stack = this.#getStack(stream, err => stream.destroy(err)); if (!stack) return; stack.pendingReads += 1; if (!this.#readOn(stream, stack)) this.dispatchAllocs(); } #isFull = function isFull() { return this.#store.maxCapacity - this.#store.length <= 0; }; dispatchAllocs() { // synchronously cycle through pending chunks // pop and cache chunks wherever possible let index = 0; while (index < this.#store.allocBuffer.length) { const value = this.#store.allocBuffer[index]; let [{chunk}, overflow] = [value, ,]; const {stream, stack, callback} = value; if (this.#isFull()) { // if cache is full, try freeing some space by resolving pending readers if ( // eslint-disable-next-line no-loop-func !this.#readOn(stream, stack, chunk, () => { // reason for this: // • items are pending to be cached // • can't cache because cache is full // • can't read because buffer is empty // solution: push to the stream directly if there are readers available this.#store.allocBuffer.splice(index, 1); callback(); }) ) index += 1; // move to next item if stack couldn't read chunks } else { const availableCapacity = this.#store.maxCapacity - this.#store.length; if (chunk) { if (chunk.length > availableCapacity) [chunk, overflow] = [chunk.slice(0, availableCapacity), chunk.slice(availableCapacity)]; this.#store.length += chunk.length; if (this.#store.length > this.#store.meta.max) this.#store.meta.max = this.#store.length; this.averageMetaTick(); } stack.buffer.push(chunk); const replacement = overflow && !this.#store.reallocate ? [{stream, stack, chunk: overflow, callback}] : []; const props = this.#store.allocBuffer.splice(index, 1, ...replacement); if (overflow && this.#store.reallocate) this.#store.allocBuffer.push({...props, chunk: overflow}); if (!overflow) callback(); else stack.pendingWrites += 1; if (stack.pendingReads) this.#readOn(stream, stack); } } } #allocOn = function allocOn(stream, stack, chunk, callback) { // || pending | reading ||=|| action || // ||---------|---------||=||--------|| // || true | ~ ||=|| alloc || // || false | true ||=|| push || // || false | false ||=|| alloc || // ||---------|---------||=||--------|| // * pending : the stream has prior chunks waiting to be cached // * reading : the stream already has pending readers // * alloc : wait for cache allocation before callback // * push : bypass the cache and push directly into the stream // * shiftc : bypass the cache and call the next reading handler // * pendingWrites : stream has unread chunks, pending or cached // * pendingReads : stream has unresolved reads if (stack.pendingWrites || !stack.pendingReads) { stack.pendingWrites += 1; this.#store.allocBuffer.push({stream, stack, chunk, callback}); this.dispatchAllocs(); } else { // reason for this: // • stream may have active readers whilst having no pending chunks // • skip the hold-up of writing to the cache. fulfil immediately stream.push(chunk); stack.pendingReads -= 1; callback(); } }; #readOn = function readOn(stream, stack, altChunk, altHandler) { let chunk; let chunkHandler; if (stack.pendingReads && stack.buffer.length) { chunk = stack.buffer.shift(); if (chunk) this.#store.length -= chunk.length; this.averageMetaTick(); } else if (stack.pendingReads && (altChunk || altChunk === null)) { [chunk, chunkHandler] = [altChunk, altHandler]; } else return false; stack.pendingReads -= 1; stack.pendingWrites -= 1; stream.push(chunk); if (typeof chunkHandler === 'function') chunkHandler(); return true; }; averageMetaTick() { this.#store.meta.totalComputed += this.#store.length; this.#store.meta.tickIndex += 1; } getSize() { return this.#store.length; } getCapacity() { return this.#store.maxCapacity; } setCapacity(capacity) { if (!Number.isSafeInteger(capacity)) throw new TypeError('<capacity> must be a valid number'); const totalMem = totalmem(); if (capacity > totalMem) throw new Error(`Capacity [${capacity}] is larger than total available memory [${totalMem}]`); if (!this.#store.nowarn && capacity > totalMem * 0.4) console.warn(`\x1b[33mWARN\x1b[0m: [StreamCache] Capacity is larger than 40% of available memory`); this.#store.maxCapacity = capacity; } getMeta() { this.averageMetaTick(); return { max: this.#store.meta.max, average: this.#store.meta.totalComputed / this.#store.meta.tickIndex, }; } } module.exports = StreamCache; module.exports.CachingStream = CachingStream; module.exports.generator = function buildSingleStreamCache(size) { // you lose control with this option. // cannot change capacity, get metrics or add new children. if (size && typeof size !== 'number') throw new TypeError('<size>, if defined must be a valid number'); const parent = new StreamCache({size}); return parent.new(); }; function test() { // eslint-disable-next-line global-require const fs = require('fs'); // eslint-disable-next-line global-require const path = require('path'); // eslint-disable-next-line global-require const {Readable} = require('stream'); // eslint-disable-next-line global-require const xbytes = require('xbytes'); // eslint-disable-next-line global-require const ProgressBar = require('xprogress'); let SIZE; const [TESTCODE, FILE, size] = process.argv.slice(2); if (['-h', '--help'].some(flag => process.argv.includes(flag))) { console.log('USAGE: streamCache.js <testCode> <inputFile> [cacheSize]'); console.log(''); console.log(' testCode'); console.log(' 1: copy inputFile directly using the stream cache'); console.log(' 2: copy inputFile twice one using cache, the other normally'); console.log(' 3: write zero bytes the size of inputFile from memory to *mask of inputFile'); console.log(' 4: write zero bytes the size of inputFile from /dev/zero to *mask of inputFile'); console.log(''); console.log(' masks'); console.log(' inputFile: examplefile.txt'); console.log(' test [1]: examplefile.test1.txt'); console.log(' test [2]: examplefile.test2.1.txt, examplefile.test2.2.txt'); console.log(' test [3]: examplefile.test3.txt'); console.log(' test [4]: examplefile.test4.txt'); console.log(''); return; } if (!(TESTCODE && FILE)) { console.log('USAGE: streamCache.js <testCode> <inputFile> [cacheSize]'); process.exit(); } if (!['1', '2', '3', '4'].includes(TESTCODE)) throw new Error(`Invalid testCode [${TESTCODE}]. Expected: '1' or '2'`); if (!fs.existsSync(FILE)) throw new Error(`Input file <${FILE}> does not exist`); if (size && (SIZE = parseInt(size, 10)) && SIZE.toString() !== size) throw new Error(`Cache size, if provided must be a valid number `); const FILESIZE = fs.statSync(FILE).size; const {name: FILENAME, ext: EXT, dir: DIR} = path.parse(FILE); const CACHE = new StreamCache({size: SIZE || 419430400}); function randomBytes(LENGTH, devZero) { if (!Number.isSafeInteger(LENGTH)) throw new Error('<size> is not a safe integer'); return devZero ? fs.createReadStream('/dev/zero', {end: LENGTH - 1}) : new Readable({ read() { if ((this.cursor = this.cursor || 0) < LENGTH - 1) { const bytes = Math.min(this.readableHighWaterMark, LENGTH - this.cursor); this.cursor += bytes; this.push(Buffer.alloc(bytes)); } else this.push(null); }, }); } function buildBarGen(LENGTH, ITEMS, initTime) { const barGen = ProgressBar.stream(LENGTH, ProgressBar.slotsByCount(ITEMS), { bar: {separator: '|'}, template: [ ':{label} {cache size: :{cacheSize}} {cache capacity: :{cacheCapacity}}', ' |:{bar:complete}| [:3{slot:percentage}%] (:{slot:eta}) [:{slot:speed(metric=/s)}] [:{slot:size}/:{slot:size:total}]', ' [:{bar}] [:3{percentage}%] (:{eta}) [:{speed(metric=/s)}] [:{size}/:{size:total}]', ], label: 'Writing...', variables: { cacheSize: () => CACHE.getSize(), cacheCapacity: () => CACHE.getCapacity(), }, }).on('complete', () => { const meta = CACHE.getMeta(); barGen.end( [ '[+] Test Complete', ` \u2022 Runtime: ${(Date.now() - initTime) / 1000}s`, ` \u2022 Max Cache Size: (${meta.max}/${CACHE.getCapacity()}) (${xbytes(meta.max, { iec: true, })}/${xbytes(CACHE.getCapacity(), {iec: true})})`, ` \u2022 Average Cache Size: ${meta.average} (${xbytes(meta.average, {iec: true})})`, '', ].join('\n'), ); }); return barGen; } function test1() { const initTime = Date.now(); const OUT = `${DIR}/${FILENAME}.test1${EXT}`; const barGen = buildBarGen(FILESIZE, 1, initTime); fs.createReadStream(FILE) .on('end', () => barGen.print(`1 [ cached]: ${(Date.now() - initTime) / 1000}s [${FILE} => ${OUT}]`)) .pipe(CACHE.new()) .pipe(barGen.next()) .pipe(fs.createWriteStream(OUT)); } function test2() { const initTime = Date.now(); const OUT1 = `${DIR}/${FILENAME}.test2.1${EXT}`; const OUT2 = `${DIR}/${FILENAME}.test2.2${EXT}`; const ITEMS = 4; const barGen = buildBarGen(FILESIZE * ITEMS, ITEMS, initTime); const cacher1 = CACHE.new(); const cacher2 = CACHE.new(); const time1 = Date.now(); fs.createReadStream(FILE) .on('end', () => barGen.print(`{ read} 1 [ cached]: ${(Date.now() - time1) / 1000}s [${FILE} => ${OUT1}]`)) .pipe(barGen.next()) .pipe(cacher1) .pipe(barGen.next()) .on('finish', () => barGen.print(`{write} 1 [ cached]: ${(Date.now() - time1) / 1000}s [${FILE} => ${OUT1}]`)) .pipe(fs.createWriteStream(OUT1)); const time2 = Date.now(); fs.createReadStream(FILE) .on('end', () => barGen.print(`{ read} 2 [uncached]: ${(Date.now() - time2) / 1000}s [${FILE} => ${OUT2}]`)) .pipe(barGen.next()) .pipe(cacher2) .pipe(barGen.next()) .on('finish', () => barGen.print(`{write} 2 [uncached]: ${(Date.now() - time2) / 1000}s [${FILE} => ${OUT2}]`)) .pipe(fs.createWriteStream(OUT2)); } function test3() { const initTime = Date.now(); const OUT = `${DIR}/${FILENAME}.test1${EXT}`; const barGen = buildBarGen(FILESIZE, 1, initTime); randomBytes(FILESIZE) .on('end', () => barGen.print(`1 [ cached]: ${(Date.now() - initTime) / 1000}s [memory => ${OUT}]`)) .pipe(CACHE.new()) .pipe(barGen.next()) .pipe(fs.createWriteStream(OUT)); } function test4() { const initTime = Date.now(); const OUT = `${DIR}/${FILENAME}.test1${EXT}`; const barGen = buildBarGen(FILESIZE, 1, initTime); randomBytes(FILESIZE, true) .on('end', () => barGen.print(`1 [ cached]: ${(Date.now() - initTime) / 1000}s [/dev/zero => ${OUT}]`)) .pipe(CACHE.new()) .pipe(barGen.next()) .pipe(fs.createWriteStream(OUT)); } switch (TESTCODE) { case '1': test1(); break; case '2': test2(); break; case '3': test3(); break; case '4': test4(); break; default: break; } } if (require.main === module) test();
// all static image files export { default as HOME } from "../assets/images/Home.svg"; export { default as PROFILE } from "../assets/images/Profile.svg"; export { default as ELLIPSE } from "../assets/images/Ellipse.svg"; export { default as RED_ELLIPSE } from "../assets/images/Ellipse-red.svg"; export { default as MINER } from "../assets/images/Miner.svg"; export { default as NO_MINE } from "../assets/images/NoMine.svg"; export { default as MINER_TWO } from "../assets/images/Miner-2.svg"; export { default as SMALL_PIN } from "../assets/images/small-pin.svg"; export { default as TENURE } from "../assets/images/Tenure.svg"; export { default as EMAIL } from "../assets/images/Email.svg"; export { default as PHONE } from "../assets/images/Phone.svg"; export { default as PERMIT } from "../assets/images/Permit.svg"; export { default as PENCIL } from "../assets/images/Pencil.svg"; export { default as GROUP_MINERS } from "../assets/images/GroupOfMiners.svg"; export { default as BRAND_PENCIL } from "../assets/images/BrandPencil.svg"; export { default as BRAND_DOCUMENT } from "../assets/images/BrandDocument.svg"; export { default as RED_CLOCK } from "../assets/images/late-clock-red.svg"; export { default as EDIT } from "../assets/images/Edit.svg"; export { default as LOGOUT } from "../assets/images/Logout.svg";
import parseDuration from 'parse-duration'; import { coerceCID } from '../../utils.js'; export default { command: 'stat <key>', describe: 'Print information of a raw IPFS block', builder: { key: { type: 'string', coerce: coerceCID }, 'cid-base': { describe: 'Number base to display CIDs in.', type: 'string', default: 'base58btc' }, timeout: { type: 'string', coerce: parseDuration } }, async handler({ctx, key, cidBase, timeout}) { const {ipfs, print} = ctx; const stats = await ipfs.block.stat(key, { timeout }); const base = await ipfs.bases.getBase(cidBase); print('Key: ' + stats.cid.toString(base.encoder)); print('Size: ' + stats.size); } };
/*! * jQuery JavaScript Library v1.8.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) * Changed by Sergey Davydov <[email protected]>: Remove r20 - %20 replace in rows 7163, 7228 */ (function(A,u){function ec(a){var b=eb[a]={};d.each(a.split(ka),function(c,e){b[e]=true});return b}function fb(a,b,c){if(c===u&&a.nodeType===1){c="data-"+b.replace(fc,"-$1").toLowerCase();c=a.getAttribute(c);if(typeof c==="string"){try{c=c==="true"?true:c==="false"?false:c==="null"?null:+c+""===c?+c:gc.test(c)?d.parseJSON(c):c}catch(e){}d.data(a,b,c)}else c=u}return c}function Sa(a){for(var b in a)if(!(b==="data"&&d.isEmptyObject(a[b])))if(b!=="toJSON")return false;return true}function qa(){return false} function Ca(){return true}function ya(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function gb(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function hb(a,b,c){b=b||0;if(d.isFunction(b))return d.grep(a,function(f,g){return!!b.call(f,g,f)===c});else if(b.nodeType)return d.grep(a,function(f){return f===b===c});else if(typeof b==="string"){var e=d.grep(a,function(f){return f.nodeType===1});if(hc.test(b))return d.filter(b,e,!c);else b=d.filter(b,e)}return d.grep(a,function(f){return d.inArray(f, b)>=0===c})}function ib(a){var b=jb.split("|");a=a.createDocumentFragment();if(a.createElement)for(;b.length;)a.createElement(b.pop());return a}function kb(a,b){if(!(b.nodeType!==1||!d.hasData(a))){var c,e,f;e=d._data(a);var g=d._data(b,e),h=e.events;if(h){delete g.handle;g.events={};for(c in h){e=0;for(f=h[c].length;e<f;e++)d.event.add(b,c,h[c][e])}}if(g.data)g.data=d.extend({},g.data)}}function lb(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes();b.mergeAttributes&&b.mergeAttributes(a); c=b.nodeName.toLowerCase();if(c==="object"){if(b.parentNode)b.outerHTML=a.outerHTML;if(d.support.html5Clone&&a.innerHTML&&!d.trim(b.innerHTML))b.innerHTML=a.innerHTML}else if(c==="input"&&mb.test(a.type)){b.defaultChecked=b.checked=a.checked;if(b.value!==a.value)b.value=a.value}else if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue;else if(c==="script"&&b.text!==a.text)b.text=a.text;b.removeAttribute(d.expando)}}function Da(a){return typeof a.getElementsByTagName!== "undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!=="undefined"?a.querySelectorAll("*"):[]}function nb(a){if(mb.test(a.type))a.defaultChecked=a.checked}function ob(a,b){if(b in a)return b;for(var c=b.charAt(0).toUpperCase()+b.slice(1),e=b,f=pb.length;f--;){b=pb[f]+c;if(b in a)return b}return e}function Ea(a,b){a=b||a;return d.css(a,"display")==="none"||!d.contains(a.ownerDocument,a)}function qb(a,b){for(var c,e,f=[],g=0,h=a.length;g<h;g++){c=a[g];if(c.style){f[g]=d._data(c,"olddisplay"); if(b){if(!f[g]&&c.style.display==="none")c.style.display="";if(c.style.display===""&&Ea(c))f[g]=d._data(c,"olddisplay",rb(c.nodeName))}else{e=Z(c,"display");!f[g]&&e!=="none"&&d._data(c,"olddisplay",e)}}}for(g=0;g<h;g++){c=a[g];if(c.style)if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?f[g]||"":"none"}return a}function sb(a,b,c){return(a=ic.exec(b))?Math.max(0,a[1]-(c||0))+(a[2]||"px"):b}function tb(a,b,c,e){b=c===(e?"border":"content")?4:b==="width"?1:0;for(var f=0;b<4;b+= 2){if(c==="margin")f+=d.css(a,c+la[b],true);if(e){if(c==="content")f-=parseFloat(Z(a,"padding"+la[b]))||0;if(c!=="margin")f-=parseFloat(Z(a,"border"+la[b]+"Width"))||0}else{f+=parseFloat(Z(a,"padding"+la[b]))||0;if(c!=="padding")f+=parseFloat(Z(a,"border"+la[b]+"Width"))||0}}return f}function ub(a,b,c){var e=b==="width"?a.offsetWidth:a.offsetHeight,f=true,g=d.support.boxSizing&&d.css(a,"boxSizing")==="border-box";if(e<=0||e==null){e=Z(a,b);if(e<0||e==null)e=a.style[b];if(Fa.test(e))return e;f=g&& (d.support.boxSizingReliable||e===a.style[b]);e=parseFloat(e)||0}return e+tb(a,b,c||(g?"border":"content"),f)+"px"}function rb(a){if(Ta[a])return Ta[a];var b=d("<"+a+">").appendTo(y.body),c=b.css("display");b.remove();if(c==="none"||c===""){ra=y.body.appendChild(ra||d.extend(y.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!sa||!ra.createElement){sa=(ra.contentWindow||ra.contentDocument).document;sa.write("<!doctype html><html><body>");sa.close()}b=sa.body.appendChild(sa.createElement(a)); c=Z(b,"display");y.body.removeChild(ra)}return Ta[a]=c}function Ua(a,b,c,e){var f;if(d.isArray(b))d.each(b,function(g,h){c||jc.test(a)?e(a,h):Ua(a+"["+(typeof h==="object"?g:"")+"]",h,c,e)});else if(!c&&d.type(b)==="object")for(f in b)Ua(a+"["+f+"]",b[f],c,e);else e(a,b)}function vb(a){return function(b,c){if(typeof b!=="string"){c=b;b="*"}var e,f,g=b.toLowerCase().split(ka),h=0,j=g.length;if(d.isFunction(c))for(;h<j;h++){e=g[h];if(f=/^\+/.test(e))e=e.substr(1)||"*";e=a[e]=a[e]||[];e[f?"unshift": "push"](c)}}}function Ga(a,b,c,e,f,g){f=f||b.dataTypes[0];g=g||{};g[f]=true;var h;f=a[f];for(var j=0,m=f?f.length:0,o=a===Va;j<m&&(o||!h);j++){h=f[j](b,c,e);if(typeof h==="string")if(!o||g[h])h=u;else{b.dataTypes.unshift(h);h=Ga(a,b,c,e,h,g)}}if((o||!h)&&!g["*"])h=Ga(a,b,c,e,"*",g);return h}function wb(a,b){var c,e,f=d.ajaxSettings.flatOptions||{};for(c in b)if(b[c]!==u)(f[c]?a:e||(e={}))[c]=b[c];e&&d.extend(true,a,e)}function xb(){try{return new A.XMLHttpRequest}catch(a){}}function yb(){setTimeout(function(){Ha= u},0);return Ha=d.now()}function kc(a,b){d.each(b,function(c,e){for(var f=(za[c]||[]).concat(za["*"]),g=0,h=f.length;g<h;g++)if(f[g].call(a,c,e))break})}function zb(a,b,c){var e=0,f=Ia.length,g=d.Deferred().always(function(){delete h.elem}),h=function(){var m=Ha||yb();m=Math.max(0,j.startTime+j.duration-m);for(var o=1-(m/j.duration||0),p=0,n=j.tweens.length;p<n;p++)j.tweens[p].run(o);g.notifyWith(a,[j,o,m]);if(o<1&&n)return m;else{g.resolveWith(a,[j]);return false}},j=g.promise({elem:a,props:d.extend({}, b),opts:d.extend(true,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Ha||yb(),duration:c.duration,tweens:[],createTween:function(m,o){var p=d.Tween(a,j.opts,m,o,j.opts.specialEasing[m]||j.opts.easing);j.tweens.push(p);return p},stop:function(m){for(var o=0,p=m?j.tweens.length:0;o<p;o++)j.tweens[o].run(1);m?g.resolveWith(a,[j,m]):g.rejectWith(a,[j,m]);return this}});c=j.props;for(lc(c,j.opts.specialEasing);e<f;e++)if(b=Ia[e].call(j,a,c,j.opts))return b;kc(j,c);d.isFunction(j.opts.start)&& j.opts.start.call(a,j);d.fx.timer(d.extend(h,{anim:j,queue:j.opts.queue,elem:a}));return j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function lc(a,b){var c,e,f,g,h;for(c in a){e=d.camelCase(c);f=b[e];g=a[c];if(d.isArray(g)){f=g[1];g=a[c]=g[0]}if(c!==e){a[e]=g;delete a[c]}if((h=d.cssHooks[e])&&"expand"in h){g=h.expand(g);delete a[e];for(c in g)if(!(c in a)){a[c]=g[c];b[c]=f}}else b[e]=f}}function ba(a,b,c,e,f){return new ba.prototype.init(a, b,c,e,f)}function Ja(a,b){var c,e={height:a},f=0;for(b=b?1:0;f<4;f+=2-b){c=la[f];e["margin"+c]=e["padding"+c]=a}if(b)e.opacity=e.width=a;return e}function Ab(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var Bb,Ka,y=A.document,mc=A.location,nc=A.navigator,oc=A.jQuery,pc=A.$,Cb=Array.prototype.push,ga=Array.prototype.slice,Db=Array.prototype.indexOf,qc=Object.prototype.toString,Wa=Object.prototype.hasOwnProperty,Xa=String.prototype.trim,d=function(a,b){return new d.fn.init(a, b,Bb)},La=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,rc=/\S/,ka=/\s+/,sc=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,tc=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,Eb=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,uc=/^[\],:{}\s]*$/,vc=/(?:^|:|,)(?:\s*\[)+/g,wc=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,xc=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,yc=/^-ms-/,zc=/-([\da-z])/gi,Ac=function(a,b){return(b+"").toUpperCase()},Ma=function(){if(y.addEventListener){y.removeEventListener("DOMContentLoaded", Ma,false);d.ready()}else if(y.readyState==="complete"){y.detachEvent("onreadystatechange",Ma);d.ready()}},Fb={};d.fn=d.prototype={constructor:d,init:function(a,b,c){var e;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((e=a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?[null,a,null]:tc.exec(a))&&(e[1]||!b))if(e[1]){a=(b=b instanceof d?b[0]:b)&&b.nodeType?b.ownerDocument||b:y;a=d.parseHTML(e[1],a,true);Eb.test(e[1])&&d.isPlainObject(b)&& this.attr.call(a,b,true);return d.merge(this,a)}else{if((b=y.getElementById(e[2]))&&b.parentNode){if(b.id!==e[2])return c.find(a);this.length=1;this[0]=b}this.context=y;this.selector=a;return this}else return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);else if(d.isFunction(a))return c.ready(a);if(a.selector!==u){this.selector=a.selector;this.context=a.context}return d.makeArray(a,this)},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return ga.call(this)}, get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){a=d.merge(this.constructor(),a);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+c;else if(b)a.selector=this.selector+"."+b+"("+c+")";return a},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.ready.promise().done(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)}, last:function(){return this.eq(-1)},slice:function(){return this.pushStack(ga.apply(this,arguments),"slice",ga.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:Cb,sort:[].sort,splice:[].splice};d.fn.init.prototype=d.fn;d.extend=d.fn.extend=function(){var a,b,c,e,f,g=arguments[0]||{},h=1,j=arguments.length,m=false;if(typeof g==="boolean"){m=g;g=arguments[1]||{};h=2}if(typeof g!== "object"&&!d.isFunction(g))g={};if(j===h){g=this;--h}for(;h<j;h++)if((a=arguments[h])!=null)for(b in a){c=g[b];e=a[b];if(g!==e)if(m&&e&&(d.isPlainObject(e)||(f=d.isArray(e)))){if(f){f=false;c=c&&d.isArray(c)?c:[]}else c=c&&d.isPlainObject(c)?c:{};g[b]=d.extend(m,c,e)}else if(e!==u)g[b]=e}return g};d.extend({noConflict:function(a){if(A.$===d)A.$=pc;if(a&&A.jQuery===d)A.jQuery=oc;return d},isReady:false,readyWait:1,holdReady:function(a){if(a)d.readyWait++;else d.ready(true)},ready:function(a){if(!(a=== true?--d.readyWait:d.isReady)){if(!y.body)return setTimeout(d.ready,1);d.isReady=true;if(!(a!==true&&--d.readyWait>0)){Ka.resolveWith(y,[d]);d.fn.trigger&&d(y).trigger("ready").off("ready")}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):Fb[qc.call(a)]||"object"},isPlainObject:function(a){if(!a|| d.type(a)!=="object"||a.nodeType||d.isWindow(a))return false;try{if(a.constructor&&!Wa.call(a,"constructor")&&!Wa.call(a.constructor.prototype,"isPrototypeOf"))return false}catch(b){return false}for(var c in a);return c===u||Wa.call(a,c)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw Error(a);},parseHTML:function(a,b,c){var e;if(!a||typeof a!=="string")return null;if(typeof b==="boolean"){c=b;b=0}b=b||y;if(e=Eb.exec(a))return[b.createElement(e[1])];e=d.buildFragment([a], b,c?null:[]);return d.merge([],(e.cacheable?d.clone(e.fragment):e.fragment).childNodes)},parseJSON:function(a){if(!a||typeof a!=="string")return null;a=d.trim(a);if(A.JSON&&A.JSON.parse)return A.JSON.parse(a);if(uc.test(a.replace(wc,"@").replace(xc,"]").replace(vc,"")))return(new Function("return "+a))();d.error("Invalid JSON: "+a)},parseXML:function(a){var b,c;if(!a||typeof a!=="string")return null;try{if(A.DOMParser){c=new DOMParser;b=c.parseFromString(a,"text/xml")}else{b=new ActiveXObject("Microsoft.XMLDOM"); b.async="false";b.loadXML(a)}}catch(e){b=u}if(!b||!b.documentElement||b.getElementsByTagName("parsererror").length)d.error("Invalid XML: "+a);return b},noop:function(){},globalEval:function(a){if(a&&rc.test(a))(A.execScript||function(b){A.eval.call(A,b)})(a)},camelCase:function(a){return a.replace(yc,"ms-").replace(zc,Ac)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var e,f=0,g=a.length,h=g===u||d.isFunction(a);if(c)if(h)for(e in a){if(b.apply(a[e], c)===false)break}else for(;f<g;){if(b.apply(a[f++],c)===false)break}else if(h)for(e in a){if(b.call(a[e],e,a[e])===false)break}else for(;f<g;)if(b.call(a[f],f,a[f++])===false)break;return a},trim:Xa&&!Xa.call("\ufeff\u00a0")?function(a){return a==null?"":Xa.call(a)}:function(a){return a==null?"":(a+"").replace(sc,"")},makeArray:function(a,b){var c,e=b||[];if(a!=null){c=d.type(a);a.length==null||c==="string"||c==="function"||c==="regexp"||d.isWindow(a)?Cb.call(e,a):d.merge(e,a)}return e},inArray:function(a, b,c){var e;if(b){if(Db)return Db.call(b,a,c);e=b.length;for(c=c?c<0?Math.max(0,e+c):c:0;c<e;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=b.length,e=a.length,f=0;if(typeof c==="number")for(;f<c;f++)a[e++]=b[f];else for(;b[f]!==u;)a[e++]=b[f++];a.length=e;return a},grep:function(a,b,c){var e,f=[],g=0,h=a.length;for(c=!!c;g<h;g++){e=!!b(a[g],g);c!==e&&f.push(a[g])}return f},map:function(a,b,c){var e,f,g=[],h=0,j=a.length;if(a instanceof d||j!==u&&typeof j==="number"&&(j>0&&a[0]&& a[j-1]||j===0||d.isArray(a)))for(;h<j;h++){e=b(a[h],h,c);if(e!=null)g[g.length]=e}else for(f in a){e=b(a[f],f,c);if(e!=null)g[g.length]=e}return g.concat.apply([],g)},guid:1,proxy:function(a,b){var c,e;if(typeof b==="string"){c=a[b];b=a;a=c}if(!d.isFunction(a))return u;e=ga.call(arguments,2);c=function(){return a.apply(b,e.concat(ga.call(arguments)))};c.guid=a.guid=a.guid||d.guid++;return c},access:function(a,b,c,e,f,g,h){var j,m=c==null,o=0,p=a.length;if(c&&typeof c==="object"){for(o in c)d.access(a, b,o,c[o],1,g,e);f=1}else if(e!==u){j=h===u&&d.isFunction(e);if(m)if(j){j=b;b=function(n,v,z){return j.call(d(n),z)}}else{b.call(a,e);b=null}if(b)for(;o<p;o++)b(a[o],c,j?e.call(a[o],o,b(a[o],c)):e,h);f=1}return f?a:m?b.call(a):p?b(a[0],c):g},now:function(){return(new Date).getTime()}});d.ready.promise=function(a){if(!Ka){Ka=d.Deferred();if(y.readyState==="complete")setTimeout(d.ready,1);else if(y.addEventListener){y.addEventListener("DOMContentLoaded",Ma,false);A.addEventListener("load",d.ready,false)}else{y.attachEvent("onreadystatechange", Ma);A.attachEvent("onload",d.ready);var b=false;try{b=A.frameElement==null&&y.documentElement}catch(c){}b&&b.doScroll&&function e(){if(!d.isReady){try{b.doScroll("left")}catch(f){return setTimeout(e,50)}d.ready()}}()}}return Ka.promise(a)};d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){Fb["[object "+b+"]"]=b.toLowerCase()});Bb=d(y);var eb={};d.Callbacks=function(a){a=typeof a==="string"?eb[a]||ec(a):d.extend({},a);var b,c,e,f,g,h,j=[],m=!a.once&&[],o=function(n){b= a.memory&&n;c=true;h=f||0;f=0;g=j.length;for(e=true;j&&h<g;h++)if(j[h].apply(n[0],n[1])===false&&a.stopOnFalse){b=false;break}e=false;if(j)if(m)m.length&&o(m.shift());else if(b)j=[];else p.disable()},p={add:function(){if(j){var n=j.length;(function v(z){d.each(z,function(G,Q){var fa=d.type(Q);if(fa==="function"&&(!a.unique||!p.has(Q)))j.push(Q);else Q&&Q.length&&fa!=="string"&&v(Q)})})(arguments);if(e)g=j.length;else if(b){f=n;o(b)}}return this},remove:function(){j&&d.each(arguments,function(n,v){for(var z;(z= d.inArray(v,j,z))>-1;){j.splice(z,1);if(e){z<=g&&g--;z<=h&&h--}}});return this},has:function(n){return d.inArray(n,j)>-1},empty:function(){j=[];return this},disable:function(){j=m=b=u;return this},disabled:function(){return!j},lock:function(){m=u;b||p.disable();return this},locked:function(){return!m},fireWith:function(n,v){v=v||[];v=[n,v.slice?v.slice():v];if(j&&(!c||m))e?m.push(v):o(v);return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!c}};return p};d.extend({Deferred:function(a){var b= [["resolve","done",d.Callbacks("once memory"),"resolved"],["reject","fail",d.Callbacks("once memory"),"rejected"],["notify","progress",d.Callbacks("memory")]],c="pending",e={state:function(){return c},always:function(){f.done(arguments).fail(arguments);return this},then:function(){var g=arguments;return d.Deferred(function(h){d.each(b,function(j,m){var o=m[0],p=g[j];f[m[1]](d.isFunction(p)?function(){var n=p.apply(this,arguments);n&&d.isFunction(n.promise)?n.promise().done(h.resolve).fail(h.reject).progress(h.notify): h[o+"With"](this===f?h:this,[n])}:h[o])});g=null}).promise()},promise:function(g){return g!=null?d.extend(g,e):e}},f={};e.pipe=e.then;d.each(b,function(g,h){var j=h[2],m=h[3];e[h[1]]=j.add;m&&j.add(function(){c=m},b[g^1][2].disable,b[2][2].lock);f[h[0]]=j.fire;f[h[0]+"With"]=j.fireWith});e.promise(f);a&&a.call(f,f);return f},when:function(a){var b=0,c=ga.call(arguments),e=c.length,f=e!==1||a&&d.isFunction(a.promise)?e:0,g=f===1?a:d.Deferred(),h=function(p,n,v){return function(z){n[p]=this;v[p]=arguments.length> 1?ga.call(arguments):z;if(v===j)g.notifyWith(n,v);else--f||g.resolveWith(n,v)}},j,m,o;if(e>1){j=Array(e);m=Array(e);for(o=Array(e);b<e;b++)if(c[b]&&d.isFunction(c[b].promise))c[b].promise().done(h(b,o,c)).fail(g.reject).progress(h(b,m,j));else--f}f||g.resolveWith(o,c);return g.promise()}});d.support=function(){var a,b,c,e,f,g,h,j=y.createElement("div");j.setAttribute("className","t");j.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";b=j.getElementsByTagName("*");c=j.getElementsByTagName("a")[0]; c.style.cssText="top:1px;float:left;opacity:.5";if(!b||!b.length)return{};e=y.createElement("select");f=e.appendChild(y.createElement("option"));b=j.getElementsByTagName("input")[0];a={leadingWhitespace:j.firstChild.nodeType===3,tbody:!j.getElementsByTagName("tbody").length,htmlSerialize:!!j.getElementsByTagName("link").length,style:/top/.test(c.getAttribute("style")),hrefNormalized:c.getAttribute("href")==="/a",opacity:/^0.5/.test(c.style.opacity),cssFloat:!!c.style.cssFloat,checkOn:b.value==="on", optSelected:f.selected,getSetAttribute:j.className!=="t",enctype:!!y.createElement("form").enctype,html5Clone:y.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",boxModel:y.compatMode==="CSS1Compat",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,boxSizingReliable:true,pixelPosition:false};b.checked=true;a.noCloneChecked=b.cloneNode(true).checked;e.disabled=true; a.optDisabled=!f.disabled;try{delete j.test}catch(m){a.deleteExpando=false}if(!j.addEventListener&&j.attachEvent&&j.fireEvent){j.attachEvent("onclick",c=function(){a.noCloneEvent=false});j.cloneNode(true).fireEvent("onclick");j.detachEvent("onclick",c)}b=y.createElement("input");b.value="t";b.setAttribute("type","radio");a.radioValue=b.value==="t";b.setAttribute("checked","checked");b.setAttribute("name","t");j.appendChild(b);c=y.createDocumentFragment();c.appendChild(j.lastChild);a.checkClone=c.cloneNode(true).cloneNode(true).lastChild.checked; a.appendChecked=b.checked;c.removeChild(b);c.appendChild(j);if(j.attachEvent)for(g in{submit:true,change:true,focusin:true}){b="on"+g;h=b in j;if(!h){j.setAttribute(b,"return;");h=typeof j[b]==="function"}a[g+"Bubbles"]=h}d(function(){var o,p,n,v=y.getElementsByTagName("body")[0];if(v){o=y.createElement("div");o.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";v.insertBefore(o,v.firstChild);p=y.createElement("div");o.appendChild(p);p.innerHTML="<table><tr><td></td><td>t</td></tr></table>"; n=p.getElementsByTagName("td");n[0].style.cssText="padding:0;margin:0;border:0;display:none";h=n[0].offsetHeight===0;n[0].style.display="";n[1].style.display="none";a.reliableHiddenOffsets=h&&n[0].offsetHeight===0;p.innerHTML="";p.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%;";a.boxSizing=p.offsetWidth===4;a.doesNotIncludeMarginInBodyOffset=v.offsetTop!==1;if(A.getComputedStyle){a.pixelPosition= (A.getComputedStyle(p,null)||{}).top!=="1%";a.boxSizingReliable=(A.getComputedStyle(p,null)||{width:"4px"}).width==="4px";n=y.createElement("div");n.style.cssText=p.style.cssText="padding:0;margin:0;border:0;display:block;overflow:hidden;";n.style.marginRight=n.style.width="0";p.style.width="1px";p.appendChild(n);a.reliableMarginRight=!parseFloat((A.getComputedStyle(n,null)||{}).marginRight)}if(typeof p.style.zoom!=="undefined"){p.innerHTML="";p.style.cssText="padding:0;margin:0;border:0;display:block;overflow:hidden;width:1px;padding:1px;display:inline;zoom:1"; a.inlineBlockNeedsLayout=p.offsetWidth===3;p.style.display="block";p.style.overflow="visible";p.innerHTML="<div></div>";p.firstChild.style.width="5px";a.shrinkWrapBlocks=p.offsetWidth!==3;o.style.zoom=1}v.removeChild(o)}});c.removeChild(j);b=c=e=f=b=c=j=null;return a}();var gc=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,fc=/([A-Z])/g;d.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true}, hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!Sa(a)},data:function(a,b,c,e){if(d.acceptData(a)){var f=d.expando,g=typeof b==="string",h=a.nodeType,j=h?d.cache:a,m=h?a[f]:a[f]&&f;if(!((!m||!j[m]||!e&&!j[m].data)&&g&&c===u)){if(!m)if(h)a[f]=m=d.deletedIds.pop()||d.guid++;else m=f;if(!j[m]){j[m]={};if(!h)j[m].toJSON=d.noop}if(typeof b==="object"||typeof b==="function")if(e)j[m]=d.extend(j[m],b);else j[m].data=d.extend(j[m].data,b);a=j[m];if(!e){if(!a.data)a.data={}; a=a.data}if(c!==u)a[d.camelCase(b)]=c;if(g){c=a[b];if(c==null)c=a[d.camelCase(b)]}else c=a;return c}}},removeData:function(a,b,c){if(d.acceptData(a)){var e,f,g,h=a.nodeType,j=h?d.cache:a,m=h?a[d.expando]:d.expando;if(j[m]){if(b)if(e=c?j[m]:j[m].data){if(!d.isArray(b))if(b in e)b=[b];else{b=d.camelCase(b);b=b in e?[b]:b.split(" ")}f=0;for(g=b.length;f<g;f++)delete e[b[f]];if(!(c?Sa:d.isEmptyObject)(e))return}if(!c){delete j[m].data;if(!Sa(j[m]))return}if(h)d.cleanData([a],true);else if(d.support.deleteExpando|| j!=j.window)delete j[m];else j[m]=null}}},_data:function(a,b,c){return d.data(a,b,c,true)},acceptData:function(a){var b=a.nodeName&&d.noData[a.nodeName.toLowerCase()];return!b||b!==true&&a.getAttribute("classid")===b}});d.fn.extend({data:function(a,b){var c,e,f,g,h,j=this[0],m=0,o=null;if(a===u){if(this.length){o=d.data(j);if(j.nodeType===1&&!d._data(j,"parsedAttrs")){f=j.attributes;for(h=f.length;m<h;m++){g=f[m].name;if(!g.indexOf("data-")){g=d.camelCase(g.substring(5));fb(j,g,o[g])}}d._data(j,"parsedAttrs", true)}}return o}if(typeof a==="object")return this.each(function(){d.data(this,a)});c=a.split(".",2);c[1]=c[1]?"."+c[1]:"";e=c[1]+"!";return d.access(this,function(p){if(p===u){o=this.triggerHandler("getData"+e,[c[0]]);if(o===u&&j){o=d.data(j,a);o=fb(j,a,o)}return o===u&&c[1]?this.data(c[0]):o}c[1]=p;this.each(function(){var n=d(this);n.triggerHandler("setData"+e,c);d.data(this,a,p);n.triggerHandler("changeData"+e,c)})},null,b,arguments.length>1,null,false)},removeData:function(a){return this.each(function(){d.removeData(this, a)})}});d.extend({queue:function(a,b,c){var e;if(a){b=(b||"fx")+"queue";e=d._data(a,b);if(c)if(!e||d.isArray(c))e=d._data(a,b,d.makeArray(c));else e.push(c);return e||[]}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.length,f=c.shift(),g=d._queueHooks(a,b),h=function(){d.dequeue(a,b)};if(f==="inprogress"){f=c.shift();e--}if(f){b==="fx"&&c.unshift("inprogress");delete g.stop;f.call(a,h,g)}!e&&g&&g.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return d._data(a,c)||d._data(a, c,{empty:d.Callbacks("once memory").add(function(){d.removeData(a,b+"queue",true);d.removeData(a,c,true)})})}});d.fn.extend({queue:function(a,b){var c=2;if(typeof a!=="string"){b=a;a="fx";c--}if(arguments.length<c)return d.queue(this[0],a);return b===u?this:this.each(function(){var e=d.queue(this,a,b);d._queueHooks(this,a);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a;b=b||"fx"; return this.queue(b,function(c,e){var f=setTimeout(c,a);e.stop=function(){clearTimeout(f)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,e=1,f=d.Deferred(),g=this,h=this.length,j=function(){--e||f.resolveWith(g,[g])};if(typeof a!=="string"){b=a;a=u}for(a=a||"fx";h--;)if((c=d._data(g[h],a+"queueHooks"))&&c.empty){e++;c.empty.add(j)}j();return f.promise(b)}});var ha,Gb,Hb,Ib=/[\t\r\n]/g,Bc=/\r/g,Cc=/^(?:button|input)$/i,Dc=/^(?:button|input|object|select|textarea)$/i, Ec=/^a(?:rea|)$/i,Jb=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,Kb=d.support.getSetAttribute;d.fn.extend({attr:function(a,b){return d.access(this,d.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){d.removeAttr(this,a)})},prop:function(a,b){return d.access(this,d.prop,a,b,arguments.length>1)},removeProp:function(a){a=d.propFix[a]||a;return this.each(function(){try{this[a]=u;delete this[a]}catch(b){}})}, addClass:function(a){var b,c,e,f,g,h,j;if(d.isFunction(a))return this.each(function(m){d(this).addClass(a.call(this,m,this.className))});if(a&&typeof a==="string"){b=a.split(ka);c=0;for(e=this.length;c<e;c++){f=this[c];if(f.nodeType===1)if(!f.className&&b.length===1)f.className=a;else{g=" "+f.className+" ";h=0;for(j=b.length;h<j;h++)if(g.indexOf(" "+b[h]+" ")<0)g+=b[h]+" ";f.className=d.trim(g)}}}return this},removeClass:function(a){var b,c,e,f,g,h,j;if(d.isFunction(a))return this.each(function(m){d(this).removeClass(a.call(this, m,this.className))});if(a&&typeof a==="string"||a===u){b=(a||"").split(ka);h=0;for(j=this.length;h<j;h++){e=this[h];if(e.nodeType===1&&e.className){c=(" "+e.className+" ").replace(Ib," ");f=0;for(g=b.length;f<g;f++)for(;c.indexOf(" "+b[f]+" ")>=0;)c=c.replace(" "+b[f]+" "," ");e.className=a?d.trim(c):""}}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(f){d(this).toggleClass(a.call(this,f,this.className,b),b)});return this.each(function(){if(c=== "string")for(var f,g=0,h=d(this),j=b,m=a.split(ka);f=m[g++];){j=e?j:!h.hasClass(f);h[j?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean"){this.className&&d._data(this,"__className__",this.className);this.className=this.className||a===false?"":d._data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,c=this.length;b<c;b++)if(this[b].nodeType===1&&(" "+this[b].className+" ").replace(Ib," ").indexOf(a)>=0)return true;return false},val:function(a){var b,c,e, f=this[0];if(arguments.length){e=d.isFunction(a);return this.each(function(g){var h=d(this);if(this.nodeType===1){g=e?a.call(this,g,h.val()):a;if(g==null)g="";else if(typeof g==="number")g+="";else if(d.isArray(g))g=d.map(g,function(j){return j==null?"":j+""});b=d.valHooks[this.type]||d.valHooks[this.nodeName.toLowerCase()];if(!b||!("set"in b)||b.set(this,g,"value")===u)this.value=g}})}else if(f){if((b=d.valHooks[f.type]||d.valHooks[f.nodeName.toLowerCase()])&&"get"in b&&(c=b.get(f,"value"))!==u)return c; c=f.value;return typeof c==="string"?c.replace(Bc,""):c==null?"":c}}});d.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,e=a.selectedIndex,f=[],g=a.options,h=a.type==="select-one";if(e<0)return null;a=h?e:0;for(c=h?e+1:g.length;a<c;a++){b=g[a];if(b.selected&&(d.support.optDisabled?!b.disabled:b.getAttribute("disabled")===null)&&(!b.parentNode.disabled||!d.nodeName(b.parentNode,"optgroup"))){b=d(b).val();if(h)return b; f.push(b)}}if(h&&!f.length&&g.length)return d(g[e]).val();return f},set:function(a,b){var c=d.makeArray(b);d(a).find("option").each(function(){this.selected=d.inArray(d(this).val(),c)>=0});if(!c.length)a.selectedIndex=-1;return c}}},attrFn:{},attr:function(a,b,c,e){var f,g,h=a.nodeType;if(!(!a||h===3||h===8||h===2)){if(e&&d.isFunction(d.fn[b]))return d(a)[b](c);if(typeof a.getAttribute==="undefined")return d.prop(a,b,c);if(e=h!==1||!d.isXMLDoc(a)){b=b.toLowerCase();g=d.attrHooks[b]||(Jb.test(b)?Gb: ha)}if(c!==u)if(c===null)d.removeAttr(a,b);else if(g&&"set"in g&&e&&(f=g.set(a,c,b))!==u)return f;else{a.setAttribute(b,c+"");return c}else if(g&&"get"in g&&e&&(f=g.get(a,b))!==null)return f;else{f=a.getAttribute(b);return f===null?u:f}}},removeAttr:function(a,b){var c,e,f,g,h=0;if(b&&a.nodeType===1)for(e=b.split(ka);h<e.length;h++)if(f=e[h]){c=d.propFix[f]||f;(g=Jb.test(f))||d.attr(a,f,"");a.removeAttribute(Kb?f:c);if(g&&c in a)a[c]=false}},attrHooks:{type:{set:function(a,b){if(Cc.test(a.nodeName)&& a.parentNode)d.error("type property can't be changed");else if(!d.support.radioValue&&b==="radio"&&d.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b);if(c)a.value=c;return b}}},value:{get:function(a,b){if(ha&&d.nodeName(a,"button"))return ha.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(ha&&d.nodeName(a,"button"))return ha.set(a,b,c);a.value=b}}},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(a,b,c){var e,f,g=a.nodeType;if(!(!a||g===3||g===8||g===2)){if(g!==1||!d.isXMLDoc(a)){b=d.propFix[b]||b;f=d.propHooks[b]}return c!==u?f&&"set"in f&&(e=f.set(a,c,b))!==u?e:a[b]=c:f&&"get"in f&&(e=f.get(a,b))!==null?e:a[b]}},propHooks:{tabIndex:{get:function(a){var b=a.getAttributeNode("tabindex");return b&&b.specified?parseInt(b.value,10):Dc.test(a.nodeName)|| Ec.test(a.nodeName)&&a.href?0:u}}}});Gb={get:function(a,b){var c,e=d.prop(a,b);return e===true||typeof e!=="boolean"&&(c=a.getAttributeNode(b))&&c.nodeValue!==false?b.toLowerCase():u},set:function(a,b,c){if(b===false)d.removeAttr(a,c);else{b=d.propFix[c]||c;if(b in a)a[b]=true;a.setAttribute(c,c.toLowerCase())}return c}};if(!Kb){Hb={name:true,id:true,coords:true};ha=d.valHooks.button={get:function(a,b){var c;return(c=a.getAttributeNode(b))&&(Hb[b]?c.value!=="":c.specified)?c.value:u},set:function(a, b,c){var e=a.getAttributeNode(c);if(!e){e=y.createAttribute(c);a.setAttributeNode(e)}return e.value=b+""}};d.each(["width","height"],function(a,b){d.attrHooks[b]=d.extend(d.attrHooks[b],{set:function(c,e){if(e===""){c.setAttribute(b,"auto");return e}}})});d.attrHooks.contenteditable={get:ha.get,set:function(a,b,c){if(b==="")b="false";ha.set(a,b,c)}}}d.support.hrefNormalized||d.each(["href","src","width","height"],function(a,b){d.attrHooks[b]=d.extend(d.attrHooks[b],{get:function(c){c=c.getAttribute(b, 2);return c===null?u:c}})});if(!d.support.style)d.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||u},set:function(a,b){return a.style.cssText=b+""}};if(!d.support.optSelected)d.propHooks.selected=d.extend(d.propHooks.selected,{get:function(){return null}});if(!d.support.enctype)d.propFix.enctype="encoding";d.support.checkOn||d.each(["radio","checkbox"],function(){d.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}});d.each(["radio","checkbox"], function(){d.valHooks[this]=d.extend(d.valHooks[this],{set:function(a,b){if(d.isArray(b))return a.checked=d.inArray(d(a).val(),b)>=0}})});var Ya=/^(?:textarea|input|select)$/i,Lb=/^([^\.]*|)(?:\.(.+)|)$/,Fc=/(?:^|\s)hover(\.\S+|)\b/,Gc=/^key/,Hc=/^(?:mouse|contextmenu)|click/,Mb=/^(?:focusinfocus|focusoutblur)$/,Nb=function(a){return d.event.special.hover?a:a.replace(Fc,"mouseenter$1 mouseleave$1")};d.event={add:function(a,b,c,e,f){var g,h,j,m,o,p,n,v,z;if(!(a.nodeType===3||a.nodeType===8||!b||!c|| !(g=d._data(a)))){if(c.handler){n=c;c=n.handler;f=n.selector}if(!c.guid)c.guid=d.guid++;j=g.events;if(!j)g.events=j={};h=g.handle;if(!h){g.handle=h=function(G){return typeof d!=="undefined"&&(!G||d.event.triggered!==G.type)?d.event.dispatch.apply(h.elem,arguments):u};h.elem=a}b=d.trim(Nb(b)).split(" ");for(g=0;g<b.length;g++){m=Lb.exec(b[g])||[];o=m[1];p=(m[2]||"").split(".").sort();z=d.event.special[o]||{};o=(f?z.delegateType:z.bindType)||o;z=d.event.special[o]||{};m=d.extend({type:o,origType:m[1], data:e,handler:c,guid:c.guid,selector:f,needsContext:f&&d.expr.match.needsContext.test(f),namespace:p.join(".")},n);v=j[o];if(!v){v=j[o]=[];v.delegateCount=0;if(!z.setup||z.setup.call(a,e,p,h)===false)if(a.addEventListener)a.addEventListener(o,h,false);else a.attachEvent&&a.attachEvent("on"+o,h)}if(z.add){z.add.call(a,m);if(!m.handler.guid)m.handler.guid=c.guid}f?v.splice(v.delegateCount++,0,m):v.push(m);d.event.global[o]=true}a=null}},global:{},remove:function(a,b,c,e,f){var g,h,j,m,o,p,n,v,z,G, Q=d.hasData(a)&&d._data(a);if(Q&&(n=Q.events)){b=d.trim(Nb(b||"")).split(" ");for(g=0;g<b.length;g++){h=Lb.exec(b[g])||[];j=m=h[1];h=h[2];if(j){v=d.event.special[j]||{};j=(e?v.delegateType:v.bindType)||j;z=n[j]||[];o=z.length;h=h?RegExp("(^|\\.)"+h.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(p=0;p<z.length;p++){G=z[p];if((f||m===G.origType)&&(!c||c.guid===G.guid)&&(!h||h.test(G.namespace))&&(!e||e===G.selector||e==="**"&&G.selector)){z.splice(p--,1);G.selector&&z.delegateCount--;v.remove&& v.remove.call(a,G)}}if(z.length===0&&o!==z.length){if(!v.teardown||v.teardown.call(a,h,Q.handle)===false)d.removeEvent(a,j,Q.handle);delete n[j]}}else for(j in n)d.event.remove(a,j+b[g],c,e,true)}if(d.isEmptyObject(n)){delete Q.handle;d.removeData(a,"events",true)}}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(a,b,c,e){if(!(c&&(c.nodeType===3||c.nodeType===8))){var f,g,h,j,m,o,p=a.type||a;h=[];if(!Mb.test(p+d.event.triggered)){if(p.indexOf("!")>=0){p=p.slice(0,-1);f=true}if(p.indexOf(".")>= 0){h=p.split(".");p=h.shift();h.sort()}if(!((!c||d.event.customEvent[p])&&!d.event.global[p])){a=typeof a==="object"?a[d.expando]?a:new d.Event(p,a):new d.Event(p);a.type=p;a.isTrigger=true;a.exclusive=f;a.namespace=h.join(".");a.namespace_re=a.namespace?RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;h=p.indexOf(":")<0?"on"+p:"";if(c){a.result=u;if(!a.target)a.target=c;b=b!=null?d.makeArray(b):[];b.unshift(a);j=d.event.special[p]||{};if(!(j.trigger&&j.trigger.apply(c,b)===false)){o=[[c, j.bindType||p]];if(!e&&!j.noBubble&&!d.isWindow(c)){m=j.delegateType||p;f=Mb.test(m+p)?c:c.parentNode;for(g=c;f;f=f.parentNode){o.push([f,m]);g=f}if(g===(c.ownerDocument||y))o.push([g.defaultView||g.parentWindow||A,m])}for(g=0;g<o.length&&!a.isPropagationStopped();g++){f=o[g][0];a.type=o[g][1];(m=(d._data(f,"events")||{})[a.type]&&d._data(f,"handle"))&&m.apply(f,b);(m=h&&f[h])&&d.acceptData(f)&&m.apply&&m.apply(f,b)===false&&a.preventDefault()}a.type=p;if(!e&&!a.isDefaultPrevented())if((!j._default|| j._default.apply(c.ownerDocument,b)===false)&&!(p==="click"&&d.nodeName(c,"a"))&&d.acceptData(c))if(h&&c[p]&&(p!=="focus"&&p!=="blur"||a.target.offsetWidth!==0)&&!d.isWindow(c)){if(g=c[h])c[h]=null;d.event.triggered=p;c[p]();d.event.triggered=u;if(g)c[h]=g}return a.result}}else{c=d.cache;for(g in c)c[g].events&&c[g].events[p]&&d.event.trigger(a,b,c[g].handle.elem,true)}}}}},dispatch:function(a){a=d.event.fix(a||A.event);var b,c,e,f,g,h,j=(d._data(this,"events")||{})[a.type]||[],m=j.delegateCount, o=ga.call(arguments),p=!a.exclusive&&!a.namespace,n=d.event.special[a.type]||{},v=[];o[0]=a;a.delegateTarget=this;if(!(n.preDispatch&&n.preDispatch.call(this,a)===false)){if(m&&!(a.button&&a.type==="click"))for(c=a.target;c!=this;c=c.parentNode||this)if(c.disabled!==true||a.type!=="click"){f={};g=[];for(b=0;b<m;b++){e=j[b];h=e.selector;if(f[h]===u)f[h]=e.needsContext?d(h,this).index(c)>=0:d.find(h,this,null,[c]).length;f[h]&&g.push(e)}g.length&&v.push({elem:c,matches:g})}j.length>m&&v.push({elem:this, matches:j.slice(m)});for(b=0;b<v.length&&!a.isPropagationStopped();b++){f=v[b];a.currentTarget=f.elem;for(c=0;c<f.matches.length&&!a.isImmediatePropagationStopped();c++){e=f.matches[c];if(p||!a.namespace&&!e.namespace||a.namespace_re&&a.namespace_re.test(e.namespace)){a.data=e.data;a.handleObj=e;e=((d.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,o);if(e!==u){a.result=e;if(e===false){a.preventDefault();a.stopPropagation()}}}}}n.postDispatch&&n.postDispatch.call(this,a);return a.result}}, props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){if(a.which==null)a.which=b.charCode!=null?b.charCode:b.keyCode;return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f= b.button,g=b.fromElement;if(a.pageX==null&&b.clientX!=null){c=a.target.ownerDocument||y;e=c.documentElement;c=c.body;a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0);a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)}if(!a.relatedTarget&&g)a.relatedTarget=g===a.target?b.toElement:g;if(!a.which&&f!==u)a.which=f&1?1:f&2?3:f&4?2:0;return a}},fix:function(a){if(a[d.expando])return a;var b,c,e=a,f=d.event.fixHooks[a.type]|| {},g=f.props?this.props.concat(f.props):this.props;a=d.Event(e);for(b=g.length;b;){c=g[--b];a[c]=e[c]}if(!a.target)a.target=e.srcElement||y;if(a.target.nodeType===3)a.target=a.target.parentNode;a.metaKey=!!a.metaKey;return f.filter?f.filter(a,e):a},special:{load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){if(d.isWindow(this))this.onbeforeunload=c},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}},simulate:function(a, b,c,e){a=d.extend(new d.Event,c,{type:a,isSimulated:true,originalEvent:{}});e?d.event.trigger(a,null,b):d.event.dispatch.call(b,a);a.isDefaultPrevented()&&c.preventDefault()}};d.event.handle=d.event.dispatch;d.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,false)}:function(a,b,c){b="on"+b;if(a.detachEvent){if(typeof a[b]==="undefined")a[b]=null;a.detachEvent(b,c)}};d.Event=function(a,b){if(!(this instanceof d.Event))return new d.Event(a,b);if(a&& a.type){this.originalEvent=a;this.type=a.type;this.isDefaultPrevented=a.defaultPrevented||a.returnValue===false||a.getPreventDefault&&a.getPreventDefault()?Ca:qa}else this.type=a;b&&d.extend(this,b);this.timeStamp=a&&a.timeStamp||d.now();this[d.expando]=true};d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=Ca;var a=this.originalEvent; if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Ca;this.stopPropagation()},isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={delegateType:b,bindType:b,handle:function(c){var e,f=c.relatedTarget,g=c.handleObj;if(!f||f!==this&&!d.contains(this,f)){c.type=g.origType;e=g.handler.apply(this,arguments); c.type=b}return e}}});if(!d.support.submitBubbles)d.event.special.submit={setup:function(){if(d.nodeName(this,"form"))return false;d.event.add(this,"click._submit keypress._submit",function(a){a=a.target;if((a=d.nodeName(a,"input")||d.nodeName(a,"button")?a.form:u)&&!d._data(a,"_submit_attached")){d.event.add(a,"submit._submit",function(b){b._submit_bubble=true});d._data(a,"_submit_attached",true)}})},postDispatch:function(a){if(a._submit_bubble){delete a._submit_bubble;this.parentNode&&!a.isTrigger&& d.event.simulate("submit",this.parentNode,a,true)}},teardown:function(){if(d.nodeName(this,"form"))return false;d.event.remove(this,"._submit")}};if(!d.support.changeBubbles)d.event.special.change={setup:function(){if(Ya.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){d.event.add(this,"propertychange._change",function(a){if(a.originalEvent.propertyName==="checked")this._just_changed=true});d.event.add(this,"click._change",function(a){if(this._just_changed&&!a.isTrigger)this._just_changed= false;d.event.simulate("change",this,a,true)})}return false}d.event.add(this,"beforeactivate._change",function(a){a=a.target;if(Ya.test(a.nodeName)&&!d._data(a,"_change_attached")){d.event.add(a,"change._change",function(b){this.parentNode&&!b.isSimulated&&!b.isTrigger&&d.event.simulate("change",this.parentNode,b,true)});d._data(a,"_change_attached",true)}})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this, arguments)},teardown:function(){d.event.remove(this,"._change");return!Ya.test(this.nodeName)}};d.support.focusinBubbles||d.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,e=function(f){d.event.simulate(b,f.target,d.event.fix(f),true)};d.event.special[b]={setup:function(){c++===0&&y.addEventListener(a,e,true)},teardown:function(){--c===0&&y.removeEventListener(a,e,true)}}});d.fn.extend({on:function(a,b,c,e,f){var g,h;if(typeof a==="object"){if(typeof b!=="string"){c=c||b;b=u}for(h in a)this.on(h, b,c,a[h],f);return this}if(c==null&&e==null){e=b;c=b=u}else if(e==null)if(typeof b==="string"){e=c;c=u}else{e=c;c=b;b=u}if(e===false)e=qa;else if(!e)return this;if(f===1){g=e;e=function(j){d().off(j);return g.apply(this,arguments)};e.guid=g.guid||(g.guid=d.guid++)}return this.each(function(){d.event.add(this,a,e,c,b)})},one:function(a,b,c,e){return this.on(a,b,c,e,1)},off:function(a,b,c){var e;if(a&&a.preventDefault&&a.handleObj){e=a.handleObj;d(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace: e.origType,e.selector,e.handler);return this}if(typeof a==="object"){for(e in a)this.off(e,b,a[e]);return this}if(b===false||typeof b==="function"){c=b;b=u}if(c===false)c=qa;return this.each(function(){d.event.remove(this,a,c,b)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){d(this.context).on(a,this.selector,b,c);return this},die:function(a,b){d(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b, c,e){return this.on(b,a,c,e)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return d.event.trigger(a,b,this[0],true)},toggle:function(a){var b=arguments,c=a.guid||d.guid++,e=0,f=function(g){var h=(d._data(this,"lastToggle"+a.guid)||0)%e;d._data(this,"lastToggle"+a.guid,h+1);g.preventDefault();return b[h].apply(this,arguments)||false}; for(f.guid=c;e<b.length;)b[e++].guid=c;return this.click(f)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});d.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(a,b){d.fn[b]=function(c,e){if(e==null){e=c;c=null}return arguments.length>0?this.on(b,null,c,e):this.trigger(b)};if(Gc.test(b))d.event.fixHooks[b]= d.event.keyHooks;if(Hc.test(b))d.event.fixHooks[b]=d.event.mouseHooks});(function(a,b){function c(i,k,l,r){l=l||[];k=k||N;var s,t,q,x,w=k.nodeType;if(!i||typeof i!=="string")return l;if(w!==1&&w!==9)return[];q=ma(k);if(!q&&!r)if(s=Ic.exec(i))if(x=s[1])if(w===9)if((t=k.getElementById(x))&&t.parentNode){if(t.id===x){l.push(t);return l}}else return l;else{if(k.ownerDocument&&(t=k.ownerDocument.getElementById(x))&&B(k,t)&&t.id===x){l.push(t);return l}}else if(s[2]){H.apply(l,R.call(k.getElementsByTagName(i), 0));return l}else if((x=s[3])&&Ob&&k.getElementsByClassName){H.apply(l,R.call(k.getElementsByClassName(x),0));return l}return G(i.replace(Na,"$1"),k,l,r,q)}function e(i){return function(k){return k.nodeName.toLowerCase()==="input"&&k.type===i}}function f(i){return function(k){var l=k.nodeName.toLowerCase();return(l==="input"||l==="button")&&k.type===i}}function g(i){return $(function(k){k=+k;return $(function(l,r){for(var s,t=i([],l.length,k),q=t.length;q--;)if(l[s=t[q]])l[s]=!(r[s]=l[s])})})}function h(i, k,l){if(i===k)return l;for(i=i.nextSibling;i;){if(i===k)return-1;i=i.nextSibling}return 1}function j(i,k){var l,r,s,t,q,x,w;if(q=W[M][i])return k?0:q.slice(0);q=i;x=[];for(w=I.preFilter;q;){if(!l||(r=Jc.exec(q))){if(r)q=q.slice(r[0].length);x.push(s=[])}l=false;if(r=Kc.exec(q)){s.push(l=new S(r.shift()));q=q.slice(l.length);l.type=r[0].replace(Na," ")}for(t in I.filter)if((r=Oa[t].exec(q))&&(!w[t]||(r=w[t](r,N,true)))){s.push(l=new S(r.shift()));q=q.slice(l.length);l.type=t;l.matches=r}if(!l)break}return k? q.length:q?c.error(i):W(i,x).slice(0)}function m(i,k,l){var r=k.dir,s=l&&k.dir==="parentNode",t=X++;return k.first?function(q,x,w){for(;q=q[r];)if(s||q.nodeType===1)return i(q,x,w)}:function(q,x,w){if(w)for(;q=q[r];){if(s||q.nodeType===1)if(i(q,x,w))return q}else for(var C,E=ca+" "+t+" ",F=E+fa;q=q[r];)if(s||q.nodeType===1)if((C=q[M])===F)return q.sizset;else if(typeof C==="string"&&C.indexOf(E)===0){if(q.sizset)return q}else{q[M]=F;if(i(q,x,w)){q.sizset=true;return q}q.sizset=false}}}function o(i){return i.length> 1?function(k,l,r){for(var s=i.length;s--;)if(!i[s](k,l,r))return false;return true}:i[0]}function p(i,k,l,r,s){for(var t,q=[],x=0,w=i.length,C=k!=null;x<w;x++)if(t=i[x])if(!l||l(t,r,s)){q.push(t);C&&k.push(x)}return q}function n(i,k,l,r,s,t){if(r&&!r[M])r=n(r);if(s&&!s[M])s=n(s,t);return $(function(q,x,w,C){if(!(q&&s)){var E,F,L=[],U=[],aa=x.length;if(!(F=q)){F=k||"*";var V=w.nodeType?[w]:w,P=[];E=0;for(var Pa=V.length;E<Pa;E++)c(F,V[E],P,q);F=P}F=F;V=i&&(q||!k)?p(F,L,i,w,C):F;P=l?s||(q?i:aa||r)? []:x:V;l&&l(V,P,w,C);if(r){F=p(P,U);r(F,[],w,C);for(w=F.length;w--;)if(E=F[w])P[U[w]]=!(V[U[w]]=E)}if(q)for(w=i&&P.length;w--;){if(E=P[w])q[L[w]]=!(x[L[w]]=E)}else{P=p(P===x?P.splice(aa,P.length):P);s?s(null,x,P,C):H.apply(x,P)}}})}function v(i){var k,l,r,s=i.length,t=I.relative[i[0].type];l=t||I.relative[" "];for(var q=t?1:0,x=m(function(E){return E===k},l,true),w=m(function(E){return ta.call(k,E)>-1},l,true),C=[function(E,F,L){return!t&&(L||F!==O)||((k=F).nodeType?x(E,F,L):w(E,F,L))}];q<s;q++)if(l= I.relative[i[q].type])C=[m(o(C),l)];else{l=I.filter[i[q].type].apply(null,i[q].matches);if(l[M]){for(r=++q;r<s;r++)if(I.relative[i[r].type])break;return n(q>1&&o(C),q>1&&i.slice(0,q-1).join("").replace(Na,"$1"),l,q<r&&v(i.slice(q,r)),r<s&&v(i=i.slice(r)),r<s&&i.join(""))}C.push(l)}return o(C)}function z(i,k){var l=k.length>0,r=i.length>0,s=function(t,q,x,w,C){var E,F,L=[],U=0,aa="0",V=t&&[],P=C!=null,Pa=O,Lc=t||r&&I.find.TAG("*",C&&q.parentNode||q),Pb=ca+=Pa==null?1:Math.E;if(P){O=q!==N&&q;fa=s.el}for(;(C= Lc[aa])!=null;aa++){if(r&&C){for(E=0;F=i[E];E++)if(F(C,q,x)){w.push(C);break}if(P){ca=Pb;fa=++s.el}}if(l){if(C=!F&&C)U--;t&&V.push(C)}}U+=aa;if(l&&aa!==U){for(E=0;F=k[E];E++)F(V,L,q,x);if(t){if(U>0)for(;aa--;)V[aa]||L[aa]||(L[aa]=da.call(w));L=p(L)}H.apply(w,L);P&&!t&&L.length>0&&U+k.length>1&&c.uniqueSort(w)}if(P){ca=Pb;O=Pa}return V};s.el=0;return l?$(s):s}function G(i,k,l,r,s){var t,q,x,w,C=j(i);if(!r)if(C.length===1){q=C[0]=C[0].slice(0);if(q.length>2&&(x=q[0]).type==="ID"&&k.nodeType===9&&!s&& I.relative[q[1].type]){k=I.find.ID(x.matches[0].replace(na,""),k,s)[0];if(!k)return l;i=i.slice(q.shift().length)}for(t=Oa.POS.test(i)?-1:q.length-1;t>=0;t--){x=q[t];if(I.relative[w=x.type])break;if(w=I.find[w])if(r=w(x.matches[0].replace(na,""),Za.test(q[0].type)&&k.parentNode||k,s)){q.splice(t,1);i=r.length&&q.join("");if(!i){H.apply(l,R.call(r,0));return l}break}}}ua(i,C)(r,k,s,l,Za.test(i));return l}function Q(){}var fa,ia,I,Y,ma,B,ua,va,D,O,J=true,M=("sizcache"+Math.random()).replace(".",""), S=String,N=a.document,K=N.documentElement,ca=0,X=0,da=[].pop,H=[].push,R=[].slice,ta=[].indexOf||function(i){for(var k=0,l=this.length;k<l;k++)if(this[k]===i)return k;return-1},$=function(i,k){i[M]=k==null||k;return i},T=function(){var i={},k=[];return $(function(l,r){k.push(l)>I.cacheLength&&delete i[k.shift()];return i[l]=r},i)},Aa=T(),W=T(),oa=T();T="\\[[\\x20\\t\\r\\n\\f]*((?:\\\\.|[-\\w]|[^\\x00-\\xa0])+)[\\x20\\t\\r\\n\\f]*(?:([*^$|!~]?=)[\\x20\\t\\r\\n\\f]*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+ "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+".replace("w","w#")+")|)|)[\\x20\\t\\r\\n\\f]*\\]";var Ba=":((?:\\\\.|[-\\w]|[^\\x00-\\xa0])+)(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+T+")|[^:]|\\\\.)*|.*))\\)|)",Na=RegExp("^[\\x20\\t\\r\\n\\f]+|((?:^|[^\\\\])(?:\\\\.)*)[\\x20\\t\\r\\n\\f]+$","g"),Jc=/^[\x20\t\r\n\f]*,[\x20\t\r\n\f]*/,Kc=/^[\x20\t\r\n\f]*([\x20\t\r\n\f>+~])[\x20\t\r\n\f]*/,Mc=RegExp(Ba),Ic=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Za=/[\x20\t\r\n\f]*[+~]/,Nc=/h\d/i,Oc=/input|select|textarea|button/i, na=/\\(?!\\)/g,Oa={ID:/^#((?:\\.|[-\w]|[^\x00-\xa0])+)/,CLASS:/^\.((?:\\.|[-\w]|[^\x00-\xa0])+)/,NAME:/^\[name=['"]?((?:\\.|[-\w]|[^\x00-\xa0])+)['"]?\]/,TAG:RegExp("^("+"(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+".replace("w","w*")+")"),ATTR:RegExp("^"+T),PSEUDO:RegExp("^"+Ba),POS:/:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i,CHILD:RegExp("^:(only|nth|first|last)-child(?:\\([\\x20\\t\\r\\n\\f]*(even|odd|(([+-]|)(\\d*)n|)[\\x20\\t\\r\\n\\f]*(?:([+-]|)[\\x20\\t\\r\\n\\f]*(\\d+)|))[\\x20\\t\\r\\n\\f]*\\)|)", "i"),needsContext:RegExp("^[\\x20\\t\\r\\n\\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\([\\x20\\t\\r\\n\\f]*((?:-\\d)?\\d*)[\\x20\\t\\r\\n\\f]*\\)|)(?=[^-]|$)","i")},ja=function(i){var k=N.createElement("div");try{return i(k)}catch(l){return false}finally{}};T=ja(function(i){i.appendChild(N.createComment(""));return!i.getElementsByTagName("*").length});var Pc=ja(function(i){i.innerHTML="<a href='#'></a>";return i.firstChild&&typeof i.firstChild.getAttribute!=="undefined"&&i.firstChild.getAttribute("href")=== "#"}),Qc=ja(function(i){i.innerHTML="<select></select>";i=typeof i.lastChild.getAttribute("multiple");return i!=="boolean"&&i!=="string"}),Ob=ja(function(i){i.innerHTML="<div class='hidden e'></div><div class='hidden'></div>";if(!i.getElementsByClassName||!i.getElementsByClassName("e").length)return false;i.lastChild.className="e";return i.getElementsByClassName("e").length===2}),Rc=ja(function(i){i.id=M+0;i.innerHTML="<a name='"+M+"'></a><div name='"+M+"'></div>";K.insertBefore(i,K.firstChild);var k= N.getElementsByName&&N.getElementsByName(M).length===2+N.getElementsByName(M+0).length;ia=!N.getElementById(M);K.removeChild(i);return k});try{R.call(K.childNodes,0)}catch(vd){R=function(i){for(var k,l=[];k=this[i];i++)l.push(k);return l}}c.matches=function(i,k){return c(i,null,null,k)};c.matchesSelector=function(i,k){return c(k,null,null,[i]).length>0};Y=c.getText=function(i){var k,l="",r=0;if(k=i.nodeType)if(k===1||k===9||k===11)if(typeof i.textContent==="string")return i.textContent;else for(i= i.firstChild;i;i=i.nextSibling)l+=Y(i);else{if(k===3||k===4)return i.nodeValue}else for(;k=i[r];r++)l+=Y(k);return l};ma=c.isXML=function(i){return(i=i&&(i.ownerDocument||i).documentElement)?i.nodeName!=="HTML":false};B=c.contains=K.contains?function(i,k){var l=i.nodeType===9?i.documentElement:i,r=k&&k.parentNode;return i===r||!!(r&&r.nodeType===1&&l.contains&&l.contains(r))}:K.compareDocumentPosition?function(i,k){return k&&!!(i.compareDocumentPosition(k)&16)}:function(i,k){for(;k=k.parentNode;)if(k=== i)return true;return false};c.attr=function(i,k){var l,r=ma(i);r||(k=k.toLowerCase());if(l=I.attrHandle[k])return l(i);if(r||Qc)return i.getAttribute(k);return(l=i.getAttributeNode(k))?typeof i[k]==="boolean"?i[k]?k:null:l.specified?l.value:null:null};I=c.selectors={cacheLength:50,createPseudo:$,match:Oa,attrHandle:Pc?{}:{href:function(i){return i.getAttribute("href",2)},type:function(i){return i.getAttribute("type")}},find:{ID:ia?function(i,k,l){if(typeof k.getElementById!=="undefined"&&!l)return(i= k.getElementById(i))&&i.parentNode?[i]:[]}:function(i,k,l){if(typeof k.getElementById!=="undefined"&&!l)return(k=k.getElementById(i))?k.id===i||typeof k.getAttributeNode!=="undefined"&&k.getAttributeNode("id").value===i?[k]:b:[]},TAG:T?function(i,k){if(typeof k.getElementsByTagName!=="undefined")return k.getElementsByTagName(i)}:function(i,k){var l=k.getElementsByTagName(i);if(i==="*"){for(var r,s=[],t=0;r=l[t];t++)r.nodeType===1&&s.push(r);return s}return l},NAME:Rc&&function(i,k){if(typeof k.getElementsByName!== "undefined")return k.getElementsByName(name)},CLASS:Ob&&function(i,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(i)}},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(i){i[1]=i[1].replace(na,"");i[3]=(i[4]||i[5]||"").replace(na,"");if(i[2]==="~=")i[3]=" "+i[3]+" ";return i.slice(0,4)},CHILD:function(i){i[1]=i[1].toLowerCase();if(i[1]==="nth"){i[2]|| c.error(i[0]);i[3]=+(i[3]?i[4]+(i[5]||1):2*(i[2]==="even"||i[2]==="odd"));i[4]=+(i[6]+i[7]||i[2]==="odd")}else i[2]&&c.error(i[0]);return i},PSEUDO:function(i){var k,l;if(Oa.CHILD.test(i[0]))return null;if(i[3])i[2]=i[3];else if(k=i[4]){if(Mc.test(k)&&(l=j(k,true))&&(l=k.indexOf(")",k.length-l)-k.length)){k=k.slice(0,l);i[0]=i[0].slice(0,l)}i[2]=k}return i.slice(0,3)}},filter:{ID:ia?function(i){i=i.replace(na,"");return function(k){return k.getAttribute("id")===i}}:function(i){i=i.replace(na,""); return function(k){return(k=typeof k.getAttributeNode!=="undefined"&&k.getAttributeNode("id"))&&k.value===i}},TAG:function(i){if(i==="*")return function(){return true};i=i.replace(na,"").toLowerCase();return function(k){return k.nodeName&&k.nodeName.toLowerCase()===i}},CLASS:function(i){var k=Aa[M][i];k||(k=Aa(i,RegExp("(^|[\\x20\\t\\r\\n\\f])"+i+"([\\x20\\t\\r\\n\\f]|$)")));return function(l){return k.test(l.className||typeof l.getAttribute!=="undefined"&&l.getAttribute("class")||"")}},ATTR:function(i, k,l){return function(r){r=c.attr(r,i);if(r==null)return k==="!=";if(!k)return true;r+="";return k==="="?r===l:k==="!="?r!==l:k==="^="?l&&r.indexOf(l)===0:k==="*="?l&&r.indexOf(l)>-1:k==="$="?l&&r.substr(r.length-l.length)===l:k==="~="?(" "+r+" ").indexOf(l)>-1:k==="|="?r===l||r.substr(0,l.length+1)===l+"-":false}},CHILD:function(i,k,l,r){if(i==="nth")return function(s){var t,q;t=s.parentNode;if(l===1&&r===0)return true;if(t){q=0;for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType===1){q++;if(s===t)break}}q-= r;return q===l||q%l===0&&q/l>=0};return function(s){var t=s;switch(i){case "only":case "first":for(;t=t.previousSibling;)if(t.nodeType===1)return false;if(i==="first")return true;t=s;case "last":for(;t=t.nextSibling;)if(t.nodeType===1)return false;return true}}},PSEUDO:function(i,k){var l,r=I.pseudos[i]||I.setFilters[i.toLowerCase()]||c.error("unsupported pseudo: "+i);if(r[M])return r(k);if(r.length>1){l=[i,i,"",k];return I.setFilters.hasOwnProperty(i.toLowerCase())?$(function(s,t){for(var q,x=r(s, k),w=x.length;w--;){q=ta.call(s,x[w]);s[q]=!(t[q]=x[w])}}):function(s){return r(s,0,l)}}return r}},pseudos:{not:$(function(i){var k=[],l=[],r=ua(i.replace(Na,"$1"));return r[M]?$(function(s,t,q,x){x=r(s,null,x,[]);for(var w=s.length;w--;)if(q=x[w])s[w]=!(t[w]=q)}):function(s,t,q){k[0]=s;r(k,null,q,l);return!l.pop()}}),has:$(function(i){return function(k){return c(i,k).length>0}}),contains:$(function(i){return function(k){return(k.textContent||k.innerText||Y(k)).indexOf(i)>-1}}),enabled:function(i){return i.disabled=== false},disabled:function(i){return i.disabled===true},checked:function(i){var k=i.nodeName.toLowerCase();return k==="input"&&!!i.checked||k==="option"&&!!i.selected},selected:function(i){return i.selected===true},parent:function(i){return!I.pseudos.empty(i)},empty:function(i){var k;for(i=i.firstChild;i;){if(i.nodeName>"@"||(k=i.nodeType)===3||k===4)return false;i=i.nextSibling}return true},header:function(i){return Nc.test(i.nodeName)},text:function(i){var k,l;return i.nodeName.toLowerCase()==="input"&& (k=i.type)==="text"&&((l=i.getAttribute("type"))==null||l.toLowerCase()===k)},radio:e("radio"),checkbox:e("checkbox"),file:e("file"),password:e("password"),image:e("image"),submit:f("submit"),reset:f("reset"),button:function(i){var k=i.nodeName.toLowerCase();return k==="input"&&i.type==="button"||k==="button"},input:function(i){return Oc.test(i.nodeName)},focus:function(i){var k=i.ownerDocument;return i===k.activeElement&&(!k.hasFocus||k.hasFocus())&&!!(i.type||i.href)},active:function(i){return i=== i.ownerDocument.activeElement},first:g(function(){return[0]}),last:g(function(i,k){return[k-1]}),eq:g(function(i,k,l){return[l<0?l+k:l]}),even:g(function(i,k){for(var l=0;l<k;l+=2)i.push(l);return i}),odd:g(function(i,k){for(var l=1;l<k;l+=2)i.push(l);return i}),lt:g(function(i,k,l){for(k=l<0?l+k:l;--k>=0;)i.push(k);return i}),gt:g(function(i,k,l){for(l=l<0?l+k:l;++l<k;)i.push(l);return i})}};va=K.compareDocumentPosition?function(i,k){if(i===k){D=true;return 0}return(!i.compareDocumentPosition||!k.compareDocumentPosition? i.compareDocumentPosition:i.compareDocumentPosition(k)&4)?-1:1}:function(i,k){if(i===k){D=true;return 0}else if(i.sourceIndex&&k.sourceIndex)return i.sourceIndex-k.sourceIndex;var l,r,s=[],t=[];l=i.parentNode;r=k.parentNode;var q=l;if(l===r)return h(i,k);else if(l){if(!r)return 1}else return-1;for(;q;){s.unshift(q);q=q.parentNode}for(q=r;q;){t.unshift(q);q=q.parentNode}l=s.length;r=t.length;for(q=0;q<l&&q<r;q++)if(s[q]!==t[q])return h(s[q],t[q]);return q===l?h(i,t[q],-1):h(s[q],k,1)};[0,0].sort(va); J=!D;c.uniqueSort=function(i){var k,l=1;D=J;i.sort(va);if(D)for(;k=i[l];l++)k===i[l-1]&&i.splice(l--,1);return i};c.error=function(i){throw Error("Syntax error, unrecognized expression: "+i);};ua=c.compile=function(i,k){var l,r=[],s=[],t=oa[M][i];if(!t){k||(k=j(i));for(l=k.length;l--;){t=v(k[l]);t[M]?r.push(t):s.push(t)}t=oa(i,z(s,r))}return t};N.querySelectorAll&&function(){var i,k=G,l=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,s=[":focus"],t=[":active",":focus"],q=K.matchesSelector|| K.mozMatchesSelector||K.webkitMatchesSelector||K.oMatchesSelector||K.msMatchesSelector;ja(function(x){x.innerHTML="<select><option selected=''></option></select>";x.querySelectorAll("[selected]").length||s.push("\\[[\\x20\\t\\r\\n\\f]*(?:checked|disabled|ismap|multiple|readonly|selected|value)");x.querySelectorAll(":checked").length||s.push(":checked")});ja(function(x){x.innerHTML="<p test=''></p>";x.querySelectorAll("[test^='']").length&&s.push("[*^$]=[\\x20\\t\\r\\n\\f]*(?:\"\"|'')");x.innerHTML= "<input type='hidden'/>";x.querySelectorAll(":enabled").length||s.push(":enabled",":disabled")});s=RegExp(s.join("|"));G=function(x,w,C,E,F){if(!E&&!F&&(!s||!s.test(x))){var L,U,aa=true,V=M;U=w;L=w.nodeType===9&&x;if(w.nodeType===1&&w.nodeName.toLowerCase()!=="object"){L=j(x);if(aa=w.getAttribute("id"))V=aa.replace(l,"\\$&");else w.setAttribute("id",V);V="[id='"+V+"'] ";for(U=L.length;U--;)L[U]=V+L[U].join("");U=Za.test(x)&&w.parentNode||w;L=L.join(",")}if(L)try{H.apply(C,R.call(U.querySelectorAll(L), 0));return C}catch(P){}finally{aa||w.removeAttribute("id")}}return k(x,w,C,E,F)};if(q){ja(function(x){i=q.call(x,"div");try{q.call(x,"[test!='']:sizzle");t.push("!=",Ba)}catch(w){}});t=RegExp(t.join("|"));c.matchesSelector=function(x,w){w=w.replace(r,"='$1']");if(!ma(x)&&!t.test(w)&&(!s||!s.test(w)))try{var C=q.call(x,w);if(C||i||x.document&&x.document.nodeType!==11)return C}catch(E){}return c(w,null,null,[x]).length>0}}}();I.pseudos.nth=I.pseudos.eq;I.filters=Q.prototype=I.pseudos;I.setFilters=new Q; c.attr=d.attr;d.find=c;d.expr=c.selectors;d.expr[":"]=d.expr.pseudos;d.unique=c.uniqueSort;d.text=c.getText;d.isXMLDoc=c.isXML;d.contains=c.contains})(A);var Sc=/Until$/,Tc=/^(?:parents|prev(?:Until|All))/,hc=/^.[^:#\[\.,]*$/,Qb=d.expr.match.needsContext,Uc={children:true,contents:true,next:true,prev:true};d.fn.extend({find:function(a){var b,c,e,f,g,h,j=this;if(typeof a!=="string")return d(a).filter(function(){b=0;for(c=j.length;b<c;b++)if(d.contains(j[b],this))return true});h=this.pushStack("","find", a);b=0;for(c=this.length;b<c;b++){e=h.length;d.find(a,this[b],h);if(b>0)for(f=e;f<h.length;f++)for(g=0;g<e;g++)if(h[g]===h[f]){h.splice(f--,1);break}}return h},has:function(a){var b,c=d(a,this),e=c.length;return this.filter(function(){for(b=0;b<e;b++)if(d.contains(this,c[b]))return true})},not:function(a){return this.pushStack(hb(this,a,false),"not",a)},filter:function(a){return this.pushStack(hb(this,a,true),"filter",a)},is:function(a){return!!a&&(typeof a==="string"?Qb.test(a)?d(a,this.context).index(this[0])>= 0:d.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){for(var c,e=0,f=this.length,g=[],h=Qb.test(a)||typeof a!=="string"?d(a,b||this.context):0;e<f;e++)for(c=this[e];c&&c.ownerDocument&&c!==b&&c.nodeType!==11;){if(h?h.index(c)>-1:d.find.matchesSelector(c,a)){g.push(c);break}c=c.parentNode}g=g.length>1?d.unique(g):g;return this.pushStack(g,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a==="string")return d.inArray(this[0], d(a));return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a&&a.nodeType?[a]:a),e=d.merge(this.get(),c);return this.pushStack(ya(c[0])||ya(e[0])?e:d.unique(e))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}});d.fn.andSelf=d.fn.addBack;d.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode", c)},next:function(a){return gb(a,"nextSibling")},prev:function(a){return gb(a,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:d.merge([],a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c);Sc.test(a)||(e=c);if(e&&typeof e==="string")f=d.filter(e,f);f=this.length>1&&!Uc[a]?d.unique(f):f;if(this.length>1&&Tc.test(a))f=f.reverse();return this.pushStack(f,a,ga.call(arguments).join(","))}});d.extend({filter:function(a,b,c){if(c)a=":not("+a+")";return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,b,c){var e=[];for(a=a[b];a&& a.nodeType!==9&&(c===u||a.nodeType!==1||!d(a).is(c));){a.nodeType===1&&e.push(a);a=a[b]}return e},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var jb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Vc=/ jQuery\d+="(?:null|\d+)"/g,$a=/^\s+/,Rb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Sb=/<([\w:]+)/,Wc=/<tbody/i, Xc=/<|&#?\w+;/,Yc=/<(?:script|style|link)/i,Zc=/<(?:script|object|embed|option|style)/i,ab=RegExp("<(?:"+jb+")[\\s/>]","i"),mb=/^(?:checkbox|radio)$/,Tb=/checked\s*(?:[^=]|=\s*.checked.)/i,$c=/\/(java|ecma)script/i,ad=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,ea={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>", "</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ub=ib(y),bb=Ub.appendChild(y.createElement("div"));ea.optgroup=ea.option;ea.tbody=ea.tfoot=ea.colgroup=ea.caption=ea.thead;ea.th=ea.td;if(!d.support.htmlSerialize)ea._default=[1,"X<div>","</div>"];d.fn.extend({text:function(a){return d.access(this,function(b){return b===u?d.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(b))},null,a,arguments.length)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(c){d(this).wrapAll(a.call(this, c))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var c=this;c.firstChild&&c.firstChild.nodeType===1;)c=c.firstChild;return c}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=d.isFunction(a);return this.each(function(c){d(this).wrapAll(b? a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){if(this.nodeType===1||this.nodeType===11)this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){if(this.nodeType===1||this.nodeType===11)this.insertBefore(a,this.firstChild)})},before:function(){if(!ya(this[0]))return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this)});if(arguments.length){var a=d.clean(arguments);return this.pushStack(d.merge(a,this),"before",this.selector)}},after:function(){if(!ya(this[0]))return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});if(arguments.length){var a=d.clean(arguments);return this.pushStack(d.merge(this,a),"after",this.selector)}},remove:function(a,b){for(var c,e=0;(c=this[e])!=null;e++)if(!a||d.filter(a,[c]).length){if(!b&&c.nodeType===1){d.cleanData(c.getElementsByTagName("*")); d.cleanData([c])}c.parentNode&&c.parentNode.removeChild(c)}return this},empty:function(){for(var a,b=0;(a=this[b])!=null;b++)for(a.nodeType===1&&d.cleanData(a.getElementsByTagName("*"));a.firstChild;)a.removeChild(a.firstChild);return this},clone:function(a,b){a=a==null?false:a;b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){return d.access(this,function(b){var c=this[0]||{},e=0,f=this.length;if(b===u)return c.nodeType===1?c.innerHTML.replace(Vc,""):u;if(typeof b=== "string"&&!Yc.test(b)&&(d.support.htmlSerialize||!ab.test(b))&&(d.support.leadingWhitespace||!$a.test(b))&&!ea[(Sb.exec(b)||["",""])[1].toLowerCase()]){b=b.replace(Rb,"<$1></$2>");try{for(;e<f;e++){c=this[e]||{};if(c.nodeType===1){d.cleanData(c.getElementsByTagName("*"));c.innerHTML=b}}c=0}catch(g){}}c&&this.empty().append(b)},null,a,arguments.length)},replaceWith:function(a){if(!ya(this[0])){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))}); if(typeof a!=="string")a=d(a).detach();return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove();b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,true)},domManip:function(a,b,c){a=[].concat.apply([],a);var e,f,g,h=0,j=a[0],m=[],o=this.length;if(!d.support.checkClone&&o>1&&typeof j==="string"&&Tb.test(j))return this.each(function(){d(this).domManip(a,b,c)});if(d.isFunction(j))return this.each(function(p){var n= d(this);a[0]=j.call(this,p,b?n.html():u);n.domManip(a,b,c)});if(this[0]){e=d.buildFragment(a,this,m);g=e.fragment;f=g.firstChild;if(g.childNodes.length===1)g=f;if(f){b=b&&d.nodeName(f,"tr");for(e=e.cacheable||o-1;h<o;h++)c.call(b&&d.nodeName(this[h],"table")?this[h].getElementsByTagName("tbody")[0]||this[h].appendChild(this[h].ownerDocument.createElement("tbody")):this[h],h===e?g:d.clone(g,true,true))}g=f=null;m.length&&d.each(m,function(p,n){if(n.src)d.ajax?d.ajax({url:n.src,type:"GET",dataType:"script", async:false,global:false,"throws":true}):d.error("no ajax");else d.globalEval((n.text||n.textContent||n.innerHTML||"").replace(ad,""));n.parentNode&&n.parentNode.removeChild(n)})}return this}});d.buildFragment=function(a,b,c){var e,f,g,h=a[0];b=b||y;b=!b.nodeType&&b[0]||b;b=b.ownerDocument||b;if(a.length===1&&typeof h==="string"&&h.length<512&&b===y&&h.charAt(0)==="<"&&!Zc.test(h)&&(d.support.checkClone||!Tb.test(h))&&(d.support.html5Clone||!ab.test(h))){f=true;e=d.fragments[h];g=e!==u}if(!e){e=b.createDocumentFragment(); d.clean(a,b,e,c);if(f)d.fragments[h]=g&&e}return{fragment:e,cacheable:f}};d.fragments={};d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e,f=0,g=[];c=d(c);var h=c.length;e=this.length===1&&this[0].parentNode;if((e==null||e&&e.nodeType===11&&e.childNodes.length===1)&&h===1){c[b](this[0]);return this}else{for(;f<h;f++){e=(f>0?this.clone(true):this).get();d(c[f])[b](e);g=g.concat(e)}return this.pushStack(g, a,c.selector)}}});d.extend({clone:function(a,b,c){var e,f,g,h;if(d.support.html5Clone||d.isXMLDoc(a)||!ab.test("<"+a.nodeName+">"))h=a.cloneNode(true);else{bb.innerHTML=a.outerHTML;bb.removeChild(h=bb.firstChild)}if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){lb(a,h);e=Da(a);f=Da(h);for(g=0;e[g];++g)f[g]&&lb(e[g],f[g])}if(b){kb(a,h);if(c){e=Da(a);f=Da(h);for(g=0;e[g];++g)kb(e[g],f[g])}}return h},clean:function(a,b,c,e){var f,g,h,j,m,o,p= b===y&&Ub,n=[];if(!b||typeof b.createDocumentFragment==="undefined")b=y;for(f=0;(h=a[f])!=null;f++){if(typeof h==="number")h+="";if(h){if(typeof h==="string")if(Xc.test(h)){p=p||ib(b);o=b.createElement("div");p.appendChild(o);h=h.replace(Rb,"<$1></$2>");g=(Sb.exec(h)||["",""])[1].toLowerCase();j=ea[g]||ea._default;m=j[0];for(o.innerHTML=j[1]+h+j[2];m--;)o=o.lastChild;if(!d.support.tbody){m=Wc.test(h);j=g==="table"&&!m?o.firstChild&&o.firstChild.childNodes:j[1]==="<table>"&&!m?o.childNodes:[];for(g= j.length-1;g>=0;--g)d.nodeName(j[g],"tbody")&&!j[g].childNodes.length&&j[g].parentNode.removeChild(j[g])}!d.support.leadingWhitespace&&$a.test(h)&&o.insertBefore(b.createTextNode($a.exec(h)[0]),o.firstChild);h=o.childNodes;o.parentNode.removeChild(o)}else h=b.createTextNode(h);h.nodeType?n.push(h):d.merge(n,h)}}if(o)h=o=p=null;if(!d.support.appendChecked)for(f=0;(h=n[f])!=null;f++)if(d.nodeName(h,"input"))nb(h);else typeof h.getElementsByTagName!=="undefined"&&d.grep(h.getElementsByTagName("input"), nb);if(c){a=function(v){if(!v.type||$c.test(v.type))return e?e.push(v.parentNode?v.parentNode.removeChild(v):v):c.appendChild(v)};for(f=0;(h=n[f])!=null;f++)if(!(d.nodeName(h,"script")&&a(h))){c.appendChild(h);if(typeof h.getElementsByTagName!=="undefined"){h=d.grep(d.merge([],h.getElementsByTagName("script")),a);n.splice.apply(n,[f+1,0].concat(h));f+=h.length}}}return n},cleanData:function(a,b){for(var c,e,f,g,h=0,j=d.expando,m=d.cache,o=d.support.deleteExpando,p=d.event.special;(f=a[h])!=null;h++)if(b|| d.acceptData(f))if(c=(e=f[j])&&m[e]){if(c.events)for(g in c.events)p[g]?d.event.remove(f,g):d.removeEvent(f,g,c.handle);if(m[e]){delete m[e];if(o)delete f[j];else if(f.removeAttribute)f.removeAttribute(j);else f[j]=null;d.deletedIds.push(e)}}}});(function(){var a,b;d.uaMatch=function(c){c=c.toLowerCase();c=/(chrome)[ \/]([\w.]+)/.exec(c)||/(webkit)[ \/]([\w.]+)/.exec(c)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(c)||/(msie) ([\w.]+)/.exec(c)||c.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(c)|| [];return{browser:c[1]||"",version:c[2]||"0"}};a=d.uaMatch(nc.userAgent);b={};if(a.browser){b[a.browser]=true;b.version=a.version}if(b.chrome)b.webkit=true;else if(b.webkit)b.safari=true;d.browser=b;d.sub=function(){function c(f,g){return new c.fn.init(f,g)}d.extend(true,c,this);c.superclass=this;c.fn=c.prototype=this();c.fn.constructor=c;c.sub=this.sub;c.fn.init=function(f,g){if(g&&g instanceof d&&!(g instanceof c))g=c(g);return d.fn.init.call(this,f,g,e)};c.fn.init.prototype=c.fn;var e=c(y);return c}})(); var Z,ra,sa,cb=/alpha\([^)]*\)/i,bd=/opacity=([^)]*)/,cd=/^(top|right|bottom|left)$/,dd=/^(none|table(?!-c[ea]).+)/,Vb=/^margin/,ic=RegExp("^("+La+")(.*)$","i"),Fa=RegExp("^("+La+")(?!px)[a-z%]+$","i"),ed=RegExp("^([-+])=("+La+")","i"),Ta={},fd={position:"absolute",visibility:"hidden",display:"block"},Wb={letterSpacing:0,fontWeight:400},la=["Top","Right","Bottom","Left"],pb=["Webkit","O","Moz","ms"],gd=d.fn.toggle;d.fn.extend({css:function(a,b){return d.access(this,function(c,e,f){return f!==u?d.style(c, e,f):d.css(c,e)},a,b,arguments.length>1)},show:function(){return qb(this,true)},hide:function(){return qb(this)},toggle:function(a,b){var c=typeof a==="boolean";if(d.isFunction(a)&&d.isFunction(b))return gd.apply(this,arguments);return this.each(function(){(c?a:Ea(this))?d(this).show():d(this).hide()})}});d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Z(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true, zIndex:true,zoom:true},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,g,h,j=d.camelCase(b),m=a.style;b=d.cssProps[j]||(d.cssProps[j]=ob(m,j));h=d.cssHooks[b]||d.cssHooks[j];if(c!==u){g=typeof c;if(g==="string"&&(f=ed.exec(c))){c=(f[1]+1)*f[2]+parseFloat(d.css(a,b));g="number"}if(!(c==null||g==="number"&&isNaN(c))){if(g==="number"&&!d.cssNumber[j])c+="px";if(!h||!("set"in h)||(c=h.set(a,c,e))!==u)try{m[b]= c}catch(o){}}}else{if(h&&"get"in h&&(f=h.get(a,false,e))!==u)return f;return m[b]}}},css:function(a,b,c,e){var f,g;g=d.camelCase(b);b=d.cssProps[g]||(d.cssProps[g]=ob(a.style,g));if((g=d.cssHooks[b]||d.cssHooks[g])&&"get"in g)f=g.get(a,true,e);if(f===u)f=Z(a,b);if(f==="normal"&&b in Wb)f=Wb[b];if(c||e!==u){a=parseFloat(f);return c||d.isNumeric(a)?a||0:f}return f},swap:function(a,b,c){var e,f={};for(e in b){f[e]=a.style[e];a.style[e]=b[e]}c=c.call(a);for(e in b)a.style[e]=f[e];return c}});if(A.getComputedStyle)Z= function(a,b){var c,e,f,g,h=A.getComputedStyle(a,null),j=a.style;if(h){c=h[b];if(c===""&&!d.contains(a.ownerDocument,a))c=d.style(a,b);if(Fa.test(c)&&Vb.test(b)){e=j.width;f=j.minWidth;g=j.maxWidth;j.minWidth=j.maxWidth=j.width=c;c=h.width;j.width=e;j.minWidth=f;j.maxWidth=g}}return c};else if(y.documentElement.currentStyle)Z=function(a,b){var c,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;if(f==null&&g&&g[b])f=g[b];if(Fa.test(f)&&!cd.test(b)){c=g.left;if(e=a.runtimeStyle&&a.runtimeStyle.left)a.runtimeStyle.left= a.currentStyle.left;g.left=b==="fontSize"?"1em":f;f=g.pixelLeft+"px";g.left=c;if(e)a.runtimeStyle.left=e}return f===""?"auto":f};d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(c,e,f){if(e)return c.offsetWidth===0&&dd.test(Z(c,"display"))?d.swap(c,fd,function(){return ub(c,b,f)}):ub(c,b,f)},set:function(c,e,f){return sb(c,e,f?tb(c,b,f,d.support.boxSizing&&d.css(c,"boxSizing")==="border-box"):0)}}});if(!d.support.opacity)d.cssHooks.opacity={get:function(a,b){return bd.test((b&& a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?0.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,e=a.currentStyle,f=d.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=e&&e.filter||c.filter||"";c.zoom=1;if(b>=1&&d.trim(g.replace(cb,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(e&&!e.filter)return}c.filter=cb.test(g)?g.replace(cb,f):g+" "+f}};d(function(){if(!d.support.reliableMarginRight)d.cssHooks.marginRight={get:function(a,b){return d.swap(a,{display:"inline-block"}, function(){if(b)return Z(a,"marginRight")})}};!d.support.pixelPosition&&d.fn.position&&d.each(["top","left"],function(a,b){d.cssHooks[b]={get:function(c,e){if(e){var f=Z(c,b);return Fa.test(f)?d(c).position()[b]+"px":f}}}})});if(d.expr&&d.expr.filters){d.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!d.support.reliableHiddenOffsets&&(a.style&&a.style.display||Z(a,"display"))==="none"};d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)}}d.each({margin:"", padding:"",border:"Width"},function(a,b){d.cssHooks[a+b]={expand:function(c){var e=typeof c==="string"?c.split(" "):[c],f={};for(c=0;c<4;c++)f[a+la[c]+b]=e[c]||e[c-2]||e[0];return f}};if(!Vb.test(a))d.cssHooks[a+b].set=sb});var jc=/\[\]$/,Xb=/\r?\n/g,hd=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,id=/^(?:select|textarea)/i;d.fn.extend({serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements? d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||id.test(this.nodeName)||hd.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(e){return{name:b.name,value:e.replace(Xb,"\r\n")}}):{name:b.name,value:c.replace(Xb,"\r\n")}}).get()}});d.param=function(a,b){var c,e=[],f=function(g,h){h=d.isFunction(h)?h():h==null?"":h;e[e.length]=encodeURIComponent(g)+"="+encodeURIComponent(h)};if(b===u)b=d.ajaxSettings&& d.ajaxSettings.traditional;if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(c in a)Ua(c,a[c],b,f);return e.join("&")};var wa,pa,jd=/#.*$/,kd=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,ld=/^(?:GET|HEAD)$/,md=/^\/\//,Yb=/\?/,nd=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,od=/([?&])_=[^&]*/,Zb=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,$b=d.fn.load,Va={},ac={},bc=["*/"]+["*"];try{pa=mc.href}catch(wd){pa=y.createElement("a");pa.href="";pa=pa.href}wa= Zb.exec(pa.toLowerCase())||[];d.fn.load=function(a,b,c){if(typeof a!=="string"&&$b)return $b.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,j=a.indexOf(" ");if(j>=0){e=a.slice(j,a.length);a=a.slice(0,j)}if(d.isFunction(b)){c=b;b=u}else if(b&&typeof b==="object")f="POST";d.ajax({url:a,type:f,dataType:"html",data:b,complete:function(m,o){if(c)h.each(c,g||[m.responseText,o,m])}}).done(function(m){g=arguments;h.html(e?d("<div>").append(m.replace(nd,"")).find(e):m)});return this};d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a,b){d.fn[b]=function(c){return this.on(b,c)}});d.each(["get","post"],function(a,b){d[b]=function(c,e,f,g){if(d.isFunction(e)){g=g||f;f=e;e=u}return d.ajax({type:b,url:c,data:e,success:f,dataType:g})}});d.extend({getScript:function(a,b){return d.get(a,u,b,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){if(b)wb(a,d.ajaxSettings);else{b=a;a=d.ajaxSettings}wb(a,b);return a},ajaxSettings:{url:pa,isLocal:/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/.test(wa[1]), global:true,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bc},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":A.String,"text html":true,"text json":d.parseJSON,"text xml":d.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:vb(Va),ajaxTransport:vb(ac), ajax:function(a,b){function c(D,O,J,M){var S,N,K,ca,X=O;if(Y!==2){Y=2;j&&clearTimeout(j);h=u;f=M||"";B.readyState=D>0?4:0;if(J){ca=n;M=B;var da,H,R,ta,$=ca.contents,T=ca.dataTypes,Aa=ca.responseFields;for(H in Aa)if(H in J)M[Aa[H]]=J[H];for(;T[0]==="*";){T.shift();if(da===u)da=ca.mimeType||M.getResponseHeader("content-type")}if(da)for(H in $)if($[H]&&$[H].test(da)){T.unshift(H);break}if(T[0]in J)R=T[0];else{for(H in J){if(!T[0]||ca.converters[H+" "+T[0]]){R=H;break}ta||(ta=H)}R=R||ta}if(R){R!==T[0]&& T.unshift(R);ca=J[R]}else ca=void 0}if(D>=200&&D<300||D===304){if(n.ifModified){if(J=B.getResponseHeader("Last-Modified"))d.lastModified[e]=J;if(J=B.getResponseHeader("Etag"))d.etag[e]=J}if(D===304){X="notmodified";S=true}else{a:{N=n;K=ca;var W,oa;X=N.dataTypes.slice();da=X[0];H={};R=0;if(N.dataFilter)K=N.dataFilter(K,N.dataType);if(X[1])for(W in N.converters)H[W.toLowerCase()]=N.converters[W];for(;J=X[++R];)if(J!=="*"){if(da!=="*"&&da!==J){W=H[da+" "+J]||H["* "+J];if(!W)for(oa in H){S=oa.split(" "); if(S[1]===J)if(W=H[da+" "+S[0]]||H["* "+S[0]]){if(W===true)W=H[oa];else if(H[oa]!==true){J=S[0];X.splice(R--,0,J)}break}}if(W!==true)if(W&&N["throws"])K=W(K);else try{K=W(K)}catch(Ba){S={state:"parsererror",error:W?Ba:"No conversion from "+da+" to "+J};break a}}da=J}S={state:"success",data:K}}X=S.state;N=S.data;K=S.error;S=!K}}else{K=X;if(!X||D){X="error";if(D<0)D=0}}B.status=D;B.statusText=(O||X)+"";S?G.resolveWith(v,[N,X,B]):G.rejectWith(v,[B,X,K]);B.statusCode(fa);fa=u;if(o)z.trigger("ajax"+(S? "Success":"Error"),[B,n,S?N:K]);Q.fireWith(v,[B,X]);if(o){z.trigger("ajaxComplete",[B,n]);--d.active||d.event.trigger("ajaxStop")}}}if(typeof a==="object"){b=a;a=u}b=b||{};var e,f,g,h,j,m,o,p,n=d.ajaxSetup({},b),v=n.context||n,z=v!==n&&(v.nodeType||v instanceof d)?d(v):d.event,G=d.Deferred(),Q=d.Callbacks("once memory"),fa=n.statusCode||{},ia={},I={},Y=0,ma="canceled",B={readyState:0,setRequestHeader:function(D,O){if(!Y){var J=D.toLowerCase();D=I[J]=I[J]||D;ia[D]=O}return this},getAllResponseHeaders:function(){return Y=== 2?f:null},getResponseHeader:function(D){var O;if(Y===2){if(!g)for(g={};O=kd.exec(f);)g[O[1].toLowerCase()]=O[2];O=g[D.toLowerCase()]}return O===u?null:O},overrideMimeType:function(D){if(!Y)n.mimeType=D;return this},abort:function(D){D=D||ma;h&&h.abort(D);c(0,D);return this}};G.promise(B);B.success=B.done;B.error=B.fail;B.complete=Q.add;B.statusCode=function(D){if(D){var O;if(Y<2)for(O in D)fa[O]=[fa[O],D[O]];else{O=D[B.status];B.always(O)}}return this};n.url=((a||n.url)+"").replace(jd,"").replace(md, wa[1]+"//");n.dataTypes=d.trim(n.dataType||"*").toLowerCase().split(ka);if(n.crossDomain==null){m=Zb.exec(n.url.toLowerCase())||false;n.crossDomain=m&&m.join(":")+(m[3]?"":m[1]==="http:"?80:443)!==wa.join(":")+(wa[3]?"":wa[1]==="http:"?80:443)}if(n.data&&n.processData&&typeof n.data!=="string")n.data=d.param(n.data,n.traditional);Ga(Va,n,b,B);if(Y===2)return B;o=n.global;n.type=n.type.toUpperCase();n.hasContent=!ld.test(n.type);o&&d.active++===0&&d.event.trigger("ajaxStart");if(!n.hasContent){if(n.data){n.url+= (Yb.test(n.url)?"&":"?")+n.data;delete n.data}e=n.url;if(n.cache===false){m=d.now();var ua=n.url.replace(od,"$1_="+m);n.url=ua+(ua===n.url?(Yb.test(n.url)?"&":"?")+"_="+m:"")}}if(n.data&&n.hasContent&&n.contentType!==false||b.contentType)B.setRequestHeader("Content-Type",n.contentType);if(n.ifModified){e=e||n.url;d.lastModified[e]&&B.setRequestHeader("If-Modified-Since",d.lastModified[e]);d.etag[e]&&B.setRequestHeader("If-None-Match",d.etag[e])}B.setRequestHeader("Accept",n.dataTypes[0]&&n.accepts[n.dataTypes[0]]? n.accepts[n.dataTypes[0]]+(n.dataTypes[0]!=="*"?", "+bc+"; q=0.01":""):n.accepts["*"]);for(p in n.headers)B.setRequestHeader(p,n.headers[p]);if(n.beforeSend&&(n.beforeSend.call(v,B,n)===false||Y===2))return B.abort();ma="abort";for(p in{success:1,error:1,complete:1})B[p](n[p]);if(h=Ga(ac,n,b,B)){B.readyState=1;o&&z.trigger("ajaxSend",[B,n]);if(n.async&&n.timeout>0)j=setTimeout(function(){B.abort("timeout")},n.timeout);try{Y=1;h.send(ia,c)}catch(va){if(Y<2)c(-1,va);else throw va;}}else c(-1,"No Transport"); return B},active:0,lastModified:{},etag:{}});var cc=[],pd=/\?/,Qa=/(=)\?(?=&|$)|\?\?/,qd=d.now();d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cc.pop()||d.expando+"_"+qd++;this[a]=true;return a}});d.ajaxPrefilter("json jsonp",function(a,b,c){var e,f,g,h=a.data,j=a.url,m=a.jsonp!==false,o=m&&Qa.test(j),p=m&&!o&&typeof h==="string"&&!(a.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qa.test(h);if(a.dataTypes[0]==="jsonp"||o||p){e=a.jsonpCallback=d.isFunction(a.jsonpCallback)? a.jsonpCallback():a.jsonpCallback;f=A[e];if(o)a.url=j.replace(Qa,"$1"+e);else if(p)a.data=h.replace(Qa,"$1"+e);else if(m)a.url+=(pd.test(j)?"&":"?")+a.jsonp+"="+e;a.converters["script json"]=function(){g||d.error(e+" was not called");return g[0]};a.dataTypes[0]="json";A[e]=function(){g=arguments};c.always(function(){A[e]=f;if(a[e]){a.jsonpCallback=b.jsonpCallback;cc.push(e)}g&&d.isFunction(f)&&f(g[0]);g=f=u});return"script"}});d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}});d.ajaxPrefilter("script",function(a){if(a.cache===u)a.cache=false;if(a.crossDomain){a.type="GET";a.global=false}});d.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||y.getElementsByTagName("head")[0]||y.documentElement;return{send:function(e,f){b=y.createElement("script");b.async="async";if(a.scriptCharset)b.charset=a.scriptCharset;b.src=a.url;b.onload=b.onreadystatechange= function(g,h){if(h||!b.readyState||/loaded|complete/.test(b.readyState)){b.onload=b.onreadystatechange=null;c&&b.parentNode&&c.removeChild(b);b=u;h||f(200,"success")}};c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(0,1)}}}});var xa,db=A.ActiveXObject?function(){for(var a in xa)xa[a](0,1)}:false,rd=0;d.ajaxSettings.xhr=A.ActiveXObject?function(){var a;if(!(a=!this.isLocal&&xb()))a:{try{a=new A.ActiveXObject("Microsoft.XMLHTTP");break a}catch(b){}a=void 0}return a}:xb;(function(a){d.extend(d.support, {ajax:!!a,cors:!!a&&"withCredentials"in a})})(d.ajaxSettings.xhr());d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var b;return{send:function(c,e){var f,g,h=a.xhr();a.username?h.open(a.type,a.url,a.async,a.username,a.password):h.open(a.type,a.url,a.async);if(a.xhrFields)for(g in a.xhrFields)h[g]=a.xhrFields[g];a.mimeType&&h.overrideMimeType&&h.overrideMimeType(a.mimeType);if(!a.crossDomain&&!c["X-Requested-With"])c["X-Requested-With"]="XMLHttpRequest";try{for(g in c)h.setRequestHeader(g, c[g])}catch(j){}h.send(a.hasContent&&a.data||null);b=function(m,o){var p,n,v,z,G;try{if(b&&(o||h.readyState===4)){b=u;if(f){h.onreadystatechange=d.noop;db&&delete xa[f]}if(o)h.readyState!==4&&h.abort();else{p=h.status;v=h.getAllResponseHeaders();z={};if((G=h.responseXML)&&G.documentElement)z.xml=G;try{z.text=h.responseText}catch(Q){}try{n=h.statusText}catch(fa){n=""}if(!p&&a.isLocal&&!a.crossDomain)p=z.text?200:404;else if(p===1223)p=204}}}catch(ia){o||e(-1,ia)}z&&e(p,n,z,v)};if(a.async)if(h.readyState=== 4)setTimeout(b,0);else{f=++rd;if(db){if(!xa){xa={};d(A).unload(db)}xa[f]=b}h.onreadystatechange=b}else b()},abort:function(){b&&b(0,1)}}}});var Ha,Ra,sd=/^(?:toggle|show|hide)$/,td=RegExp("^(?:([-+])=|)("+La+")([a-z%]*)$","i"),ud=/queueHooks$/,Ia=[function(a,b,c){var e,f,g,h,j,m,o=this,p=a.style,n={},v=[],z=a.nodeType&&Ea(a);if(!c.queue){j=d._queueHooks(a,"fx");if(j.unqueued==null){j.unqueued=0;m=j.empty.fire;j.empty.fire=function(){j.unqueued||m()}}j.unqueued++;o.always(function(){o.always(function(){j.unqueued--; d.queue(a,"fx").length||j.empty.fire()})})}if(a.nodeType===1&&("height"in b||"width"in b)){c.overflow=[p.overflow,p.overflowX,p.overflowY];if(d.css(a,"display")==="inline"&&d.css(a,"float")==="none")if(!d.support.inlineBlockNeedsLayout||rb(a.nodeName)==="inline")p.display="inline-block";else p.zoom=1}if(c.overflow){p.overflow="hidden";d.support.shrinkWrapBlocks||o.done(function(){p.overflow=c.overflow[0];p.overflowX=c.overflow[1];p.overflowY=c.overflow[2]})}for(e in b){f=b[e];if(sd.exec(f)){delete b[e]; if(f!==(z?"hide":"show"))v.push(e)}}if(f=v.length){g=d._data(a,"fxshow")||d._data(a,"fxshow",{});z?d(a).show():o.done(function(){d(a).hide()});o.done(function(){var G;d.removeData(a,"fxshow",true);for(G in n)d.style(a,G,n[G])});for(e=0;e<f;e++){b=v[e];h=o.createTween(b,z?g[b]:0);n[b]=g[b]||d.style(a,b);if(!(b in g)){g[b]=h.start;if(z){h.end=h.start;h.start=b==="width"||b==="height"?1:0}}}}}],za={"*":[function(a,b){var c,e,f=this.createTween(a,b),g=td.exec(b),h=f.cur(),j=+h||0,m=1,o=20;if(g){c=+g[2]; e=g[3]||(d.cssNumber[a]?"":"px");if(e!=="px"&&j){j=d.css(f.elem,a,true)||c||1;do{m=m||".5";j/=m;d.style(f.elem,a,j+e)}while(m!==(m=f.cur()/h)&&m!==1&&--o)}f.unit=e;f.start=j;f.end=g[1]?j+(g[1]+1)*c:c}return f}]};d.Animation=d.extend(zb,{tweener:function(a,b){if(d.isFunction(a)){b=a;a=["*"]}else a=a.split(" ");for(var c,e=0,f=a.length;e<f;e++){c=a[e];za[c]=za[c]||[];za[c].unshift(b)}},prefilter:function(a,b){b?Ia.unshift(a):Ia.push(a)}});d.Tween=ba;ba.prototype={constructor:ba,init:function(a,b,c, e,f,g){this.elem=a;this.prop=c;this.easing=f||"swing";this.options=b;this.start=this.now=this.cur();this.end=e;this.unit=g||(d.cssNumber[c]?"":"px")},cur:function(){var a=ba.propHooks[this.prop];return a&&a.get?a.get(this):ba.propHooks._default.get(this)},run:function(a){var b,c=ba.propHooks[this.prop];this.pos=this.options.duration?b=d.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):b=a;this.now=(this.end-this.start)*b+this.start;this.options.step&&this.options.step.call(this.elem, this.now,this);c&&c.set?c.set(this):ba.propHooks._default.set(this);return this}};ba.prototype.init.prototype=ba.prototype;ba.propHooks={_default:{get:function(a){if(a.elem[a.prop]!=null&&(!a.elem.style||a.elem.style[a.prop]==null))return a.elem[a.prop];a=d.css(a.elem,a.prop,false,"");return!a||a==="auto"?0:a},set:function(a){if(d.fx.step[a.prop])d.fx.step[a.prop](a);else if(a.elem.style&&(a.elem.style[d.cssProps[a.prop]]!=null||d.cssHooks[a.prop]))d.style(a.elem,a.prop,a.now+a.unit);else a.elem[a.prop]= a.now}}};ba.propHooks.scrollTop=ba.propHooks.scrollLeft={set:function(a){if(a.elem.nodeType&&a.elem.parentNode)a.elem[a.prop]=a.now}};d.each(["toggle","show","hide"],function(a,b){var c=d.fn[b];d.fn[b]=function(e,f,g){return e==null||typeof e==="boolean"||!a&&d.isFunction(e)&&d.isFunction(f)?c.apply(this,arguments):this.animate(Ja(b,true),e,f,g)}});d.fn.extend({fadeTo:function(a,b,c,e){return this.filter(Ea).css("opacity",0).show().end().animate({opacity:b},a,c,e)},animate:function(a,b,c,e){var f= d.isEmptyObject(a),g=d.speed(b,c,e);b=function(){var h=zb(this,d.extend({},a),g);f&&h.stop(true)};return f||g.queue===false?this.each(b):this.queue(g.queue,b)},stop:function(a,b,c){var e=function(f){var g=f.stop;delete f.stop;g(c)};if(typeof a!=="string"){c=b;b=a;a=u}if(b&&a!==false)this.queue(a||"fx",[]);return this.each(function(){var f=true,g=a!=null&&a+"queueHooks",h=d.timers,j=d._data(this);if(g)j[g]&&j[g].stop&&e(j[g]);else for(g in j)j[g]&&j[g].stop&&ud.test(g)&&e(j[g]);for(g=h.length;g--;)if(h[g].elem=== this&&(a==null||h[g].queue===a)){h[g].anim.stop(c);f=false;h.splice(g,1)}if(f||!c)d.dequeue(this,a)})}});d.each({slideDown:Ja("show"),slideUp:Ja("hide"),slideToggle:Ja("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(c,e,f){return this.animate(b,c,e,f)}});d.speed=function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off? 0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default;if(e.queue==null||e.queue===true)e.queue="fx";e.old=e.complete;e.complete=function(){d.isFunction(e.old)&&e.old.call(this);e.queue&&d.dequeue(this,e.queue)};return e};d.easing={linear:function(a){return a},swing:function(a){return 0.5-Math.cos(a*Math.PI)/2}};d.timers=[];d.fx=ba.prototype.init;d.fx.tick=function(){for(var a,b=d.timers,c=0;c<b.length;c++){a=b[c];!a()&&b[c]===a&&b.splice(c--, 1)}b.length||d.fx.stop()};d.fx.timer=function(a){if(a()&&d.timers.push(a)&&!Ra)Ra=setInterval(d.fx.tick,d.fx.interval)};d.fx.interval=13;d.fx.stop=function(){clearInterval(Ra);Ra=null};d.fx.speeds={slow:600,fast:200,_default:400};d.fx.step={};if(d.expr&&d.expr.filters)d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length};var dc=/^(?:body|html)$/i;d.fn.offset=function(a){if(arguments.length)return a===u?this:this.each(function(j){d.offset.setOffset(this, a,j)});var b,c,e,f,g,h={top:0,left:0};if(f=(e=this[0])&&e.ownerDocument){if((c=f.body)===e)return d.offset.bodyOffset(e);b=f.documentElement;if(!d.contains(b,e))return h;if(typeof e.getBoundingClientRect!=="undefined")h=e.getBoundingClientRect();e=Ab(f);f=b.clientTop||c.clientTop||0;c=b.clientLeft||c.clientLeft||0;g=e.pageYOffset||b.scrollTop;return{top:h.top+g-f,left:h.left+(e.pageXOffset||b.scrollLeft)-c}}};d.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;if(d.support.doesNotIncludeMarginInBodyOffset){b+= parseFloat(d.css(a,"marginTop"))||0;c+=parseFloat(d.css(a,"marginLeft"))||0}return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");if(e==="static")a.style.position="relative";var f=d(a),g=f.offset(),h=d.css(a,"top"),j=d.css(a,"left"),m={},o={};if((e==="absolute"||e==="fixed")&&d.inArray("auto",[h,j])>-1){o=f.position();e=o.top;j=o.left}else{e=parseFloat(h)||0;j=parseFloat(j)||0}if(d.isFunction(b))b=b.call(a,c,g);if(b.top!=null)m.top=b.top-g.top+e;if(b.left!=null)m.left=b.left-g.left+ j;"using"in b?b.using.call(a,m):f.css(m)}};d.fn.extend({position:function(){if(this[0]){var a=this[0],b=this.offsetParent(),c=this.offset(),e=dc.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0;c.left-=parseFloat(d.css(a,"marginLeft"))||0;e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent|| y.body;a&&!dc.test(a.nodeName)&&d.css(a,"position")==="static";)a=a.offsetParent;return a||y.body})}});d.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);d.fn[a]=function(e){return d.access(this,function(f,g,h){var j=Ab(f);if(h===u)return j?b in j?j[b]:j.document.documentElement[g]:f[g];if(j)j.scrollTo(!c?h:d(j).scrollLeft(),c?h:d(j).scrollTop());else f[g]=h},a,e,arguments.length,null)}});d.each({Height:"height",Width:"width"},function(a,b){d.each({padding:"inner"+ a,content:b,"":"outer"+a},function(c,e){d.fn[e]=function(f,g){var h=arguments.length&&(c||typeof f!=="boolean"),j=c||(f===true||g===true?"margin":"border");return d.access(this,function(m,o,p){if(d.isWindow(m))return m.document.documentElement["client"+a];if(m.nodeType===9){o=m.documentElement;return Math.max(m.body["scroll"+a],o["scroll"+a],m.body["offset"+a],o["offset"+a],o["client"+a])}return p===u?d.css(m,o,p,j):d.style(m,o,p,j)},b,h?f:u,h,null)}})});A.jQuery=A.$=d;typeof define==="function"&& define.amd&&define.amd.jQuery&&define("jquery",[],function(){return d})})(window);
;(function (root) { 'use strict'; /**@amsave*/ var SAVEJSON = '{"timebar":{"currTime":582,"timescale":0.12,"length":816.6666666666665},"sequences":[{"type":"css_sequ_type","data":{"name":"#head","fill":"forward","iterations":1,"selectors":["#head"],"parameters":[{"name":"transform","keys":[{"value":{"tx":12,"ty":-3.9999999999999982,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":12,"ty":-3.9999999999999982,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":12,"ty":-12.999999999999998,"tz":0,"rx":0,"ry":0,"rz":-0.044687862938096234,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":350.0000000000001,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"48.65% 62.64%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}},{"type":"css_sequ_type","data":{"name":"#rshoulder","fill":"forward","iterations":1,"selectors":["#rshoulder"],"parameters":[{"name":"transform","keys":[{"value":{"tx":57.999999999999986,"ty":32,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":57.999999999999986,"ty":32,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":57.999999999999986,"ty":32,"tz":0,"rx":0,"ry":0,"rz":-0.25968231446012213,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":291.66666666666674,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"25.53% 52.86%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":true}},{"type":"css_sequ_type","data":{"name":"#lshoulder","fill":"forward","iterations":1,"selectors":["#lshoulder"],"parameters":[{"name":"transform","keys":[{"value":{"tx":-5.999999999999993,"ty":34,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":-5.999999999999993,"ty":34,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":-5.999999999999993,"ty":34,"tz":0,"rx":0,"ry":0,"rz":0.2787647371163926,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":308.3333333333333,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"70.21% 55.71%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}},{"type":"css_sequ_type","data":{"name":"#rhand","fill":"forward","iterations":1,"selectors":["#rhand"],"parameters":[{"name":"transform","keys":[{"value":{"tx":77,"ty":-45.999999999999986,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":77,"ty":-45.999999999999986,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":72,"ty":-53.999999999999986,"tz":0,"rx":0,"ry":0,"rz":-0.16728852982993225,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":291.66666666666663,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"48.65% 87.50%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}},{"type":"css_sequ_type","data":{"name":"#lhand","fill":"forward","iterations":1,"selectors":["#lhand"],"parameters":[{"name":"transform","keys":[{"value":{"tx":-18,"ty":-45.99999999999994,"tz":0,"rx":0,"ry":0,"rz":0.01889773251816429,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":-18,"ty":-45.99999999999994,"tz":0,"rx":0,"ry":0,"rz":0.01889773251816429,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":-14,"ty":-51.99999999999994,"tz":0,"rx":0,"ry":0,"rz":0.21434860915395326,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":291.66666666666663,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"52.38% 86.45%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}},{"type":"css_sequ_type","data":{"name":"#rfoot","fill":"forward","iterations":1,"selectors":["#rfoot"],"parameters":[{"name":"transform","keys":[{"value":{"tx":44,"ty":33.00000000000001,"tz":0,"rx":0,"ry":0,"rz":0.1742096512819481,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":44,"ty":33.00000000000001,"tz":0,"rx":0,"ry":0,"rz":0.1742096512819481,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":52,"ty":-22.999999999999993,"tz":0,"rx":0,"ry":0,"rz":-0.03653758506419469,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":400,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"42.50% 73.08%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}},{"type":"css_sequ_type","data":{"name":"#lfoot","fill":"forward","iterations":1,"selectors":["#lfoot"],"parameters":[{"name":"transform","keys":[{"value":{"tx":-2,"ty":-18.999999999999986,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":0,"ease":"linear"},{"value":{"tx":-2,"ty":-18.999999999999986,"tz":0,"rx":0,"ry":0,"rz":0,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":800,"ease":"linear"},{"value":{"tx":13,"ty":37.000000000000014,"tz":0,"rx":0,"ry":0,"rz":-0.21557443118453357,"sx":1,"sy":1,"sz":1,"skewX":0,"skewY":0,"perspective":0},"time":400,"ease":"linear"}]},{"name":"transform-origin","keys":[{"value":"52.50% 68.46%","time":0,"ease":"linear"}]},{"keys":[]}],"isShowingParams":false}}]}'; var sequPlayerGens = [function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(12px,-3.9999999999999982px) "},{"offset":0.42857142857142877,"transform":"translate(12px,-12.999999999999998px) rotate(-0.044687862938096234rad) "},{"offset":0.9795918367346941,"transform":"translate(12px,-3.9999999999999982px) "}],[{"offset":0,"transform-origin":"48.65% 62.64%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#head'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(57.999999999999986px,32px) "},{"offset":0.3571428571428573,"transform":"translate(57.999999999999986px,32px) rotate(-0.25968231446012213rad) "},{"offset":0.9795918367346941,"transform":"translate(57.999999999999986px,32px) "}],[{"offset":0,"transform-origin":"25.53% 52.86%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#rshoulder'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(-5.999999999999993px,34px) "},{"offset":0.3775510204081633,"transform":"translate(-5.999999999999993px,34px) rotate(0.2787647371163926rad) "},{"offset":0.9795918367346941,"transform":"translate(-5.999999999999993px,34px) "}],[{"offset":0,"transform-origin":"70.21% 55.71%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#lshoulder'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(77px,-45.999999999999986px) "},{"offset":0.35714285714285715,"transform":"translate(72px,-53.999999999999986px) rotate(-0.16728852982993225rad) "},{"offset":0.9795918367346941,"transform":"translate(77px,-45.999999999999986px) "}],[{"offset":0,"transform-origin":"48.65% 87.50%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#rhand'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(-18px,-45.99999999999994px) rotate(0.01889773251816429rad) "},{"offset":0.35714285714285715,"transform":"translate(-14px,-51.99999999999994px) rotate(0.21434860915395326rad) "},{"offset":0.9795918367346941,"transform":"translate(-18px,-45.99999999999994px) rotate(0.01889773251816429rad) "}],[{"offset":0,"transform-origin":"52.38% 86.45%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#lhand'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(44px,33.00000000000001px) rotate(0.1742096512819481rad) "},{"offset":0.48979591836734704,"transform":"translate(52px,-22.999999999999993px) rotate(-0.03653758506419469rad) "},{"offset":0.9795918367346941,"transform":"translate(44px,33.00000000000001px) rotate(0.1742096512819481rad) "}],[{"offset":0,"transform-origin":"42.50% 73.08%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#rfoot'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }, function () { var player, animation, isInited = false, animations = [], paramKeys = [[{"offset":0,"transform":"translate(-2px,-18.999999999999986px) "},{"offset":0.48979591836734704,"transform":"translate(13px,37.000000000000014px) rotate(-0.21557443118453357rad) "},{"offset":0.9795918367346941,"transform":"translate(-2px,-18.999999999999986px) "}],[{"offset":0,"transform-origin":"52.50% 68.46%"}],[]], options = {"direction":"normal","duration":816.6666666666665,"iterations":1,"fill":"forward"}, elems = document.querySelectorAll('#lfoot'); for (var i = 0; i < elems.length; ++i) { for (var j = 0; j < paramKeys.length; ++j) { animations.push(new Animation(elems[i], paramKeys[j], options)); } } animation = new AnimationGroup(animations); return { play: function () { if (!isInited) { player = document.timeline.play(animation); isInited = true; } else { player.play(); } }, pause: function () { if (!player) { return; } player.pause(); }, seek: function (time) { if (!player) { return; } player.currentTime = time; } }; }]; root.am = root.am || {}; root.am.pageScripts = root.am.pageScripts || {}; var reg = root.am.pageScripts.amsave = { createPlayer: function (opt) { var sequencePlayers = []; sequPlayerGens.forEach(function (create) { sequencePlayers.push(create(opt)) ; }); return { play: callPlayers.bind(null, 'play'), pause: callPlayers.bind(null, 'pause'), seek: callPlayers.bind(null, 'seek'), }; function callPlayers(fnName, arg1) { sequencePlayers.forEach(function (sequencePlayer) { sequencePlayer[fnName].call(null, arg1); }); } }, saveJson: SAVEJSON, }; if (typeof define === 'function' && define.amd) { define(function () { return reg; }); } if (typeof exports === 'object') { module.exports = reg; } if (document.readyState == 'interactive' || document.readyState == 'complete') { reg.createPlayer().play(); } else { document.addEventListener('DOMContentLoaded', function () { reg.createPlayer().play(); }); } }(this));
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getStats = void 0; var api_1 = require("../api"); function getStats(options) { return api_1.RightConsents.http({ method: "GET", url: "".concat(api_1.RightConsents.config.apiRoot, "/stats"), options: options, }); } exports.getStats = getStats;
import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; Meteor.methods({ 'jitsi:updateTimeout': (rid) => { if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'jitsi:updateTimeout' }); } const room = RocketChat.models.Rooms.findOneById(rid); const currentTime = new Date().getTime(); const jitsiTimeout = new Date((room && room.jitsiTimeout) || currentTime).getTime(); if (jitsiTimeout <= currentTime) { RocketChat.models.Rooms.setJitsiTimeout(rid, new Date(currentTime + 35 * 1000)); const message = RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser('jitsi_call_started', rid, '', Meteor.user(), { actionLinks : [ { icon: 'icon-videocam', label: TAPi18n.__('Click_to_join'), method_id: 'joinJitsiCall', params: '' }, ], }); const room = RocketChat.models.Rooms.findOneById(rid); message.msg = TAPi18n.__('Started_a_video_call'); message.mentions = [ { _id:'here', username:'here', }, ]; RocketChat.callbacks.run('afterSaveMessage', message, room); } else if ((jitsiTimeout - currentTime) / 1000 <= 15) { RocketChat.models.Rooms.setJitsiTimeout(rid, new Date(jitsiTimeout + 25 * 1000)); } }, });
sap.ui.define(['sap/ui/webc/common/thirdparty/base/types/Float', 'sap/ui/webc/common/thirdparty/base/i18nBundle', 'sap/ui/webc/common/thirdparty/base/Keys', './SliderBase', './generated/templates/RangeSliderTemplate.lit', './generated/i18n/i18n-defaults'], function (Float, i18nBundle, Keys, SliderBase, RangeSliderTemplate_lit, i18nDefaults) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } var Float__default = /*#__PURE__*/_interopDefaultLegacy(Float); const metadata = { tag: "ui5-range-slider", languageAware: true, managedSlots: true, properties: { startValue: { type: Float__default, defaultValue: 0, }, endValue: { type: Float__default, defaultValue: 100, }, }, }; class RangeSlider extends SliderBase { static get metadata() { return metadata; } static get template() { return RangeSliderTemplate_lit; } static get VALUES() { return { start: "startValue", end: "endValue", }; } constructor() { super(); this._stateStorage.startValue = null; this._stateStorage.endValue = null; this.i18nBundle = i18nBundle.getI18nBundle("@ui5/webcomponents"); } get tooltipStartValue() { const stepPrecision = this.constructor._getDecimalPrecisionOfNumber(this._effectiveStep); return this.startValue.toFixed(stepPrecision); } get tooltipEndValue() { const stepPrecision = this.constructor._getDecimalPrecisionOfNumber(this._effectiveStep); return this.endValue.toFixed(stepPrecision); } get _ariaDisabled() { return this.disabled || undefined; } get _ariaLabelledByText() { return this.i18nBundle.getText(i18nDefaults.RANGE_SLIDER_ARIA_DESCRIPTION); } get _ariaHandlesText() { const isRTL = this.effectiveDir === "rtl"; const isReversed = this._areValuesReversed(); const ariaHandlesText = {}; if ((isRTL && !isReversed) || (!isRTL && isReversed)) { ariaHandlesText.startHandleText = this.i18nBundle.getText(i18nDefaults.RANGE_SLIDER_END_HANDLE_DESCRIPTION); ariaHandlesText.endHandleText = this.i18nBundle.getText(i18nDefaults.RANGE_SLIDER_START_HANDLE_DESCRIPTION); } else { ariaHandlesText.startHandleText = this.i18nBundle.getText(i18nDefaults.RANGE_SLIDER_START_HANDLE_DESCRIPTION); ariaHandlesText.endHandleText = this.i18nBundle.getText(i18nDefaults.RANGE_SLIDER_END_HANDLE_DESCRIPTION); } return ariaHandlesText; } onBeforeRendering() { if (!this.isCurrentStateOutdated()) { return; } this.notResized = true; this.syncUIAndState("startValue", "endValue"); this._updateHandlesAndRange(null); } _onfocusin(event) { if (!this._getInitialValue("endValue")) { this._setInitialValue("startValue", this.startValue); this._setInitialValue("endValue", this.endValue); } if (this.showTooltip) { this._tooltipVisibility = SliderBase.TOOLTIP_VISIBILITY.VISIBLE; } } _onfocusout(event) { if (this._isFocusing()) { this._preventFocusOut(); return; } this._setAffectedValue(null); this._setInitialValue("startValue", null); this._setInitialValue("endValue", null); if (this.showTooltip) { this._tooltipVisibility = SliderBase.TOOLTIP_VISIBILITY.HIDDEN; } } _onkeyup(event) { super._onkeyup(event); this._swapValues(); this._setAffectedValue(null); } _handleActionKeyPress(event) { if (Keys.isEscape(event)) { this.update(null, this._getInitialValue("startValue"), this._getInitialValue("endValue")); return; } this._setAffectedValueByFocusedElement(); const min = this._effectiveMin; const max = this._effectiveMax; const affectedValue = this._valueAffected; if ((Keys.isEnd(event) || Keys.isHome(event)) && !affectedValue) { this._homeEndForSelectedRange(event, Keys.isHome(event) ? "startValue" : "endValue", min, max); return; } const newValueOffset = this._handleActionKeyPressBase(event, affectedValue); if (!newValueOffset) { return; } if (affectedValue && !this._isPressInCurrentRange) { const newValue = this.constructor.clipValue(newValueOffset + this[affectedValue], min, max); this.update(affectedValue, newValue, null); } else if ((newValueOffset < 0 && this.startValue > min) || (newValueOffset > 0 && this.endValue < max)) { const newStartValue = this.constructor.clipValue(newValueOffset + this.startValue, min, max); const newEndValue = this.constructor.clipValue(newValueOffset + this.endValue, min, max); this.update(affectedValue, newStartValue, newEndValue); } } _setAffectedValueByFocusedElement() { if (this.shadowRoot.activeElement === this._startHandle) { this._setAffectedValue(RangeSlider.VALUES.start); } if (this.shadowRoot.activeElement === this._endHandle) { this._setAffectedValue(RangeSlider.VALUES.end); } if (this.shadowRoot.activeElement === this._progressBar) { this._setAffectedValue(null); } this._setIsPressInCurrentRange(!this._valueAffected); } _homeEndForSelectedRange(event, affectedValue, min, max) { const newValueOffset = this._handleActionKeyPressBase(event, affectedValue); const newStartValue = this.constructor.clipValue(newValueOffset + this.startValue, min, max); const newEndValue = this.constructor.clipValue(newValueOffset + this.endValue, min, max); this.update(null, newStartValue, newEndValue); } update(affectedValue, startValue, endValue) { if (!affectedValue) { this.updateValue("startValue", startValue); this.updateValue("endValue", endValue); this._updateHandlesAndRange(null); } else { const newValue = startValue; this._updateHandlesAndRange(newValue); this.updateValue(affectedValue, newValue); } } _onmousedown(event) { if (this.disabled || this._effectiveStep === 0) { return; } const newValue = this.handleDownBase(event); this._saveInteractionStartData(event, newValue); if (this._isPressInCurrentRange || this._handeIsPressed) { this._handeIsPressed = false; return; } this.update(this._valueAffected, newValue, null); } _saveInteractionStartData(event, newValue) { const progressBarDom = this.shadowRoot.querySelector(".ui5-slider-progress").getBoundingClientRect(); this._startValueAtBeginningOfAction = this.startValue; this._endValueAtBeginningOfAction = this.endValue; this._initialPageXPosition = this.constructor.getPageXValueFromEvent(event); this._pressTargetAndAffectedValue(this._initialPageXPosition, newValue); this._initialStartHandlePageX = this.directionStart === "left" ? progressBarDom.left : progressBarDom.right; } _handleMove(event) { event.preventDefault(); if (this.disabled || this._effectiveStep === 0) { return; } if (!this._isPressInCurrentRange) { this._updateValueOnHandleDrag(event); return; } this._updateValueOnRangeDrag(event); } _updateValueOnHandleDrag(event) { const newValue = this.constructor.getValueFromInteraction(event, this._effectiveStep, this._effectiveMin, this._effectiveMax, this.getBoundingClientRect(), this.directionStart); this.update(this._valueAffected, newValue, null); } _updateValueOnRangeDrag(event) { const currentPageXPos = this.constructor.getPageXValueFromEvent(event); const newValues = this._calculateRangeOffset(currentPageXPos, this._initialStartHandlePageX); this._setAffectedValue(null); this.update(null, newValues[0], newValues[1]); } _handleUp() { if (this.startValue !== this._startValueAtBeginningOfAction || this.endValue !== this._endValueAtBeginningOfAction) { this.fireEvent("change"); } this._swapValues(); this._setAffectedValueByFocusedElement(); this._setAffectedValue(null); this._startValueAtBeginningOfAction = null; this._endValueAtBeginningOfAction = null; this._setIsPressInCurrentRange(false); this.handleUpBase(); } _pressTargetAndAffectedValue(clientX, value) { const startHandle = this.shadowRoot.querySelector(".ui5-slider-handle--start"); const endHandle = this.shadowRoot.querySelector(".ui5-slider-handle--end"); const handleStartDomRect = startHandle.getBoundingClientRect(); const handleEndDomRect = endHandle.getBoundingClientRect(); const inHandleStartDom = clientX >= handleStartDomRect.left && clientX <= handleStartDomRect.right; const inHandleEndDom = clientX >= handleEndDomRect.left && clientX <= handleEndDomRect.right; if (inHandleEndDom || inHandleStartDom) { this._handeIsPressed = true; } if (inHandleEndDom || value > this.endValue) { this._setAffectedValue(RangeSlider.VALUES.end); } if (inHandleStartDom || value < this.startValue) { this._setAffectedValue(RangeSlider.VALUES.start); } const isNewValueInCurrentRange = value >= this._startValueAtBeginningOfAction && value <= this._endValueAtBeginningOfAction; this._setIsPressInCurrentRange(!(this._valueAffected || this._handeIsPressed) ? isNewValueInCurrentRange : false); } _setAffectedValue(valuePropAffectedByInteraction) { this._valueAffected = valuePropAffectedByInteraction; if (this._areValuesReversed()) { this._setValuesAreReversed(); } } _setIsPressInCurrentRange(isPressInCurrentRange) { this._isPressInCurrentRange = isPressInCurrentRange; } focusInnerElement() { const isReversed = this._areValuesReversed(); const affectedValue = this._valueAffected; if (this._isPressInCurrentRange || !affectedValue) { this._progressBar.focus(); } if ((affectedValue === RangeSlider.VALUES.start && !isReversed) || (affectedValue === RangeSlider.VALUES.end && isReversed)) { this._startHandle.focus(); } if ((affectedValue === RangeSlider.VALUES.end && !isReversed) || (affectedValue === RangeSlider.VALUES.start && isReversed)) { this._endHandle.focus(); } } _calculateRangeOffset(currentPageXPos, initialStartHandlePageXPos) { if (this._initialPageXPosition === currentPageXPos) { return [this.startValue, this.endValue]; } const min = this._effectiveMin; const max = this._effectiveMax; const selectedRange = this.endValue - this.startValue; let startValue = this._calculateStartValueByOffset(currentPageXPos, initialStartHandlePageXPos); startValue = this.constructor.clipValue(startValue, min, max - selectedRange); return [startValue, startValue + selectedRange]; } _calculateStartValueByOffset(currentPageXPos, initialStartHandlePageXPos) { const min = this._effectiveMin; const max = this._effectiveMax; const step = this._effectiveStep; const dom = this.getBoundingClientRect(); let startValue; let startValuePageX; let positionOffset; if (currentPageXPos > this._initialPageXPosition) { positionOffset = currentPageXPos - this._initialPageXPosition; startValuePageX = initialStartHandlePageXPos + positionOffset; startValue = this.constructor.computedValueFromPageX(startValuePageX, min, max, dom, this.directionStart); startValue = this.constructor.getSteppedValue(startValue, step, min); } else { positionOffset = this._initialPageXPosition - currentPageXPos; startValuePageX = initialStartHandlePageXPos - positionOffset; startValue = this.constructor.computedValueFromPageX(startValuePageX, min, max, dom, this.directionStart); startValue = this.constructor.getSteppedValue(startValue, step, min); } return startValue; } _updateHandlesAndRange(newValue) { const max = this._effectiveMax; const min = this._effectiveMin; const prevStartValue = this.getStoredPropertyState("startValue"); const prevEndValue = this.getStoredPropertyState("endValue"); const affectedValue = this._valueAffected; if (affectedValue === RangeSlider.VALUES.start) { this._selectedRange = (prevEndValue - newValue) / (max - min); this._firstHandlePositionFromStart = ((newValue - min) / (max - min)) * 100; } else if (affectedValue === RangeSlider.VALUES.end) { this._selectedRange = ((newValue - prevStartValue)) / (max - min); this._secondHandlePositionFromStart = ((newValue - min) / (max - min)) * 100; } else { this._selectedRange = ((this.endValue - this.startValue)) / (max - min); this._firstHandlePositionFromStart = ((this.startValue - min) / (max - min)) * 100; this._secondHandlePositionFromStart = ((this.endValue - min) / (max - min)) * 100; } } _swapValues() { const affectedValue = this._valueAffected; if (affectedValue === RangeSlider.VALUES.start && this.startValue > this.endValue) { const prevEndValue = this.endValue; this.endValue = this.startValue; this.startValue = prevEndValue; this._setValuesAreReversed(); this.focusInnerElement(); } if (affectedValue === RangeSlider.VALUES.end && this.endValue < this.startValue) { const prevStartValue = this.startValue; this.startValue = this.endValue; this.endValue = prevStartValue; this._setValuesAreReversed(); this.focusInnerElement(); } } _setValuesAreReversed() { this._reversedValues = !this._reversedValues; } _areValuesReversed() { return this._reversedValues; } get _startHandle() { return this.shadowRoot.querySelector(".ui5-slider-handle--start"); } get _endHandle() { return this.shadowRoot.querySelector(".ui5-slider-handle--end"); } get _progressBar() { return this.shadowRoot.querySelector(".ui5-slider-progress"); } get styles() { return { progress: { "transform": `scaleX(${this._selectedRange})`, "transform-origin": `${this.directionStart} top`, [this.directionStart]: `${this._firstHandlePositionFromStart}%`, }, startHandle: { [this.directionStart]: `${this._firstHandlePositionFromStart}%`, }, endHandle: { [this.directionStart]: `${this._secondHandlePositionFromStart}%`, }, tickmarks: { "background": `${this._tickmarks}`, }, label: { "width": `${this._labelWidth}%`, }, labelContainer: { "width": `100%`, [this.directionStart]: `-${this._labelWidth / 2}%`, }, tooltip: { "visibility": `${this._tooltipVisibility}`, }, }; } static async onDefine() { await i18nBundle.fetchI18nBundle("@ui5/webcomponents"); } } RangeSlider.define(); return RangeSlider; });
import io, os, sys, types import nbformat from IPython.core.interactiveshell import InteractiveShell # This tool allows importing .ipynb files in other ipthon notebooks. # Simply type 'import thing' and it will look for thing.ipynb and # import it. def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path class NotebookLoader(object): """Module Loader for IPython Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing IPython notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = nbformat.read(f, nbformat.NO_CONVERT) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.dict()["cells"]: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod class NotebookFinder(object): """Module finder that locates IPython Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key] sys.meta_path.append(NotebookFinder())
import url from 'url'; import 'isomorphic-fetch'; function reject(val) { throw new Error(val); } function status(response) { if (response.status >= 200 && response.status < 300) return response; return response.json().then((data, err) => { if (err) { return response.text().then(reject); } return reject(data.error); }); } function json(response) { if (response.status === 204) return {}; return response.json(); } class Core { constructor(apiRoot) { this.apiRoot = apiRoot; if (typeof localStorage !== 'undefined') { this.token = localStorage.getItem('jwt'); } } request(resource, method, body) { return fetch(url.resolve(this.apiRoot, resource), { method, headers: { Authorization: `Bearer ${this.token}`, Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(body), }) .then(status) .then(json); } get(resource) { return this.request(resource, 'get'); } post(resource, body) { return this.request(resource, 'post', body); } put(resource, body) { return this.request(resource, 'put', body); } delete(resource) { return this.request(resource, 'delete'); } } export default Core;
(this["webpackJsonpergo-template"]=this["webpackJsonpergo-template"]||[]).push([[5],{248:function(e,o){function n(e){var o=new Error("Cannot find module '"+e+"'");throw o.code="MODULE_NOT_FOUND",o}n.keys=function(){return[]},n.resolve=n,e.exports=n,n.id=248}}]); //# sourceMappingURL=5.533f67b2.chunk.js.map
import pandas as pd import tkinter as tk from tkinter import filedialog from data_structures import experiment import os Tk = tk.Tk() Tk.withdraw() def ask_path(): return filedialog.asksaveasfile(mode='w').name def df_to_excel(df, sheet_name='Sheet1'): ''' Uses pandas to always return a .xlsx file of the given df Giving the save name a file extension results in multiple files being saved ''' where = filedialog.asksaveasfile(mode='wb', filetypes=[('Microsoft Excel Worksheet', '.xlsx')], defaultextension='.xlsx') save_name = where.name if save_name[-5:] != '.xlsx': save_name = str(save_name + '.xlsx') with pd.ExcelWriter(save_name) as writer: df.to_excel(writer, engine='openpyxl', sheet_name=sheet_name) def cary630(filename): ''' Given path, shapes .CSV data output by Aligent's Cary 630 Spectrometer (managed by MicroLab) to a usable dataframe with integer index ''' df = pd.read_csv(filename, header=4, names=['Wavenumber', 'Absorbance']) return df def load_experiment(filetype: str = '.csv') -> experiment: ''' :param filetype: .xlsx or .csv :return: experiment object Creates and experiment object for a previously exported experiment. If filetype = .xlsx, the excel file must have sheets named 'data' and 'params' If filetype = .csv, two CSVs in the selected folder must be named 'data' and 'params', respecitively ''' if filetype == '.xlsx': file = filedialog.askopenfilename(filetypes=[('Excel Worksheet', '.xlsx')]) x = pd.ExcelFile(file, engine='openpyxl') sheets = {} for sheet in x.sheet_names: df = pd.read_excel(file, sheet_name=sheet, index_col=0) sheets[str(sheet)] = df data = sheets['data'] del sheets['data'] params = sheets['params'] del sheets['params'] opt = [] for sheet in sheets.keys(): opt.append(sheets[sheet]) exp = experiment(data, params, opt) return exp elif filetype == '.csv': dirname = filedialog.askdirectory(title='Select a folder of CSV files') filenames = os.listdir(dirname) data = pd.read_csv(dirname+'/data.csv', index_col=0) params = pd.read_csv(dirname + '/params.csv', index_col=0) filenames.remove('data.csv') filenames.remove('params.csv') opt = [] for file in filenames: opt.append( pd.read_csv(dirname+'/'+file, index_col=0) ) exp = experiment(data, params, opt) return exp # Testing df # df = pd.DataFrame({ # 1: ['one', 'four', 'seven'], # 2: ['two', 'five', 'eight'], # 3: ['three', 'six', 'nine'] # }, index=[0, 1, 2]) # # df_to_excel(df)
import React from "react" import { documentToReactComponents } from "@contentful/rich-text-react-renderer" const SinglePost = ({ post }) => { // Embedded images images in our blog post const options = { renderNode: { "embedded-asset-block": node => { const alt = node.data.target.fields.file["en-US"].title const url = node.data.target.fields.file["en-US"].url return <img alt={alt} src={url} /> }, }, } // END ... Embedded images images in our blog post return ( <article> <h2> {post.title} </h2> <span> {post.dp} </span> <div> {documentToReactComponents(post.body.json, options)} </div> </article> ) } export default SinglePost